What is an MCP server and how does Model Context Protocol work
An MCP server (Model Context Protocol server) is a lightweight adapter program that connects AI applications to working tools, read-only data, and prompt templates through one open standard. Instead of writing separate glue code for every combination of model and database or API, you wrap a capability once so any compliant client can read its schema and call it. Below, we cover the fundamentals: what is an MCP server, how does the 2026 stateless specification work, and which security risks should you close before production?
Protocol vs. server: Model Context Protocol (MCP) defines JSON-RPC 2.0 messages, transports, and authorization; an MCP server implements those rules around your database, local utility, or external API.
Open governance: Anthropic introduced MCP in November 2024 and donated the specification in December 2025 to the Linux Foundation's Agentic AI Foundation (AAIF), co-founded with Block and OpenAI.
Three roles and three core elements: an AI Host (Claude Desktop, Claude Code, Cursor, VS Code, or ChatGPT) opens a 1:1 Client connection per server, while the server exposes model-controlled Tools, app-controlled Resources, and user-controlled Prompts.
Stateless 2026 spec (2026-07-28): the July 2026 revision removed sessions and the initialize handshake, adding mandatory server/discover, the subscriptions/listen stream, Multi Round-Trip Requests (MRTR), and HTTP routing headers (Mcp-Method and Mcp-Name).
What is an MCP server and why AI workflows need one
On its own, a language model only works with text inside its context window and patterns stored in its weights. It cannot query PostgreSQL or check live storefront stock unless an external program runs that request and sends back structured data.
The word “server” often trips teams up early on. Many engineers hear it and picture a rack in a data center or a heavy backend. In MCP, it is simply a protocol role, closer to a driver or adapter. Some MCP servers run locally as lightweight child processes spawned by a code editor or desktop chat app, while others sit behind an HTTPS URL so an entire team or cloud AI host can share one toolset.
Before MCP, wiring N AI apps to M services meant maintaining N x M custom connectors that broke whenever an SDK changed. One shared standard collapses that matrix to N + M: you maintain one MCP server per service, and any compatible host reads its schemas directly. After moving to the AAIF in December 2025 (backed by AWS, Cloudflare, Google, Microsoft, and Bloomberg), the ecosystem grew from 10,000+ servers at launch to over 16,000 on PulseMCP and 32,000+ on Glama in 2026.
How an MCP server works: Host, Client, and Server roles
So what is an MCP server in practice? You have to look at the full chain. Every deployment splits responsibilities across three components exchanging JSON-RPC 2.0 messages. The server never calls an LLM directly; it responds to client requests and talks to the underlying system it wraps.
MCP Host: the user-facing AI application (Claude Desktop, Claude Code, Cursor, VS Code, or a custom agent runtime). It keeps conversation history, connects servers, asks for confirmation before risky calls, and decides which outputs enter model context.
MCP Client: a protocol connector inside the Host, created strictly 1:1 per server. If GitHub, PostgreSQL, and a scraper are connected at the same time, the Host runs three isolated clients so credentials and errors stay separated.
MCP Server: the adapter on the connected service side. It publishes available schemas, validates arguments against JSON Schema, runs the database query or API call, and returns structured output.

Permissions stay cleanly separated across layers: the model only proposes a tool call, the Host asks the user to approve it, and the MCP server enforces real access rights in the target system.
Core server primitives: Tools, Resources, and Prompts
The specification divides server capabilities into three core primitives based on who triggers the call. That keeps read-only reference data separate from operations that modify state.
Primitive | Triggered by | Core JSON-RPC methods | Examples | Rules in spec 2026-07-28 |
Tools | Model (decides when to invoke) | tools/list, tools/call | run_sql_query, create_github_issue, run_search | Defined with inputSchema and outputSchema (JSON Schema 2020-12); return structuredContent plus a plain-text copy. Hints like readOnlyHint and destructiveHint cannot be trusted without checking the server itself. |
Resources | Application (Host attaches context) | resources/list, resources/templates/list, resources/read, subscriptions/listen | file:///repo/README.md, db://schema/orders, weather://forecast/{city} | Read-only URI data with MIME types; support cache hints (ttlMs, cacheScope) and update subscriptions. |
Prompts | User (slash commands or UI buttons) | prompts/list, prompts/get | /audit-pull-request, /incident-triage, /price-diff | Reusable templates with string arguments and autocomplete via completion/complete. |
In practice, exposing 200 raw REST routes as 200 individual tools backfires: model selection accuracy drops, and bloated schemas burn context tokens before the first user question. Group low-level endpoints into compact, task-focused tools instead.
Moving to a stateless core in MCP specification 2026-07-28
Tutorials from 2025 describe MCP as a stateful protocol that opens with an initialize handshake and carries an Mcp-Session-Id header. That applies to legacy revisions (2024-11-05 through 2025-11-25).
On July 28, 2026, revision 2026-07-28 shifted the protocol core to a stateless model. Servers now scale behind load balancers and in serverless runtimes without shared session storage. When a task still needs state across steps, the server issues an explicit handle and the model passes it back as a regular argument.
No handshake or session ID: initialize, notifications/initialized, and Mcp-Session-Id were removed. Requests pass io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities inside _meta (mirrored in the MCP-Protocol-Version HTTP header), while incompatible versions return error -32022 (UnsupportedProtocolVersion).
Mandatory server/discover method: lets a client inspect supported versions, server identity, and capabilities in a single call.
Unified subscriptions/listen stream: an on-demand HTTP POST stream replaced the legacy HTTP GET stream and resources/subscribe, tagging events with io.modelcontextprotocol/subscriptionId.
Multi Round-Trip Requests (MRTR): when a tool needs mid-call clarification from a person, the server returns resultType: "input_required" alongside inputRequests and a signed requestState token. The client collects the reply and retries with inputResponses.
API gateway headers and caching: Streamable HTTP POST calls mirror key parameters into Mcp-Method, Mcp-Name, and custom Mcp-Param-* headers (via x-mcp-header). Gateways and WAFs can route or rate-limit tool calls without parsing JSON, and replies now support ttlMs and cacheScope cache hints.
Deprecations and Tasks extension: 2026-07-28 deprecated Roots, Sampling, Logging, and OAuth Dynamic Client Registration (RFC 7591) with a minimum 12-month window (earliest removal 2027-07-28). Legacy HTTP+SSE (deprecated since 2025-03-26) stays for at least three months after SEP-2596 reaches Final, and long-running async jobs moved to io.modelcontextprotocol/tasks (tasks/get, tasks/update).
Many 2025 servers in production still speak 2025-11-25, so major AI hosts keep backward compatibility active while new remote deployments target 2026-07-28.
Local stdio vs. remote Streamable HTTP: what is an MCP server under the hood
Debates over whether an MCP server is a local script or a hosted web service almost always come down to transport. Transport handles JSON-RPC 2.0 delivery without changing protocol behavior. With HTTP+SSE deprecated, new projects choose between two options:
Dimension | Local stdio transport | Remote Streamable HTTP transport |
Deployment | Client spawns a local child process | Standalone HTTP/HTTPS service at one URL (e.g., https://api.example.com/mcp) |
Message format | Newline-delimited JSON-RPC over stdin and stdout | HTTP POST returning application/json or a request-scoped SSE stream |
Authorization | Local environment variables (no OAuth over stdio) | OAuth 2.1 Resource Server (Bearer token), RFC 9728, CIMD, RFC 8707 audience binding |
Cancellation | Client sends notifications/cancelled with the request ID | Client closes the HTTP/SSE response stream |
Common mistakes | Writing logs to stdout breaks JSON-RPC parsing (log to stderr) | Binding local HTTP to 0.0.0.0 instead of 127.0.0.1, or skipping Origin validation (return 403 Forbidden against DNS rebinding) |
Where it fits | Local Git, disk files, solo IDE workflows | Team services, SaaS endpoints, cloud hosts, Docker stacks like Yozh Scraper |
In 2026-07-28, Streamable HTTP removed SSE resumability via Last-Event-ID. If a connection drops, the in-flight call resets and retries from scratch, so design write tools to be idempotent.
What is an MCP server vs. REST API, function calling, and RAG
These layers solve different architectural jobs and usually work alongside one another rather than replacing each other.
Layer | Primary job | Who drives calls | How it relates to MCP | When to skip MCP |
REST / GraphQL API | Service-to-service data exchange and business logic | Fixed client code calling documented routes | Most MCP servers wrap an existing API into authorized tool calls | Predictable sync jobs, webhooks, or cron tasks without LLM logic |
Native function calling | Model capability to emit structured JSON arguments | Hardwired inside one app's provider API | MCP standardizes discovery and reuse; under the hood, the Host still runs model function calling | Small single-app prototypes with 2 to 5 private functions |
RAG (vector search) | Indexing documents and retrieving relevant passages | Retrieval pipeline runs ahead of generation | Complementary: an MCP server can expose search_docs or Resources over a vector store | Static knowledge-base Q&A with no live actions |
MCP server | Unified boundary for live tools, data, and prompts | Any compliant Host reads tools/list so the model selects actions dynamically | Reusable adapter between AI hosts and internal systems | Worth adding when multiple hosts or teams share the same tools |
Minimal MCP server code examples (2026 SDKs)
In code terms, the shortest answer to “what is an MCP server?” takes roughly 25 lines around an HTTP client. Official Tier-1 SDKs cover TypeScript, Python, Go, C#, Rust, and Ruby. Both Python and TypeScript shipped breaking releases in 2026, so check your imports before copying older snippets.
Python example (MCP SDK 2.x)
Python MCP SDK 2.x (mcp>=2,<3, Python 3.10+) renamed FastMCP to MCPServer under mcp.server.mcpserver. Internally, SDK 2.x moved to httpx2, so httpx is no longer installed automatically - list it explicitly in your dependencies for outbound HTTP requests. Synchronous def handlers now execute on worker threads instead of blocking the event loop.
import os
from urllib.parse import urlparse
import httpx
from mcp.server.mcpserver import MCPServer
mcp = MCPServer("regional-page-checker")
@mcp.tool()
async def fetch_headers(url: str) -> dict[str, str | int]:
"""Fetch HTTP status and content-type headers via an optional proxy."""
parsed = urlparse(url)
if parsed.scheme not in ("http", "https") or not parsed.netloc:
raise ValueError("URL must start with http:// or https://")
proxy_url = os.environ.get("CYBERYOZH_PROXY_URL") or None
async with httpx.AsyncClient(proxy=proxy_url, timeout=15.0) as client:
response = await client.head(url, follow_redirects=True)
return {
"url": str(response.url),
"status_code": response.status_code,
"content_type": response.headers.get("content-type", ""),
}
if __name__ == "__main__":
mcp.run() # Runs over stdio by defaultTypeScript example (@modelcontextprotocol/server)
In 2026, the TypeScript SDK split into standalone @modelcontextprotocol/server and @modelcontextprotocol/client packages alongside Streamable HTTP adapters (@modelcontextprotocol/node, express, fastify, hono) and Standard Schema support, including Zod v4. The schema below accepts http and https URLs only.
import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
const server = new McpServer({ name: 'status-check-server', version: '1.0.0' });
server.registerTool(
'check_endpoint',
{
description: 'Send a read-only HEAD request and return the HTTP status code',
inputSchema: z.object({
url: z.url({ protocol: /^https?$/ }),
}),
},
async ({ url }) => {
const res = await fetch(url, {
method: 'HEAD',
signal: AbortSignal.timeout(10_000),
});
return {
content: [{ type: 'text', text: `${url} returned HTTP ${res.status}` }],
};
}
);
async function main() {
await server.connect(new StdioServerTransport());
}
main().catch((err) => {
console.error('MCP server startup failed:', err);
process.exit(1);
});Writing fatal errors to console.error (stderr) keeps JSON-RPC messages on stdout intact.
Connecting a ready-made Streamable HTTP server
For public web data collection, you do not need to build a browser wrapper from scratch. The MIT-licensed open-source Yozh Scraper repository runs Playwright workers over Redis/taskiq and exposes two Streamable HTTP endpoints:
http://localhost:8000/mcp - 21 allowlisted search and scraping tools (including run_search and get_queue_stats);
http://localhost:8001/mcp - crawler methods (create_crawl, get_crawl, get_crawl_results, and cancel_crawl).
Connecting both endpoints in ~/.claude/settings.json takes six lines:
{
"mcpServers": {
"yozh-scraper": { "type": "http", "url": "http://localhost:8000/mcp" },
"open-crawler": { "type": "http", "url": "http://localhost:8001/mcp" }
}
}If an agent needs to click elements and fill out forms through a browser accessibility tree directly from your terminal, walk through our Playwright MCP with Claude Code setup guide.
Authorization, access rights, and MCP security risks
Before shipping to production, revisit one practical angle of “what is an MCP server?”: every server holds real downstream credentials while an agent builds tool chains at runtime. Text rules in a system prompt cannot enforce access control - put those boundaries in the protocol and server code.
Remote HTTP servers operate as OAuth 2.1 Resource Servers:
unauthenticated requests receive 401 Unauthorized with a WWW-Authenticate header pointing to Protected Resource Metadata (RFC 9728);
clients register through Client ID Metadata Documents (CIMD) instead of deprecated RFC 7591, complete PKCE with an RFC 8707 Resource Indicator binding token audience to that exact URL, and verify iss (RFC 9207);
servers reject tokens issued for a foreign audience to block token passthrough.
Research and real-world cases from 2025-2026 point to five threat classes worth addressing before production:
Threat class | How it works | Documented cases and tests (2025-2026) | Controls (OWASP MCP) |
Tool poisoning (OWASP MCP03 beta) | Hidden instructions inside tool descriptions or schemas enter model context before the user prompt | NeuralTrust review of Shaikh & Montaruli (Nov 2026: 9,720 tests, 12 frameworks, 18 models): 22.9% success, 12.1% credential leaks; ShareLock (Liu et al., June 2026): >90% across four multi-tool setups on two clients | Audit full untruncated tool definitions, set additionalProperties: false, and scan servers with mcp-scan |
Rug pulls & package compromise | A server passes initial review, then quietly alters descriptions, annotations, or code on update | postmark-mcp 1.0.16 (Sept 2025, covert BCC), SANDWORM_MODE / McpInject (Socket, Feb 2026), @dforge-core/dforge-mcp 0.2.21 (CloudSEK/Orca, Sept 2026) | Pin a hash of the full tool definition (description, schemas, annotations) and halt startup on mismatch |
Cross-server shadowing | An untrusted server's tool description influences how the model calls a trusted server on the same Host | Invariant Labs (2025) and Cloud Security Alliance (May 2026) | Separate billing and PII servers from third-party servers across distinct Host profiles |
Indirect prompt injection (OWASP MCP06 beta) | Hostile text inside a web page, email, or ticket triggers unwanted follow-up tool calls | Invariant Labs (May 2025): hidden text in a public GitHub issue copied private repo files into a public PR | Treat tool outputs as untrusted, verify caller identity server-side, and require approval for writes (see browser agent prompt injection and session risks) |
Exposed endpoints & stdio command execution | Unauthenticated HTTP endpoints or unverified launch commands in external configs | Knostic (July 2025): 1,862 public servers listing tools without auth; OX Security (April 2026): command execution through untrusted stdio configs | Sandbox local servers at the OS level (bare chroot is not enough), bind local HTTP to 127.0.0.1, and review stdio commands |
When web-connected MCP servers need proxy routing
Local MCP servers reading files on disk or querying internal SQL tables need no proxy setup. Things change once tools reach the public web to collect catalogs and prices, verify regional search results, or refresh a RAG index.
Parallel requests from one cloud IP quickly hit HTTP 403 and 429 limits or return prices for the wrong region. Configure routing inside the server's HTTP client or browser worker (using environment variables like CYBERYOZH_PROXY_URL above, never in the LLM prompt) with dedicated MCP server proxy routing:
For multi-country data collection: use rotating residential proxies (100M+ IPs across 195+ countries, pay-as-you-go GB billing with automatic traffic rollover and sticky sessions up to 24 hours).
For trust-sensitive storefronts and multi-threaded search collection: use LTE/5G mobile proxies with unlimited traffic on real carrier networks.
Verify outbound addresses through the CyberYozh App IP Fraud Score checker before launching traffic, or read how network proxies support AI agents to see how proxy layers pair with LLM gateways.