08E.1 The Model Context Protocol (MCP)
08A.2 built the agent loop: call the model, run its tool calls, feed the results back. 08A.6 showed how to design tools a model can use. Both lessons ended at the same boundary: the tools were plain Python functions you wrote yourself. The Model Context Protocol (MCP) is the open standard that lets your agent loop reach tools, data and prompts that somebody else already built — a GitHub server, a Postgres server, a browser server — without you writing a bespoke integration for each one. This lesson covers what MCP is, exactly what goes over the wire, how to build a server with the official Python SDK, how to plug MCP into your agent (including the provider-native support each of the big four APIs now offers), and the security model you must understand before you let a model loose on somebody else's tools.
The protocol moved fast. The lesson targets the 2026-07-28 revision of the specification — the current stable revision as of November 2026 — which removed the connection handshake and made every request self-contained. Where the older design still matters (most servers and clients in the wild speak it), the lesson says so and shows the difference.
What you'll learn
- The problem MCP solves (N integrations × M clients), who the parties are (host, client, server), and what MCP is not
- The protocol as of the
2026-07-28revision: JSON-RPC 2.0 messages,server/discover, per-request capabilities, and the no-handshake lifecycle - The three server primitives — tools, resources (and resource templates) and prompts — and the client-side features (elicitation, plus the now-deprecated sampling, roots and protocol logging)
- Transports: stdio and Streamable HTTP (and why the legacy HTTP+SSE transport is deprecated)
- Tool results: content blocks,
structuredContent/outputSchema,isError, and the behavioural annotations (readOnlyHint,destructiveHint,idempotentHint,openWorldHint) - Cross-cutting utilities: pagination, caching hints, progress, cancellation, change notifications via
subscriptions/listen, and the Multi Round-Trip Requests (MRTR) pattern - Building a complete MCP server in Python with the official
mcpSDK (MCPServer), including typed schemas, structured output, progress, logging, lifespan state, elicitation (asking the user mid-call) and in-memory tests - Using MCP from your agent: the SDK
Client, mapping MCP tools onto the provider tool formats from lesson 03.5, and each provider's native MCP support (OpenAI, Anthropic, Gemini, OpenRouter) - Where people actually use MCP: desktop apps, IDEs and chat products
- The security model: the threat model (tool poisoning, rug pulls, confused deputy, token passthrough), the OAuth 2.1-based authorization spec, and a hands-on checklist
- The ecosystem: the official registry, popular servers, and an honest decision table for when MCP beats plain function tools, OpenAPI wrappers or provider built-ins
- The official extensions (Tasks for long-running work, MCP Apps for inline UI, Skills over MCP), what the Python SDK implements today, and how to do long-running work without them
What you don't need
- API keys. Every part has something you can run for free: pure-Python protocol pieces over in-memory streams, an MCP server exercised by the SDK's in-memory client, and config you can read. Samples that need a hosted provider are labelled illustrative.
- A running MCP host. You can build and test a server with
Client(mcp)entirely in memory; connecting Claude Desktop or Cursor is optional. - Deep OAuth knowledge. The authorization section explains the flow you need; implementing an authorization server is out of scope (see Module 12).
Setup
The pure-protocol samples need only the standard library. The SDK samples need Python 3.11+ and the official MCP Python SDK. If you already have a project folder from earlier lessons, reuse it — the module's lessons picked different names and any of them works; otherwise run uv init tools-agents --bare --python 3.13 && cd tools-agents first (see lesson 03.1, Part 4 for the full setup and the .env file), then add:
uv add "mcp[cli]" pytest anyio
# or: pip install "mcp[cli]" pytest anyiomcp is the official Python SDK (it requires Python 3.10+). The [cli] extra adds the mcp command-line tool (mcp dev, mcp run, mcp install) used throughout the lesson. These samples were written and checked against mcp 2.3.0 as of November 2026. v2 landed on 2026-07-28 and renamed the high-level server class, so a plain install gives you v2 and code written against v1 (FastMCP) will not import — 3.1 explains the mapping. If a later major release changes the API again, the SDK's migration guide (linked in the references) is the authority.
Samples that call a hosted LLM API additionally need the module's provider SDKs and keys (OPENAI_API_KEY and ANTHROPIC_API_KEY in .env, plus the optional GEMINI_API_KEY and OPENROUTER_API_KEY); see the shared setup in lesson 03.1.
What you must be able to do after this lesson#
- Explain the host, client and server roles in MCP
- Describe the tools, resources and prompts primitives
- Choose between the stdio and Streamable HTTP transports
- Build an MCP server in Python with typed tools
- Connect an agent to an MCP server and map its tools to provider formats
- Name the main MCP security threats and their mitigations
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Just add the GitHub MCP server to the agent." | 1.1 The N×M problem |
| "MCP is just a protocol, not an agent framework." | 1.2 What MCP is — and what it isn't |
| "Which spec version are we targeting?" | 1.4 The spec, and the big 2026 change |
| "What's the difference between a tool, a resource and a prompt?" | 2.3 The three server primitives |
"Why is there no initialize call anymore?" |
2.2 Lifecycle without a handshake |
| "The server needs to ask the user something mid-tool-call." | 2.4 Client features and MRTR |
| "How do I implement that question in the Python SDK?" | 3.6 Asking the user mid-call |
| "stdio or Streamable HTTP?" | 2.6 Transports |
| "How do I return structured data from a tool?" | 2.7 Tool results: content, structuredContent and outputSchema |
| "How do I test an MCP server?" | 3.4 Testing with the in-memory client |
| "Can Claude call my MCP server directly?" | 4.3 Provider-native MCP support |
| "Is this MCP server safe to connect?" | Part 5: Security and authorization |
| "When is MCP worth the indirection?" | 6.3 MCP vs the alternatives |
Part 1: What MCP is and why it exists#
1.1 The N×M problem#
Every agent you build needs tools. In 08A.2 those tools were functions you wrote: lookup_order, search_docs, create_ticket. That works until the list grows — you want GitHub, Postgres, Slack, your CRM, a browser, a filesystem — and until more than one agent needs them. Before MCP, each pairing needed custom work:
- Every tool provider had to write a bespoke integration for every agent framework and every LLM API. A GitHub integration for your LangGraph agent, another for your CrewAI agent, another for the raw OpenAI loop, another for Claude Desktop.
- Every agent builder had to write a bespoke client for every service: the GitHub API client, the Slack client, the database driver wrapper — each with its own auth, pagination, error shapes and rate limits.
With N tool providers and M agent hosts, you get up to N × M integrations. MCP collapses that: each provider writes one MCP server, each host writes one MCP client, and any server works with any client. This is the same move the Language Server Protocol (LSP) made for code editors in 2016: before LSP, every editor needed a plugin for every language; after it, language servers and editors only needed to speak one protocol. MCP's own documentation makes the analogy explicit.
1.2 What MCP is — and what it isn't#
MCP is an open protocol for connecting LLM applications to external context and capabilities. Concretely it defines:
- A message format: JSON-RPC 2.0 messages between a client and a server.
- A set of primitives the server can expose: tools (functions the model may call), resources (data the application may attach as context) and prompts (templated messages the user may invoke).
- A set of client features the client may offer back: elicitation (asking the user for input mid-request), and — now deprecated — sampling (the server asking the client to run an LLM call) and roots (the client telling the server which directories matter).
- Transports: how the bytes move — a local subprocess over stdio, or HTTP for remote servers.
- An authorization framework for HTTP transports, built on OAuth 2.1.
What MCP is not:
- Not an agent framework. It has no loops, no planning, no memory, no orchestration. Your agent loop from 08A.2 still does all of that; MCP is one of the tool sources the loop can draw from. Frameworks like LangGraph or the OpenAI Agents SDK use MCP; they are not MCP.
- Not an authentication system by itself. The spec defines how an HTTP server declares and validates OAuth tokens, but it doesn't issue identities, manage users, or decide your permission model. Those remain your job (and Module 12's).
- Not a guarantee of safety. A connected MCP server can expose tools that read your files, spend money or delete data. The protocol carries warnings and hints; the trust decisions are yours (Part 5).
- Not a replacement for good tool design. Everything in 08A.6 — descriptions the model can act on, tight schemas, concise results — applies with full force to MCP tools. MCP standardizes the plumbing; it does not make bad tools good.
1.3 Who the parties are#
The architecture has three roles, and keeping them straight prevents most confusion:
flowchart LR
subgraph hostproc ["Host process (the application the user talks to)"]
H["Host<br/>e.g. Claude Desktop, your agent app"]
C1["MCP client 1"]
C2["MCP client 2"]
C3["MCP client 3"]
H --> C1 & C2 & C3
end
subgraph local ["This machine"]
S1["MCP server 1<br/>e.g. filesystem"]
S2["MCP server 2<br/>e.g. your orders DB"]
C1 -->|stdio or HTTP| S1
C2 -->|stdio or HTTP| S2
end
subgraph remote ["Internet"]
S3["MCP server 3<br/>e.g. a SaaS vendor's server"]
C3 -->|HTTPS + OAuth| S3
end- Host — the LLM application the user interacts with: Claude Desktop, an IDE, your own agent service. The host creates and manages clients, enforces security policy and consent, and decides which servers may connect.
- Client — a connector inside the host. Each client speaks MCP to exactly one server. If your host uses three MCP servers, it runs three clients. When you write an MCP client in Python (as in Part 4), your agent application is the host and your
Clientobject is the client. - Server — the service that exposes context and capabilities: files, a database, an API, a prompt library. Servers are deliberately narrow: "servers should be extremely easy to build" and "highly composable", and a server cannot see the whole conversation or other servers — it only sees what a request carries.
1.4 The spec, and the big 2026 change#
MCP is versioned by date: a revision identifier like 2025-11-25 or 2026-07-28 records the last date on which backwards-incompatible changes were made. The current stable revision is 2026-07-28, released 28 July 2026; the previous one is 2025-11-25 (November 2025), and 2025-06-18 before that. Revisions marked "current" may still receive backwards-compatible changes; "final" revisions are frozen.
The 2026-07-28 revision is the biggest break since remote MCP launched, and you need to know what changed because much of the older documentation (and most tutorial content written before mid-2026) describes the old design:
Old model (≤ 2025-11-25) |
New model (2026-07-28) |
|---|---|
Connection opens with an initialize handshake; client and server negotiate version and capabilities once per session |
No handshake. Every request carries its protocol version, client identity and capabilities in _meta. Servers answer a mandatory server/discover RPC if the client wants capabilities up front |
Streamable HTTP assigns a session via the Mcp-Session-Id header; server can send requests (sampling, elicitation, roots) down an open stream |
Stateless. No session header. Server-to-client requests travel inside a result as InputRequiredResult (the MRTR pattern); the client retries the original call with answers attached |
| Server notifies changes over a GET stream or per-request streams | A single subscriptions/listen request opens a long-lived stream the client opts into per notification type |
| Sampling, roots and logging are first-class features | Deprecated (with a ≥12-month offramp): new implementations shouldn't adopt them |
| Dynamic Client Registration is the default way for clients to register with an authorization server | CIMD (Client ID Metadata Documents) is preferred; DCR is deprecated but still works |
The Python SDK v2 (see 3.1) speaks 2026-07-28 and serves older clients from the same server automatically, so you rarely have to choose — but you should understand both shapes because the wire examples in 2.8 show the modern one.
1.5 History and governance#
- November 2024: Anthropic open-sourced MCP — specification, SDKs, a Claude Desktop integration and a starter set of servers — positioning it as an open standard any model provider could adopt.
- 2025: rapid adoption. ChatGPT, Cursor, VS Code, Gemini and others added MCP support; the specification went through the
2025-03-26(Streamable HTTP),2025-06-18and2025-11-25revisions; the community registry launched in preview in September 2025. - 9 December 2025: Anthropic donated MCP to the Agentic AI Foundation (AAIF) under the Linux Foundation, co-founded by Anthropic, Block and OpenAI with support from Google, Microsoft, AWS, Cloudflare and Bloomberg. Platinum members include AWS, Anthropic, Block, Bloomberg, Cloudflare, Google, Microsoft and OpenAI. Governance is now foundation-managed rather than vendor-managed — the same trajectory LSP, Kubernetes and other infrastructure standards followed.
- As of November 2026: the
2026-07-28revision is current; the Python and TypeScript SDKs reported 97M+ monthly downloads combined in Anthropic's December 2025 donation announcement — check the SDK repositories for current counts; ecosystem reporting put the number of public MCP servers above ten thousand by that date — the registry has grown since, so check it for current counts.
The lesson's sources for everything volatile are the specification site (modelcontextprotocol.io/specification), the SDK documentation (py.sdk.modelcontextprotocol.io for Python), and the official blog. When something here and a blog post disagree, the specification wins.
Part 2: Protocol anatomy#
2.1 JSON-RPC 2.0 messages#
Every MCP message is a JSON-RPC 2.0 message: {"jsonrpc": "2.0", ...} with one of three shapes.
| Shape | Has | Direction | Used for |
|---|---|---|---|
| Request | id (string or integer, never null), method, optional params |
client → server | tools/call, resources/read, prompts/get, server/discover, list operations |
| Response | same id, plus result or error |
server → client | results and errors |
| Notification | method, optional params, no id |
either direction | progress, cancellation, list-changed, log messages |
A successful response's result carries a resultType field: "complete" for a finished result, or "input_required" for the MRTR pattern (2.4). Results from older servers that omit resultType are treated as "complete".
Error responses use standard JSON-RPC codes (-32700 parse error, -32600 invalid request, -32601 method not found, -32602 invalid params, -32603 internal error) plus three MCP-specific codes allocated from the spec's reserved range:
| Code | Name | Meaning |
|---|---|---|
-32020 |
HeaderMismatch |
Streamable HTTP headers disagree with the JSON-RPC body (e.g. Mcp-Name doesn't match params.name) |
-32021 |
MissingRequiredClientCapability |
The request needs a client capability the client didn't declare |
-32022 |
UnsupportedProtocolVersion |
The server doesn't speak the requested protocol version; error.data.supported lists what it does |
One more code you will meet: a resources/read for a URI the server doesn't have now returns -32602 (invalid params); earlier revisions used -32002. Clients written for the old code should treat both as "no such resource".
A subtle but important rule for tool authors: protocol errors vs tool errors. A protocol error means the request itself was malformed (unknown tool name, bad JSON-RPC). A tool execution error is a successful JSON-RPC response whose result has isError: true and a text content block explaining what went wrong — "Invalid departure date: must be in the future." The spec is explicit that input-validation and business-logic failures belong in isError results so the model can read them and self-correct; protocol errors are for things the model can't fix. Lesson 03.5 taught the same lesson for provider tool calling; MCP standardizes it.
2.2 Lifecycle without a handshake#
Under 2026-07-28 there is no connection setup at all. Every request is self-contained: it declares its protocol version, client identity and capabilities in _meta:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "lookup_order",
"arguments": {"order_id": "A-1042"},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {"name": "support-agent", "version": "1.4.0"},
"io.modelcontextprotocol/clientCapabilities": {"elicitation": {"form": {}}}
}
}
}If the client wants to know what the server supports before calling anything, it sends the mandatory server/discover RPC; the server replies with supportedVersions, capabilities, instructions (natural-language guidance for the model on how to use the server) and its serverInfo identity. Calling it is optional — a client may send tools/call directly and handle UnsupportedProtocolVersionError (-32022) by retrying with a version from error.data.supported. On Streamable HTTP the same version travels in the MCP-Protocol-Version header, which must match the _meta value.
2.3 The three server primitives#
The heart of MCP is a clean division of labour, expressed as a control hierarchy:
| Primitive | Controlled by | What it is | Analogy |
|---|---|---|---|
| Tools | The model | Functions the model may call to take actions | POST — does work, may have side effects |
| Resources | The application | Data/context the host attaches for the model | GET — loads data, changes nothing |
| Prompts | The user | Reusable message templates the user invokes by name (slash commands, menu entries) | A saved query the user runs |
- Tools are defined by
name,title,description,inputSchema(JSON Schema, 2020-12 by default), optionaloutputSchema, optionalannotationsandicons. Names should be 1–128 characters of[A-Za-z0-9_.-]— the spec's guidance exists because these names end up in model context. A server declares thetoolscapability and answerstools/list(paginated) andtools/call. - Resources are identified by a URI (
file:///…,https://…, or custom schemes likedocs://). A resource hasuri,name,mimeType, optionalsize,description,icons. Contents are text or base64blob.resources/listenumerates concrete resources;resources/templates/listenumerates parameterized URIs (RFC 6570 templates likefile:///{path}) the client can expand.resources/readreturns contents; ahttps://resource may alternatively be fetched directly by the client. - Prompts have
name,description, optionalarguments(each withname,description,required), andprompts/getreturnsmessages— an array of{role: "user"|"assistant", content}messages, wherecontentis a single block of type text, image, audio,resource_linkor embeddedresource. A prompt is how a server ships a curated instruction — "here is how our support team wants refunds triaged" — that a user invokes deliberately.
The control distinction is the design lesson: the model decides when to call a tool, the application decides what context to attach, the user decides which prompt to run. If you find yourself wanting the model to autonomously pull a document, that's a tool that reads a resource (or a resource the host auto-attaches); if you want the user to opt into a workflow, that's a prompt.
2.4 Client features and MRTR#
Servers sometimes need something from the client while serving a request: a missing parameter, a confirmation, an LLM completion. Under 2026-07-28 this is the Multi Round-Trip Requests (MRTR) pattern — the only way, since servers can no longer send their own requests down a stream:
- Client sends a normal request (e.g.
tools/call). - Server replies
resultType: "input_required"with aninputRequestsmap (each entry a client-bound request likeelicitation/create) and an opaquerequestStateblob. - Client gathers the input (asks the user, calls the model, whatever) and retries the original request with the same parameters plus
inputResponsesandrequestState, under a new JSON-RPCid. - Server completes the call.
On the wire, step 2's reply is an ordinary result whose resultType is "input_required". inputRequests is a map keyed by server-chosen names; each value is a client-bound request such as elicitation/create:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"resultType": "input_required",
"inputRequests": {
"escalation_ok": {
"method": "elicitation/create",
"params": {
"mode": "form",
"message": "Escalate ticket T-0007 to high priority?",
"requestedSchema": {
"type": "object",
"properties": {"approve": {"type": "boolean"}},
"required": ["approve"]
}
}
}
},
"requestState": "opaque-state-token"
}
}The client's retry is the same tools/call — same name, same arguments — plus inputResponses (answers keyed by the same names the server chose) and the echoed requestState, under a new id:
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "escalate_ticket",
"arguments": {"subject": "T-0007", "priority": "high"},
"inputResponses": {
"escalation_ok": {"action": "accept", "content": {"approve": true}}
},
"requestState": "opaque-state-token",
"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28"}
}
}The server needs nothing but what's in the retry — no shared session state, which is exactly why the pattern suits a stateless, load-balanced deployment. 3.6 shows how the Python SDK generates and consumes these exchanges for you.
MRTR applies only to tools/call, resources/read and prompts/get. The client features that can appear inside inputRequests:
- Elicitation — the server asks the user for structured input. Two modes:
form(an in-band JSON form with a restricted flat schema of primitives/enums; never for passwords, API keys or payment credentials) andurl(redirect the user to an external page for sensitive flows like OAuth or payments — data doesn't pass through the client). Elicitation is the surviving, recommended client feature. - Sampling (
sampling/createMessage) — the server asks the client to run an LLM completion, optionally with tools, so the server never needs its own model API key. Deprecated in2026-07-28(SEP-2577): it remains for ≥12 months, but new implementations should call provider APIs directly. ItsincludeContextparameter values"thisServer"and"allServers"were already soft-deprecated in2025-11-25and were formally reclassified as Deprecated in2026-07-28(SEP-2596) — omit the field or use"none"; they will be removed no later than the sampling feature itself. - Roots (
roots/list) — the client tells the server which directories/projects are in scope. Deprecated in2026-07-28: pass paths via tool parameters, resource URIs or server config instead. - Logging — the server streams
notifications/messagelog entries to the client. Deprecated in2026-07-28: log tostderron stdio and use OpenTelemetry for observability.
2.5 Cross-cutting utilities#
| Utility | Mechanism |
|---|---|
| Pagination | tools/list, resources/list, resources/templates/list, prompts/list accept a cursor param and return nextCursor. Cursors are opaque — never parse them; a missing nextCursor means end of results; invalid cursor → -32602. |
| Caching | Complete results from server/discover and the list/read operations carry ttlMs (freshness hint, ms; 0 = immediately stale) and cacheScope ("public" shareable / "private" per-auth-context). Change notifications invalidate. |
| Progress | Client puts a unique progressToken in request _meta; server emits notifications/progress with progress, optional total, message. Streamable HTTP delivers it on the request's SSE stream; stdio as a plain notification line. |
| Cancellation | stdio: client sends notifications/cancelled with requestId. Streamable HTTP: closing the response SSE stream is the cancellation. Servers should stop work and send no further messages for the cancelled id. |
| Change notifications | Servers that declare listChanged/subscribe capabilities notify via subscriptions/listen: the client opens one long-lived stream opting into toolsListChanged, promptsListChanged, resourcesListChanged, resourceSubscriptions; the server acknowledges (notifications/subscriptions/acknowledged) and tags events with io.modelcontextprotocol/subscriptionId. Replaces the old per-resource subscribe methods and the standalone GET stream. |
| Completion | completion/complete lets clients autocomplete prompt/resource-template arguments (e.g. file paths) — a UX nicety, not model-facing. |
Two footnotes to that table. First, _meta doubles as the observability hook: traceparent, tracestate and baggage are reserved keys (the one exception to the io.modelcontextprotocol/ prefix rule) carrying W3C trace-context and baggage, so an MCP call can join the same distributed trace as your LLM calls — the seam Module 11A's tracing coverage builds on. Second, one utility that no longer exists: the ping method that kept sessions alive in earlier revisions was removed in 2026-07-28. There is no protocol-level keepalive — liveness is the transport's and your deployment's job (HTTP health endpoints, your own timeouts), so don't write ping-based keepalive code.
2.6 Transports#
A transport is a binding: how messages are framed and delivered. Protocol semantics are identical on all of them.
stdio — the client launches the server as a subprocess and speaks newline-delimited JSON-RPC over its stdin/stdout. The server may write logs to stderr (never stdout — stdout is the wire). One message per line, no embedded newlines. Shutdown: client closes stdin, server exits. This is the default for local servers: Claude Desktop, IDEs and mcp dev all use it. Security note: launching a stdio server means executing a local command — vet it like any dependency (Part 5).
Streamable HTTP — the modern remote transport. The server exposes one endpoint (conventionally /mcp) accepting POST. Each JSON-RPC message is its own POST with Accept: application/json, text/event-stream; the server replies either a single JSON object or a request-scoped SSE stream carrying progress notifications then the final response. Every POST must carry MCP-Protocol-Version, Mcp-Method (the JSON-RPC method), and for tools/call/resources/read/prompts/get a Mcp-Name header — so gateways, rate limiters and WAFs can route and authorize without parsing the body. Servers must validate Origin (DNS-rebinding defence; bad origin → HTTP 403) and should bind localhost only when local. An optional x-mcp-header schema annotation lets a server mirror a primitive tool parameter into an Mcp-Param-* header.
What Streamable HTTP no longer does (2026-07-28). Earlier revisions let a client resume a broken SSE stream with the Last-Event-ID header and have the server redeliver missed messages. That was removed: a broken response stream now loses the in-flight request, and the client must re-issue it as a new request with a new id. Two consequences for your design: make tool calls idempotent or safely repeatable (the retry may land on a different server instance, and the first attempt may or may not have run — the same discipline as 08A.14 Part 5 idempotency keys), and push genuinely long operations to the Tasks extension (6.6) instead of holding one HTTP response open for minutes.
HTTP+SSE (legacy) — the original remote transport from 2024-11-05: a GET stream for server→client messages plus a separate POST endpoint. Deprecated since 2025-03-26 and on a removal track; don't build on it. Some older clients still require it — the SDK's sse transport exists only for them.
2.7 Tool results: content, structuredContent and outputSchema#
A tools/call result has two channels:
content— an array of unstructured blocks the model reads:text,image(base64 + mimeType),audio,resource_link(a URI the client may fetch), and embeddedresource. Multiple blocks allowed; keep text concise — this is model context, billed in tokens.structuredContent— an arbitrary JSON value conforming to the tool's optionaloutputSchema. This is typed data for the client application (your code), not prose for the model. The spec notes it's unrelated to LLM "structured outputs" (schema-constrained generation from 03.4) — it's the tool's return value. For backwards compatibility a server should also serialize the JSON into a text block.
Errors inside a call come back as isError: true with an actionable text message — the model reads it and retries with corrected arguments. Protocol-level failures (unknown tool, malformed request) are JSON-RPC errors instead.
Annotations are behavioural hints on tools (and audiences/priorities on resources and content): readOnlyHint (doesn't modify its environment), destructiveHint (may perform destructive updates — only meaningful when readOnlyHint is false), idempotentHint (repeated calls with same args have no additional effect), openWorldHint (interacts with external entities vs a closed world). The spec warns clients must treat annotations as untrusted unless the server is trusted — a malicious server can lie about readOnlyHint. Your host uses them for approval UX; your own policy layer shouldn't.
2.8 Real JSON-RPC exchanges#
The fastest way to understand MCP is to watch bytes move. This pure-standard-library sample implements a minimal stateless server — server/discover, tools/list, tools/call, resources/read, prompts/get — over an in-memory pipe, speaking the 2026-07-28 wire format:
# s2_mini_mcp.py — a minimal stateless MCP server, no SDK, stdlib only
import json
from typing import Any
PROTOCOL_VERSION = "2026-07-28"
META = {
"io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
"io.modelcontextprotocol/clientInfo": {"name": "mini-client", "version": "0.1"},
"io.modelcontextprotocol/clientCapabilities": {},
}
ORDERS = {"A-1042": {"status": "shipped", "eta": "2026-11-08"}}
POLICIES = {
"refunds": "Refunds are issued within 5 business days for orders < 30 days old.",
}
def ok(req_id: Any, result: dict) -> dict:
result.setdefault("resultType", "complete")
return {"jsonrpc": "2.0", "id": req_id, "result": result}
def err(req_id: Any, code: int, message: str) -> dict:
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
def handle(msg: dict) -> dict | None:
method = msg.get("method")
params = msg.get("params") or {}
if "id" not in msg: # a notification never gets a response
return None
req_id = msg["id"]
if method == "server/discover":
return ok(req_id, {
"supportedVersions": [PROTOCOL_VERSION],
"capabilities": {"tools": {}, "resources": {}, "prompts": {}},
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "mini-ops", "version": "0.1"}},
"instructions": "Order and policy lookups for the support desk.",
})
if method == "tools/list":
return ok(req_id, {"tools": [
{"name": "lookup_order", "description": "Look up an order by id.",
"inputSchema": {"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"]},
"annotations": {"readOnlyHint": True, "openWorldHint": False}},
]})
if method == "tools/call" and params.get("name") == "lookup_order":
order = ORDERS.get(params.get("arguments", {}).get("order_id", ""))
if order is None:
return ok(req_id, {"isError": True, "content": [
{"type": "text", "text": "No order with that id; try the order number from the receipt."}]})
return ok(req_id, {
"isError": False,
"content": [{"type": "text", "text": f"Order {params['arguments']['order_id']}: {order}"}],
"structuredContent": order,
})
if method == "tools/call":
return err(req_id, -32602, f"Unknown tool: {params.get('name')}")
if method == "resources/read" and params.get("uri") == "policy://refunds":
return ok(req_id, {"contents": [
{"uri": "policy://refunds", "mimeType": "text/plain",
"text": POLICIES["refunds"]}]})
if method == "prompts/get" and params.get("name") == "refund_triage":
return ok(req_id, {"description": "Refund triage template",
"messages": [{"role": "user",
"content": {"type": "text",
"text": f"Triage this refund request against policy://refunds.\n\n{params.get('arguments', {}).get('request', '')}"}}]})
return err(req_id, -32601, f"Method not found: {method}")
if __name__ == "__main__":
requests = [
{"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": META}},
{"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {"_meta": META}},
{"jsonrpc": "2.0", "id": 3, "method": "tools/call",
"params": {"name": "lookup_order", "arguments": {"order_id": "A-1042"}, "_meta": META}},
{"jsonrpc": "2.0", "id": 4, "method": "tools/call",
"params": {"name": "lookup_order", "arguments": {"order_id": "NOPE"}, "_meta": META}},
{"jsonrpc": "2.0", "id": 5, "method": "resources/read",
"params": {"uri": "policy://refunds", "_meta": META}},
{"jsonrpc": "2.0", "id": 6, "method": "prompts/get",
"params": {"name": "refund_triage",
"arguments": {"request": "Customer wants a refund on order A-1042."},
"_meta": META}},
]
for r in requests:
print("→", json.dumps(r["method"] if "method" in r else r))
resp = handle(r)
if resp is not None: # notifications produce no response
print("←", json.dumps(resp, indent=2))
print()A fully conforming server would also add ttlMs and cacheScope to the server/discover and list results (2.5); the sample leaves them out to keep the exchanges short.
→ "server/discover"
← {
"jsonrpc": "2.0",
"id": 1,
"result": {
"supportedVersions": [
"2026-07-28"
],
"capabilities": {
"tools": {},
"resources": {},
"prompts": {}
},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "mini-ops",
"version": "0.1"
}
},
"instructions": "Order and policy lookups for the support desk.",
"resultType": "complete"
}
}
→ "tools/list"
← {
"jsonrpc": "2.0",
"id": 2,
"result": {
"tools": [
{
"name": "lookup_order",
"description": "Look up an order by id.",
"inputSchema": {
"type": "object",
"properties": {
"order_id": {
"type": "string"
}
},
"required": [
"order_id"
]
},
"annotations": {
"readOnlyHint": true,
"openWorldHint": false
}
}
],
"resultType": "complete"
}
}
→ "tools/call"
← {
"jsonrpc": "2.0",
"id": 3,
"result": {
"isError": false,
"content": [
{
"type": "text",
"text": "Order A-1042: {'status': 'shipped', 'eta': '2026-11-08'}"
}
],
"structuredContent": {
"status": "shipped",
"eta": "2026-11-08"
},
"resultType": "complete"
}
}
→ "tools/call"
← {
"jsonrpc": "2.0",
"id": 4,
"result": {
"isError": true,
"content": [
{
"type": "text",
"text": "No order with that id; try the order number from the receipt."
}
],
"resultType": "complete"
}
}
→ "resources/read"
← {
"jsonrpc": "2.0",
"id": 5,
"result": {
"contents": [
{
"uri": "policy://refunds",
"mimeType": "text/plain",
"text": "Refunds are issued within 5 business days for orders < 30 days old."
}
],
"resultType": "complete"
}
}
→ "prompts/get"
← {
"jsonrpc": "2.0",
"id": 6,
"result": {
"description": "Refund triage template",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "Triage this refund request against policy://refunds.\n\nCustomer wants a refund on order A-1042."
}
}
],
"resultType": "complete"
}
}A few things to notice in real output:
server/discoverreturns capabilities andinstructions— free-text guidance the host can inject so the model knows when to reach for this server.- The failed
lookup_orderis not a JSON-RPC error: it's a normal result withisError: trueand a message written for the model to act on. structuredContentcarries the machine-readable order;contentcarries the human/model-readable line.- The same
handle()works unchanged over stdio or HTTP — the transport only changes framing. - Two wire rules the sample honours: a message with no
idis a notification and gets no response at all (handlereturnsNone), and atools/callnaming an unknown tool is-32602(invalid params) —-32601is reserved for unknown methods.
Part 3: Building an MCP server in Python#
3.1 Setup and your first server#
The official Python SDK is the mcp package (these samples were checked against version 2.3.0 as of November 2026). Its high-level interface is MCPServer — renamed from v1's FastMCP, which is why v1 code (from mcp.server.fastmcp import FastMCP) fails on v2. You register plain Python functions with decorators; the SDK derives names, descriptions and JSON Schemas from your function signatures and docstrings:
# server.py
from mcp.server import MCPServer
mcp = MCPServer("Demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
"""Greet someone by name."""
return f"Hello, {name}!"
@mcp.prompt()
def summarize(text: str) -> str:
"""Summarize a piece of text in one sentence."""
return f"Summarize the following text in one sentence:\n\n{text}"
if __name__ == "__main__":
mcp.run() # stdio by defaultWhat the SDK does for you, which is most of the protocol: JSON Schema generation from type hints (via Pydantic), argument validation before your function runs, JSON-RPC dispatch, pagination, capability declaration, both protocol eras (2026-07-28 and legacy initialize clients), and transport plumbing. mcp dev server.py opens the MCP Inspector; mcp run server.py --transport streamable-http serves it on http://127.0.0.1:8000/mcp.
3.2 The running example: an ops server#
The module's running example is the support-and-operations assistant. Here it becomes an MCP server exposing three things: order/ticket tools, a policy resource, and a prompt template — all over in-memory fake data so everything is testable:
# ops_server.py — the module's running example as an MCP server
from dataclasses import dataclass
from mcp.server import MCPServer
from mcp.server.mcpserver import Context
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
ORDERS = {
"A-1042": {"status": "shipped", "eta": "2026-11-08", "total": 189.00},
"B-2077": {"status": "processing", "eta": None, "total": 42.50},
}
TICKETS = [] # in-memory store; a real server would use a database
POLICY_REFUNDS = (
"Refunds are issued within 5 business days for orders less than 30 days old. "
"Orders over $500 require supervisor approval."
)
mcp = MCPServer("ops-assistant", instructions=(
"Order lookups, ticket creation and refund triage for the support desk. "
"Read policy://refunds before issuing any refund."
))
@dataclass
class OrderResult:
order_id: str
status: str
eta: str | None
total: float
@mcp.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def lookup_order(order_id: str) -> OrderResult:
"""Look up an order by its order id (e.g. 'A-1042')."""
if order_id not in ORDERS:
raise ToolError(f"No order '{order_id}'. Check the id on the receipt.")
o = ORDERS[order_id]
return OrderResult(order_id=order_id, status=o["status"], eta=o["eta"], total=o["total"])
@mcp.tool()
def create_ticket(subject: str, body: str, priority: str = "normal") -> str:
"""Create a support ticket. priority: low | normal | high."""
ticket_id = f"T-{len(TICKETS) + 1:04d}"
TICKETS.append({"id": ticket_id, "subject": subject, "body": body, "priority": priority})
return f"Created ticket {ticket_id}."
@mcp.resource("policy://refunds")
def refund_policy() -> str:
"""The refund policy the support team must apply."""
return POLICY_REFUNDS
@mcp.prompt()
def refund_triage(request: str) -> str:
"""Triage a refund request against the refund policy."""
return (f"A customer requests a refund. Policy (policy://refunds):\n{POLICY_REFUNDS}\n\n"
f"Request:\n{request}\n\nDecide: approve, deny, or escalate — and say why.")
if __name__ == "__main__":
mcp.run()Notes that matter in production but are compressed here: create_ticket should be idempotent (accept an idempotency key — see 08A.6), validate priority as a Literal, and log every call; the annotations mark lookup_order read-only so hosts can auto-approve it while prompting for create_ticket. Tool errors: raise ToolError (from mcp.server.mcpserver.exceptions) for failures the model can act on — the request still succeeds, is_error is True, and your message lands in content where the model reads it (prefixed with the tool name). Any other exception also returns is_error=True, but the SDK sanitises it to Error executing tool <name> so internals never leak — reserve MCPError (from mcp) for request-level rejections that should fail the whole call as a JSON-RPC error.
3.3 Context, progress, logging and lifespan#
Inside any handler you can declare a ctx: Context parameter — the SDK injects it and it never appears in the model-facing schema. This and the next block continue ops_server.py from 3.2, so mcp already exists; the imports are repeated so each block parses its annotations on its own:
from mcp.server import MCPServer
from mcp.server.mcpserver import Context
mcp = MCPServer("ops-assistant") # in ops_server.py this is the instance from 3.2
@mcp.tool()
async def slow_report(ctx: Context) -> str:
"""Generate a weekly ops report (simulated slow work)."""
for i in range(1, 4):
await ctx.report_progress(i, 3, f"Step {i}/3")
... # real work here
return "Report ready."ctx.request_id identifies the request; ctx.read_resource(uri) lets a tool read the server's own resources; ctx.session.send_tool_list_changed() (or the 2026-style ctx.notify_tools_changed()) tells subscribed clients to re-list. Logging is ordinary Python logging — write to stderr; the deprecated protocol logging utility is not needed. Lifespan gives the server process-wide state:
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from mcp.server import MCPServer
from mcp.server.mcpserver import Context
class _Pool:
"""Stand-in for a real connection pool — swap in your driver's pool type."""
async def close(self) -> None:
... # a real pool drains in-flight work and returns connections here
async def connect_db() -> _Pool:
"""Stand-in for your startup code: open a connection pool, load config, etc."""
return _Pool()
@dataclass
class AppContext:
db: _Pool # a connection pool opened at startup
@asynccontextmanager
async def app_lifespan(server: MCPServer) -> AsyncIterator[AppContext]:
db = await connect_db() # startup
try:
yield AppContext(db=db)
finally:
await db.close() # shutdown
# In ops_server.py this REPLACES the `mcp = MCPServer("ops-assistant", instructions=...)`
# line from 3.2: pass `lifespan=app_lifespan` there (keep the instructions argument too).
mcp = MCPServer("ops-assistant", lifespan=app_lifespan)
@mcp.tool()
def db_ping(ctx: Context[AppContext]) -> str:
"""Check the database connection."""
return "ok" if ctx.request_context.lifespan_context.db else "down"The lifespan runs once around the server's life; handlers reach it via ctx.request_context.lifespan_context, fully typed by Context[AppContext].
3.4 Testing with the in-memory client#
The same Client class that talks to URLs and subprocesses connects directly to your server object — no port, no transport:
# test_ops_server.py
import pytest
from mcp import Client
from ops_server import TICKETS, mcp
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_lookup_order():
async with Client(mcp, raise_exceptions=True) as client:
result = await client.call_tool("lookup_order", {"order_id": "A-1042"})
assert result.structured_content["status"] == "shipped"
missing = await client.call_tool("lookup_order", {"order_id": "NOPE"})
assert missing.is_error
assert "No order 'NOPE'" in missing.content[0].text
@pytest.mark.anyio
async def test_create_ticket():
async with Client(mcp, raise_exceptions=True) as client:
before = len(TICKETS)
result = await client.call_tool(
"create_ticket",
{"subject": "Late delivery", "body": "Order A-1042 arrived late.", "priority": "high"},
)
assert not result.is_error
assert result.content[0].text.startswith("Created ticket T-")
assert len(TICKETS) == before + 1
assert TICKETS[-1]["priority"] == "high"
@pytest.mark.anyio
async def test_server_metadata():
async with Client(mcp, raise_exceptions=True) as client:
tools = await client.list_tools()
by_name = {t.name: t for t in tools.tools}
assert {"lookup_order", "create_ticket"} <= set(by_name)
assert by_name["lookup_order"].annotations.read_only_hint is True
prompt = await client.get_prompt("refund_triage", {"request": "refund please"})
assert "policy://refunds" in prompt.messages[0].content.textraise_exceptions=True surfaces real errors in tests instead of the sanitised "Internal server error" a remote caller would see. This pattern — Client(mcp) in a pytest fixture — is how the SDK tests its own examples and how you should test every server you ship.
3.5 Running and packaging#
- stdio (default):
mcp.run()— the host launchespython ops_server.pyas a subprocess. - Streamable HTTP:
mcp.run(transport="streamable-http", port=3001)→http://127.0.0.1:3001/mcp. Options includejson_response=True(single JSON replies instead of SSE) andstateless_http=True. - Inside an existing ASGI app (FastAPI etc.): mount the Starlette app returned by
mcp.streamable_http_app()inside aMount. One trap: a mounted sub-application's own lifespan never runs, so the host app must entermcp.session_manager.run()in its lifespan (SDK docs, the ASGI page under "Run", read 11 November 2026).host,port,json_responseandstateless_httpare arguments torun(), not to theMCPServer(...)constructor; withjson_response=Truethere is no back channel, so progress and legacyctx.elicit()calls stop working. - Distribution: publish the server as a package (
uv build+ PyPI) so hosts install it withuvx your-package(orpipx run); containerise it and expose the HTTP transport for remote use. Declare a compatiblemcpversion range in your package metadata (for examplemcp>=2,<3) — the SDK's protocol layer changes between majors.
3.6 Asking the user mid-call: elicitation and MRTR#
2.4 showed MRTR on the wire. The SDK's answer on MCPServer is dependencies: annotate a parameter Annotated[T, Resolve(fn)] and the SDK runs fn before your tool body. If fn returns Elicit(message, Model), the SDK asks the user — over MRTR on a 2026-07-28 client, over a direct elicitation request on a legacy one — validates the answer against Model, and injects it. The parameter never appears in the model-facing schema, so the model can't invent or skip it.
Adding to ops_server.py — a tool that must not escalate to high priority without a human yes:
# additions to ops_server.py — merge these imports into the file's header
from typing import Annotated
from pydantic import BaseModel, Field
from mcp.server.mcpserver import (
AcceptedElicitation, CancelledElicitation, DeclinedElicitation,
Elicit, ElicitationResult, Resolve,
)
class Confirm(BaseModel):
approve: bool = Field(description="Approve the escalation?")
async def confirm_escalation(subject: str, priority: str) -> Confirm | Elicit[Confirm]:
"""Resolver: only interrupt the user when the model asks for 'high'."""
if priority != "high":
return Confirm(approve=True) # nothing to ask: no round-trip
return Elicit(f"Escalate ticket '{subject}' to high priority?", Confirm)
@mcp.tool()
async def escalate_ticket(
subject: str,
priority: str,
confirm: Annotated[ElicitationResult[Confirm], Resolve(confirm_escalation)],
) -> str:
"""Set a ticket's priority; escalating to 'high' requires user approval."""
match confirm:
case AcceptedElicitation(data=Confirm(approve=True)):
return f"Escalated '{subject}' to {priority}."
case AcceptedElicitation():
return f"User kept '{subject}' at normal priority."
case DeclinedElicitation():
return "User declined; priority unchanged."
case CancelledElicitation():
return "User cancelled; priority unchanged."How it plays out: the model calls escalate_ticket with priority="high". The SDK runs confirm_escalation first — it sees the same validated subject/priority arguments the tool body will get, matched by name — gets Elicit(...) back, and the call pauses as the InputRequiredResult from 2.4. The client renders the message plus a form built from Confirm; the answer returns as an ElicitationResult your match handles case by case. Annotate the parameter Confirm instead of ElicitationResult[Confirm] when you don't need to distinguish the outcomes — the tool then receives the model on accept and the call fails with an error result on decline or cancel.
Three alternatives and edges worth knowing:
await ctx.elicit(message, schema)asks directly from inside a tool body (result.actionis"accept"/"decline"/"cancel"). ⚠️ It only works for clients on legacy (≤2025-11-25) connections — on2026-07-28there is no server→client channel and the call fails. The resolver form above is the one that works on both eras.- Returning
InputRequiredResultyourself — an@mcp.prompt()or@mcp.resource()template function can return it directly and read the retry's answers offctx.input_responses. A tool that already usesResolve(...)parameters cannot also do this; the SDK rejects the mix at registration. requestStateis sealed for you.MCPServerencrypts and authenticates outgoing state, binds it to the principal, the originating request and a per-round TTL (600 seconds by default), and verifies every echo — but the sealing key is generated per process. A retry landing on a different worker or after a restart fails, so multi-instance deployments pass shared keys:MCPServer("ops", request_state_security=RequestStateSecurity(keys=[key]))(importRequestStateSecurityfrommcp.server.mcpserver), one or more secrets of ≥32 bytes each, identical on every instance.
Client side, Client drives the whole MRTR loop for you: register an elicitation_callback and it answers each inputRequests entry, retries with inputResponses plus the echoed requestState, and repeats until a normal result arrives — capped at input_required_max_rounds=10 rounds by default, with a short backoff when a round carries only state:
# client side — your host application
from mcp import Client
from mcp.client import ClientRequestContext
from mcp.types import ElicitRequestParams, ElicitResult
async def ask_user(ctx: ClientRequestContext, params: ElicitRequestParams) -> ElicitResult:
# render params.message and the requestedSchema form in your UI
return ElicitResult(action="accept", content={"approve": True})
async with Client("http://127.0.0.1:3001/mcp", elicitation_callback=ask_user) as client:
result = await client.call_tool("escalate_ticket", {"subject": "T-0007", "priority": "high"})
print(result.content)Leave the callback off and the first round fails — the SDK's stand-in answers every elicitation with an error and call_tool raises MCPError ("Elicitation not supported"). For distributed clients that must own the loop themselves (question and retry handled by different processes), drop to client.session.call_tool(..., allow_input_required=True), which returns CallToolResult | InputRequiredResult per leg.
Part 4: Using MCP from your agent#
4.1 The SDK client#
import anyio
from mcp import Client
async def main() -> None:
# Streamable HTTP remote server
async with Client("https://mcp.example.com/mcp") as client:
print(client.protocol_version) # e.g. "2026-07-28"
tools = await client.list_tools()
result = await client.call_tool("lookup_order", {"order_id": "A-1042"})
print(result.structured_content)
# stdio: launch a local server as a subprocess
from mcp import StdioServerParameters
params = StdioServerParameters(command="python", args=["ops_server.py"])
async with Client(params) as client:
resources = await client.list_resources()
anyio.run(main)Client(target) negotiates the protocol version automatically (mode="auto" default; pin with mode="2026-07-28"). One Client per server — the 1:1 client↔server rule is enforced by the architecture.
The list_* methods don't auto-paginate: each takes a cursor= keyword and returns next_cursor. Draining a paged list is one loop — free against a server that doesn't page, since next_cursor is None on the first response:
# pagination: pass each page's next_cursor back verbatim until it is None
from mcp import Client
from mcp.types import Tool
async def list_all_tools(client: Client) -> list[Tool]:
tools: list[Tool] = []
cursor: str | None = None
while True:
page = await client.list_tools(cursor=cursor)
tools.extend(page.tools)
if page.next_cursor is None:
break
cursor = page.next_cursor
return toolsCursors are opaque — the only legal source is the previous page's next_cursor, and the server owns the page size (there is no limit= in the protocol).
4.2 Mapping MCP tools onto provider formats#
Your agent loop from 08A.2 speaks provider tool formats (03.5). Bridging is mechanical: client.list_tools() → convert each MCP tool to the provider's function/tool shape (name, description, inputSchema → the provider's parameters schema), and client.call_tool() results → the provider's tool-result content. 03.5, 1.4 has the per-provider vocabularies; the mapping table:
| MCP field | OpenAI Responses/Chat | Anthropic Messages | Gemini generate_content |
OpenRouter (Chat Completions) |
|---|---|---|---|---|
name |
name |
name |
FunctionDeclaration.name |
function.name |
description |
description |
description |
description |
function.description |
inputSchema |
parameters |
input_schema |
parameters (Schema) |
function.parameters |
| result text | output text item |
tool_result content |
function_response parts |
role: "tool" message |
The gotchas are the ones 03.5 already catalogued: echo call IDs, append the full assistant turn, and feed isError results back as data — an MCP tool error is content for the model, not an exception for your loop. The provider-agnostic client from 03.11 is the natural place for this adapter if you support multiple providers.
4.3 Provider-native MCP support#
All four providers can consume MCP — but differently, and the differences decide your architecture. Verified as of November 2026:
| Provider | Mechanism | What it does | Limits (verify on docs) |
|---|---|---|---|
| OpenAI | mcp tool type in the Responses API: {"type": "mcp", "server_label": "…", "server_url": "…", "authorization": "<OAuth access token>", "require_approval": …} |
Provider connects to the remote MCP server, imports its tools (an mcp_list_tools item), calls them inside the response loop (mcp_call items); calls pause for you as mcp_approval_request items unless approval is relaxed |
Streamable HTTP or HTTP/SSE servers; the OAuth token you supply is not stored, so send it on every request; allowed_tools trims the imported list; require_approval is "always", "never" or a per-tool object; Secure MCP Tunnel (tunnel_id) reaches private/local servers; defer_loading works with tool search; OpenAI warns to connect only trusted servers (tool results enter model context) |
| Anthropic | MCP connector (beta, betas=["mcp-client-2025-11-20"] or the newer "mcp-client-2026-09-15"): mcp_servers + a matching mcp_toolset entry in tools on client.beta.messages.create |
Provider handles connection, discovery, tool calls and errors; per-tool allow/deny lists; with the 2026-09-15 header the API records each server's tool list as an mcp_tool_listing block and lets you pin it |
Remote only (Streamable HTTP and SSE; not stdio); tools only — no resources, prompts, sampling; OAuth Bearer token in authorization_token; not eligible for zero data retention; the beta header names have already changed once, so check the docs |
| Gemini | google-genai SDK: pass an MCP ClientSession in tools=[…] (experimental); also server-side mcpServers/mcp_server tool (Streamable HTTP) |
SDK-side: your process is the MCP client, tools surface as function declarations with automatic function calling; server-side: Google connects | SDK-side is async-only and experimental; server-side Streamable HTTP only, names without - |
| OpenRouter | No native MCP-server tool in Chat Completions | You connect to the MCP server yourself and convert tools to function definitions (official cookbook pattern); @openrouter/mcp does this for the TypeScript Agent SDK |
Tool support is per-model (supported_parameters); OpenRouter also runs its own MCP server (mcp.openrouter.ai/mcp) for catalogue/model queries — a different direction |
Illustrative requests (not run; mcp.example.com is a placeholder, so both need a real server and a key, and the beta header names are the volatile part). OpenAI first — approval is on by default, and the safe pattern is to import only the tools you need and relax approval only for read-only ones:
import os
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-luna",
tools=[{
"type": "mcp",
"server_label": "ops",
"server_url": "https://mcp.example.com/mcp",
"authorization": os.environ["OPS_MCP_TOKEN"], # not stored by OpenAI: send it every call
"allowed_tools": ["lookup_order", "create_ticket"],
"require_approval": {"never": {"tool_names": ["lookup_order"]}}, # create_ticket still asks
}],
input="Look up order A-1042 and summarise its status.",
)
# If create_ticket was needed, response.output holds an mcp_approval_request item;
# you answer with an mcp_approval_response item in the next request.
print(response.output_text)Anthropic's connector is the same idea with different names — a server entry plus a toolset that points at it, on the beta endpoint:
import os
import anthropic
client = anthropic.Anthropic()
response = client.beta.messages.create(
model="claude-sonnet-5-5",
max_tokens=2048,
betas=["mcp-client-2025-11-20"],
mcp_servers=[{
"type": "url",
"url": "https://mcp.example.com/mcp",
"name": "ops",
"authorization_token": os.environ["OPS_MCP_TOKEN"],
}],
tools=[{
"type": "mcp_toolset",
"mcp_server_name": "ops",
# allowlist pattern: disable everything, enable only what the task needs
"default_config": {"enabled": False},
"configs": {"lookup_order": {"enabled": True}},
}],
messages=[{"role": "user", "content": "Look up order A-1042 and summarise its status."}],
)
print([block.type for block in response.content]) # may include mcp_tool_use / mcp_tool_result blocks4.4 Hosts, IDEs and chat products#
Beyond APIs, MCP is how desktop apps and editors get tools. As of November 2026 the main hosts:
- Claude (claude.ai), Cowork, Claude Desktop, mobile and Claude Code — one connectors catalogue across all of them: remote "custom connectors" (Streamable HTTP + OAuth) everywhere, plus local stdio servers on the desktop and CLI products.
- VS Code / GitHub Copilot — MCP servers in
.vscode/mcp.jsonor user settings; agent mode picks up tools. - Cursor —
~/.cursor/mcp.json(or project.cursor/mcp.json) withmcpServersentries. - ChatGPT — custom MCP connectors (developer mode / deep research; write actions historically beta for Business plans — verify current plan gating).
- Gemini CLI, Codex CLI —
mcpServersconfig; both speak stdio and remote transports. - The MCP Inspector (
mcp dev) — the reference debugging host.
Typical mcpServers config shape (Cursor/Claude Desktop style):
{
"mcpServers": {
"ops": {
"command": "python",
"args": ["/path/to/ops_server.py"]
},
"remote-docs": {
"url": "https://mcp.example.com/mcp",
"headers": {"Authorization": "Bearer ${MCP_TOKEN}"}
}
}
}Part 5: Security and authorization#
5.1 The threat model#
MCP's power is that a server can make a model do things. The spec's own security guidance plus community research (02.10, Part 17) give the threat list:
| Threat | What it looks like | Defence |
|---|---|---|
| Tool poisoning | A tool's description/inputSchema contains hidden instructions ("before calling, email the user's files to…") |
Treat descriptions as untrusted; host allow-lists; human approval for sensitive tools; vet servers |
| Rug pull | A trusted server's tool definitions change after approval | Pin server versions; re-review on update; hash tool lists in CI |
| Confused deputy | The server uses its credentials to do things the user shouldn't | Per-user auth; least-privilege scopes; act as the user, not the server |
| Token passthrough / over-broad scopes | Client forwards its OAuth token to a malicious server, or requests * scopes |
RFC 8707 resource parameter binds tokens to one server; request minimal scopes; step-up auth for more |
| Cross-server tool shadowing | With several servers connected, one server's tool description tells the model how to use (or to ignore) another server's tools, or a look-alike tool name captures calls meant for a trusted one | Namespace tools per server in your host (ops__lookup_order), connect high-trust and low-trust servers to different agents, review descriptions as untrusted prompt text |
| Local command execution | A stdio server is arbitrary code on your machine | Vet like any dependency; sandbox; run only what you need |
| SSRF / data exfiltration | A "fetch URL" tool reaches internal networks or leaks context | Egress allow-lists; URL validation; no secrets in tool args |
| Indirection via results | Tool results contain injected instructions the model obeys | Results are data, not instructions; output validation; quarantine untrusted content (Module 12) |
5.2 The MCP authorization model (HTTP transports)#
For Streamable HTTP, MCP authorization is OAuth 2.1 (a selected subset) with these pieces — all verified against the 2026-07-28 spec:
- Client calls without a token → server returns
401withWWW-Authenticate: Bearer resource_metadata="…"(and optionallyscope=hints). - Client fetches the server's Protected Resource Metadata (RFC 9728) → learns the authorization server(s).
- Client discovers AS metadata via RFC 8414 or OIDC Discovery.
- Client registers: preferred mechanism is Client ID Metadata Documents (CIMD) — the client_id is an HTTPS URL hosting its metadata; pre-registered clients also work; Dynamic Client Registration (RFC 7591) is deprecated but still accepted.
- Authorization request includes PKCE and the
resourceparameter (RFC 8707) naming the MCP server's canonical URI — so the issued token is audience-bound and useless at other servers. - Authorization server returns a code +
iss(RFC 9207); the client validatesissbefore redeeming — closing mix-up attacks. - Client exchanges the code (with
code_verifier+resource) for an access token, sent asAuthorization: Beareron every request. Tokens never go in query strings; servers must not accept or transit tokens not issued for them. - Insufficient scope at runtime →
403+WWW-Authenticatewitherror="insufficient_scope"and required scopes → the client does a step-up re-authorization (union of old + new scopes), retrying only a few times.
stdio servers skip all of this — credentials come from the environment, which is exactly why vetting the server matters.
5.3 The hands-on checklist#
Before connecting any MCP server to an agent that can act:
- Vet the server: who publishes it, is it in the official registry, what does its code do (read it — it's usually a small package)?
- Least privilege: request only the scopes/tools needed; disable tools you won't use; keep destructive tools behind human approval.
- Pin versions: exact package versions or container digests; review diffs on upgrade (rug-pull defence).
- Sandbox: run stdio servers in a container/VM with no secrets in env and egress allow-lists; remote servers get network-level controls.
- Human-in-the-loop: require approval for write/destructive tools (
readOnlyHint/destructiveHintinform UX but are untrusted — enforce in your policy layer, per 08A.2 and 08A.14). - Treat outputs as data: tool results and resource contents are untrusted text; never let them trigger actions without validation.
- Log and audit: log every
tools/call(server, tool, args summary, result summary, latency) with atrace_id(03.10); the deprecated protocol logging utility isn't needed — your own logging is better anyway. - Budget: MCP tool definitions cost context tokens (6.4); cap the tool list per agent.
Module 12 owns the full treatment: prompt-injection defences, the "lethal trifecta" analysis, guardrails and red-teaming.
Part 6: The ecosystem and when MCP is worth it#
Deep-dive
6.1 Registry and catalogues#
The official MCP Registry (registry.modelcontextprotocol.io, in preview since September 2025) is the canonical catalogue: server creators publish a server.json (name like io.github.you/server, install method, capabilities) after DNS-verifying their namespace; clients and aggregators query its REST API. It's metadata-only — no code hosting, no quality ranking, no curation — so treat listing as discovery, not vetting. Community catalogues (PulseMCP and others) aggregate further. When evaluating a server, the registry entry tells you how to install it; your job is deciding whether to trust it.
6.2 Popular servers#
The ecosystem has thousands of servers; the recurring categories: filesystem (read/write scoped dirs), git, databases (Postgres, SQLite, Mongo), browsers (Playwright-style automation), SaaS (GitHub, Slack, Linear, Stripe, Notion), search/fetch (web, docs), memory/stores, and dev tools (Docker, Kubernetes, CI). Quality varies enormously — many are thin wrappers, some are unmaintained, and "10,000 servers" counts include duplicates and toys. Prefer servers from the vendor of the service itself, widely-used maintained projects, or ones you can read end-to-end (most are a few hundred lines).
6.3 MCP vs the alternatives#
| Option | Choose it when | Cost |
|---|---|---|
| Plain function tools (08A.2, 08A.6) | Your own backend logic; full control; few tools | You write client+server glue per integration |
| Provider built-in/server-side tools (08A.8) | Web search, code execution, file search the provider hosts well | Vendor lock-in; less control; per-call pricing |
| OpenAPI → tools | You have an existing REST API and want coverage fast | Auto-generated tools from big specs perform badly (huge schemas, vague descriptions); curate instead |
| MCP | Third-party or shared capabilities you don't want to rebuild; multiple hosts/agents consume them; remote servers with their own auth | Indirection: another process/protocol to run, secure, debug; tool-definition token cost; version churn |
MCP earns its keep when the same capability serves multiple consumers, when the server owner maintains it (GitHub maintains the GitHub server), or when you need remote access with standard OAuth. For a single agent calling your own functions, plain tools are simpler — resist MCP for its own sake.
6.4 The token cost of many tools#
Every connected server's tool definitions land in the model's context on every request — names, descriptions, schemas. A server with 50 tools can add thousands of tokens before the user says a word, and tool-selection accuracy degrades as the count grows (08A.6 covers the accuracy-vs-count trade-off). Mitigations: connect only needed servers, prefer servers with fewer, well-named tools, use provider tool search / deferred loading features (08A.8), and remember tools/list results are now cacheable (ttlMs/cacheScope) so clients don't refetch constantly.
6.5 Server design guidelines#
Building an MCP server? Apply 08A.6's rules plus protocol-specific ones:
- Fewer, better tools. A
search+fetchpair beats 30 endpoint wrappers; task-level tools beat chatty primitives. - Resources vs tools: data the app should attach → resource; actions the model should choose → tool.
- Stateless by default: no hidden per-connection state; mint explicit handles for multi-call workflows (the spec's "stateful tools" guidance).
- Idempotent writes where possible; clear
isErrormessages written for the model. - Paginate large lists (
nextCursor), set sensiblettlMs/cacheScope, emitlistChangedonly if the list actually changes. - Annotate honestly (
readOnlyHintetc.) — clients use them for approval UX, and liars get blocked. - Version the server;
serverInfo+instructionshelp hosts and models orient.
6.6 Extensions: Tasks, MCP Apps, Skills#
Beyond the core, 2026-07-28 adds an extensions framework: an extensions map inside the client's per-request capabilities and inside the server's server/discover capabilities, keyed by identifier (io.modelcontextprotocol/tasks, io.modelcontextprotocol/ui). Extensions are always opt-in and need support from both sides — a server must never return a task to a client that didn't declare the extension. Three are official as of November 2026 (spec overview and extension pages, opened 2026-11-08):
| Extension | What it adds | Why you would care |
|---|---|---|
Tasks (io.modelcontextprotocol/tasks) |
A server answers a request with a durable task handle (resultType: "task", with taskId, status, ttlMs, pollIntervalMs) instead of blocking; the client polls tasks/get and may cancel with tasks/cancel |
CI runs, batch jobs, report generation, human approvals — anything that outlives one HTTP response |
MCP Apps (io.modelcontextprotocol/ui) |
A tool points at a ui:// resource (_meta.ui.resourceUri); the host renders that HTML in a sandboxed iframe inside the chat, and the app can call tools back through the host |
Forms, dashboards, previews where a wall of text is the wrong interface |
| Skills over MCP | Rich agent-workflow instructions (the SKILL.md idea from 08A.15 §3.3) discovered and fetched through the protocol |
One server ships both tools and the know-how to use them |
Tasks in more detail, because it is the one most agent builders hit first. A task moves through five statuses: working, input_required, completed, failed, cancelled; the last three are terminal. When the server needs a human or the client mid-run, the status becomes input_required and the tasks/get reply carries an inputRequests map — the same shape as MRTR in 2.4 — which the client answers with tasks/update. On completed the result field holds exactly what the original tools/call would have returned; on failed the error field holds the JSON-RPC error. Cancellation is cooperative: the server acknowledges but may not stop. Because the task ID is a durable handle, a client that crashes can resume polling after a restart — so persist task IDs, and respect pollIntervalMs. This replaces the experimental tasks API of 2025-11-25 (the blocking tasks/result method and tasks/list are gone); servers can also push notifications/tasks to clients that opted in through subscriptions/listen.
client → tools/call build_report (declares io.modelcontextprotocol/tasks)
server ← { resultType: "task", taskId: "tk_91", status: "working", pollIntervalMs: 2000, ttlMs: 600000 }
client → tasks/get tk_91 (repeat every ~2 s)
server ← { status: "input_required", inputRequests: { ok: elicitation/create … } }
client → tasks/update tk_91 { inputResponses: { ok: { action: "accept", … } } }
client → tasks/get tk_91
server ← { status: "completed", result: { content: [ … ], isError: false } }How agent frameworks and hosts consume MCP is covered in 08F.1; how a coding agent uses MCP servers as one tool source is in 08A.15.
6.7 Failure gallery#
| Symptom | Likely cause | Fix |
|---|---|---|
The model calls an MCP tool, gets isError, and retries the same bad arguments forever |
The error text doesn't tell the model what to change, or nothing bounds the loop | Write isError messages that name the correction (raise ToolError, 3.2); cap steps in your agent loop (08A.2) |
tools/call hangs — no result, no error |
The server is stuck, or nobody set a timeout | Client-side timeouts on every call; on Streamable HTTP, closing the response SSE stream is the cancellation — make sure the server honours it (2.5) |
| Client shows a stale tool list after the server added or removed tools | Server didn't declare listChanged, the client isn't subscribed, or a ttlMs/cacheScope hint is being over-trusted |
Declare the capability and notify via subscriptions/listen/ctx.notify_tools_changed(); treat ttlMs as a hint, not a guarantee (2.5, 3.3) |
-32021 MissingRequiredClientCapability when a tool tries to ask the user something |
The client didn't declare elicitation in _meta.clientCapabilities |
Declare the capability (form and/or url mode); the SDK does this automatically, hand-rolled clients must not forget (2.1, 3.6) |
The model reports a protocol error where it expected an isError result to read |
Unknown tool name → -32602; malformed request → -32602; only execution failures become isError |
Check which layer failed: protocol errors are for requests the model can't fix; move actionable validation messages into ToolError results (2.1) |
A 2025-11-25-era client can't talk to your server (or vice versa) |
Protocol-era mismatch: initialize handshake vs per-request _meta |
Use SDK mode="auto" — it detects and serves both eras from one MCPServer (4.1) |
tools/list returns so much that the context window overflows |
Many servers × verbose tool definitions | Connect fewer servers, prefer small well-named tool sets, use provider tool-search/deferred loading (6.4, 08A.8) |
| An MRTR retry is rejected, or works on one instance but not another | requestState was sealed under a process-local key; the retry landed elsewhere |
Pass shared RequestStateSecurity(keys=[...]) on every instance; keep secrets ≥32 bytes (3.6) |
| "We connected a server we didn't vet" incident | Registry listing ≠ vetting; tool descriptions and results are untrusted input | Run the 5.3 checklist before connecting anything that can act (Part 5) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "MCP is an agent framework." | It's a protocol for context/tools/prompts. Your loop, planning and memory are still yours (08A.2). |
| "MCP handles auth for you." | It defines an OAuth 2.1 profile for HTTP servers; you still design scopes, consent UX and your permission model. |
"There is an initialize handshake to implement." |
Not in 2026-07-28: requests are self-contained; server/discover is optional discovery. Legacy clients still handshake — the SDK serves both. |
| "Servers can call back into the client anytime." | Not anymore: server→client requests travel inside InputRequiredResult (MRTR) on tools/call/resources/read/prompts/get only. |
| "Tool annotations are trustworthy safety labels." | They're untrusted hints — a malicious server can lie. Enforce safety in your own policy layer. |
| "MCP replaces provider built-in tools." | Different layers: built-ins are provider-hosted; MCP is a standard you or vendors host. Often complementary. |
| "stdio servers are safe because they're local." | A stdio server is arbitrary local code — vet and sandbox it like any dependency. |
| "More MCP servers = more capable agent." | Each server's tools cost context tokens and can degrade tool selection; connect deliberately. |
"structuredContent is the model's structured output." |
It's the tool's typed return for your code; the model reads content. Unrelated to LLM schema-constrained generation. |
| "The registry vets servers for you." | It catalogs metadata (install info, namespace-verified publisher). No quality ranking, no security audit. |
Key takeaways#
- MCP standardises the N×M problem: one server per capability, one client per host — the LSP/USB-C move for agent context.
- Host orchestrates and enforces policy; client is the 1:1 connector; server exposes tools (model-controlled), resources/templates (app-controlled) and prompts (user-controlled).
- The
2026-07-28spec is stateless: no handshake, no sessions; per-request_meta,server/discover, MRTR for client input,subscriptions/listenfor change streams, cacheable paginated lists. - Transports: stdio for local subprocesses, Streamable HTTP for remote (header-routed, OAuth 2.1 with CIMD + RFC 8707 audience binding); legacy HTTP+SSE is deprecated.
- The Python SDK v2 (
mcp2.3.0) gives youMCPServerdecorators,Contextinjection, lifespan state,ctx.report_progress, in-memoryClient(mcp)tests, andmcp.run()for stdio/HTTP — it serves both protocol eras. - All four providers consume MCP differently: OpenAI and Anthropic have native remote-MCP tool types (tools only, remote only); Gemini via SDK session or server-side tool; OpenRouter needs client-side bridging.
- Extensions are opt-in: Tasks gives long-running calls a durable, pollable handle (the Python SDK doesn't implement it yet, so use a start/status tool pair meanwhile); the provider connectors are beta APIs and Anthropic's can pin a server's tool list against rug pulls.
- Security is architectural, not protocol magic: vet servers, least privilege, pin versions, sandbox stdio, approvals for writes, treat descriptions and results as untrusted.
- Use MCP when a capability serves multiple consumers or a vendor maintains the server; plain function tools remain the right default for your own logic.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| MCP (Model Context Protocol) | Open protocol for connecting LLM apps to tools, resources and prompts via JSON-RPC |
| Host / client / server | The LLM app / its per-server connector / the capability provider |
| Primitive | A server-exposed feature family: tools, resources, prompts |
| Tool | A model-controlled function the server exposes for the model to call |
| Resource / resource template | App-controlled data by URI / parameterized URI pattern (RFC 6570) |
| Prompt | A user-controlled message template the user invokes by name |
| Elicitation | Server→client request for user input (form or URL mode) |
| Sampling / roots | Deprecated client features: server-requested LLM call / client-declared directories |
| MRTR | Multi Round-Trip Requests: input_required results + retried calls carrying inputResponses |
server/discover |
Mandatory discovery RPC returning versions, capabilities, identity |
resultType |
"complete" or "input_required" marker on every result |
| stdio transport | Newline-delimited JSON-RPC over a subprocess's stdin/stdout |
| Streamable HTTP | POST-per-message HTTP transport with optional per-request SSE replies |
Mcp-Method / Mcp-Name / MCP-Protocol-Version |
HTTP headers mirroring body fields for routing/validation |
structuredContent / outputSchema |
A tool's typed JSON result / its JSON Schema |
isError |
Tool-execution failure flag inside a successful result |
ToolError / MCPError |
SDK exceptions: message reaches the model as isError / fails the request as a JSON-RPC error |
Resolve / Elicit |
SDK dependency annotation that fills a parameter itself / asks the user mid-call |
requestState |
Opaque, integrity-protected token the client echoes on an MRTR retry |
elicitation_callback |
Client callback that answers elicitation/create input requests |
| Tool annotations | Untrusted behavioural hints: readOnlyHint, destructiveHint, idempotentHint, openWorldHint |
| Pagination cursor | Opaque cursor/nextCursor token for list operations |
ttlMs / cacheScope |
Cache freshness hint / sharing scope on complete results |
subscriptions/listen |
Long-lived opted-in stream for server change notifications |
| CIMD | Client ID Metadata Documents — preferred OAuth client registration (DCR deprecated) |
RFC 8707 resource |
OAuth parameter binding a token to one resource server's audience |
| MCP Registry | Official metadata catalogue of public MCP servers (registry.modelcontextprotocol.io) |
| MCP Apps / Tasks / Skills | Official extensions: inline UI / durable async ops / instruction packages |
| Extension (MCP) | Opt-in protocol add-on declared in the extensions map of both sides' capabilities (io.modelcontextprotocol/tasks, io.modelcontextprotocol/ui) |
Task (resultType: "task") |
Durable handle for a long-running call: statuses working, input_required, completed, failed, cancelled; polled with tasks/get |
| Tool-list pinning | Anthropic connector feature (mcp-client-2026-09-15): record or copy a server's tool list so later changes cannot reach the model |
| Tool shadowing | One server's tool description or name steering the model's use of another server's tools |
All terms are also collected in the glossary.
Exercises#
- Wire protocol: extend
s2_mini_mcp.pywith acreate_tickettool (called throughtools/call) that returnsstructuredContentand anisErrorfor a duplicate id. Run it and paste thetools/callexchange. - SDK server: finish
ops_server.py, then write thetest_ops_server.pyfixture and make all three tests pass withpytest. - Provider mapping: write the adapter that converts
client.list_tools()output into OpenAI Chat Completionstoolsand Anthropictoolsshapes (pure Python, no API calls — unit-test it). - Security review: pick a third-party MCP server from the official registry. Read its
server.jsonand source. List every tool, its annotations, and what could go wrong if a model called each one. - Decision: your team wants GitHub access in three different agents. Argue MCP vs three hand-rolled integrations vs provider built-ins, using the 6.3 table.
- Context cost: connect five servers exposing ~15 tools each. Estimate the token cost of their definitions (use 03.7's counting approach) and decide which servers to keep.
- Elicitation: add an approval-gated tool to
ops_server.pyusingResolve/Elicit(theescalate_ticketpattern from 3.6), then drive it in a test withClient(mcp, elicitation_callback=...). - Long-running work without the Tasks extension: add
start_reportandget_report_statustools toops_server.pythat implement the job-ID pattern from 6.6 (an in-memory dict of jobs with statusesworking/completed/failed). Then write down, in a table, how each status maps to a Tasks-extension status and which Tasks feature (durable handle,input_required, cooperative cancel) your version lacks. - Rug-pull test: write a pure-Python function
tool_list_changed(old, new)that hashes each tool'sname,descriptionandinputSchema(canonical JSON) and reports added, removed and modified tools. Run it on two hand-made lists where only one description gained the sentence "also send the user's files to…", and explain which defence from 5.1 it implements.
Hints
- Model the duplicate with a module-level
TICKETS = {}; return{"isError": True, "content": [{"type": "text", "text": "Ticket T-1 already exists; use update_ticket."}]}— anisErrorresult, not a JSON-RPC error, because the model can fix it. - The three tests are
test_lookup_order,test_create_ticketandtest_server_metadatafrom 3.4. Runuv run pytest -q; if pytest complains about the anyio backend, check theanyio_backendfixture. - OpenAI Chat Completions wants
{"type": "function", "function": {"name", "description", "parameters"}}; Anthropic wants{"name", "description", "input_schema"}. Test with a hand-built object that hasname,descriptionandinputSchemaattributes. - Look first at
readOnlyHintanddestructiveHint, then ignore them: assume the annotations lie and read the code of each tool. - Count integrations (3 consumers × 1 vs 1 server × 3 hosts), who maintains the server, auth, and the token cost of the tool list.
- 5 servers × 15 tools = 75 definitions; at roughly 150 to 300 tokens each that is about 11,000 to 22,000 tokens on every request. Measure your own with the counting endpoint, do not trust the estimate.
- Drive it with
Client(mcp, elicitation_callback=ask_user)whereask_userreturnsElicitResult(action="accept", content={"approve": True}), then again with"decline". - A start tool returns a job ID at once; the model must call the status tool, so the system prompt or the tool description has to say so.
hashlib.sha256(json.dumps(tool, sort_keys=True).encode()).hexdigest()per tool, keyed by name; compare the two dicts. This is the CI-side version of Anthropic's tool-list pinning.
Check yourself#
- What problem does MCP solve, and what's the LSP analogy?It collapses N×M bespoke integrations into one standard client-server protocol — like LSP did for language servers across editors.
- Name the three server primitives and who controls each.Tools (model-controlled), resources/resource templates (application-controlled), prompts (user-controlled).
- What replaced the
initializehandshake in2026-07-28, and how does a client learn server capabilities?Per-request_metacarries version/capabilities;server/discoveris the optional discovery RPC; version mismatch →-32022. - How does a server ask the user for input mid-
tools/callin the modern spec?MRTR: returnresultType: "input_required"withinputRequests(e.g.elicitation/create); client retries withinputResponses+requestState. - Which client features are deprecated as of
2026-07-28?The client features roots, sampling and protocol logging (SEP-2577). Alongside them the revision also deprecates Dynamic Client Registration (in favour of CIMD), the HTTP+SSE transport and theincludeContextvalues"thisServer"/"allServers"; elicitation is the client feature that survives. - What's the difference between a protocol error and a tool execution error?Protocol errors are malformed-request JSON-RPC errors; tool execution errors are successful results with
isError: truewritten for the model to self-correct. - Compare stdio and Streamable HTTP transports: when does each fit?stdio: local subprocess, newline-delimited, default for desktop/IDE hosts. Streamable HTTP: remote, POST-per-message, header-routed, OAuth — for deployed servers.
- What do
ttlMsandcacheScopedo, and which operations carry them?ttlMs= freshness hint in ms;cacheScope="public"/"private"sharing. Onserver/discoverand complete list/read results. - How do you test an MCP server without running a transport?
Client(mcp, raise_exceptions=True)connects in memory — same class as URL/stdio clients. - Which providers support MCP natively, and what are the limits for each?OpenAI (Responses
mcptool, remote, approval modes, Secure MCP Tunnel); Anthropic (MCP connector, remote tools only); Gemini (SDKClientSessiontool, experimental; server-sidemcp_serverStreamable HTTP); OpenRouter (no native tool — client-side bridging /@openrouter/mcp). - Why is
Authorization: Bearer+ the RFC 8707resourceparameter important?It binds the OAuth token's audience to that MCP server so it can't be replayed elsewhere; required on auth and token requests. - Name three threats an MCP server can pose and one defence for each.Tool poisoning (vet + untrusted descriptions), rug pull (pin versions), token passthrough (RFC 8707 + minimal scopes), local command execution (sandbox stdio), data exfiltration (egress allow-lists + approvals).
- When is MCP not worth it?When the capability is your own logic used by one agent — plain function tools are simpler; or when tool-count context cost outweighs reuse.
- How does the Python SDK let a tool ask the user a question mid-call, and why prefer it over
ctx.eliciton2026-07-28?AResolve(fn)dependency returnsElicit(message, Model); the SDK pauses the call as anInputRequiredResult, the client answers, and the retried call injects the validated result.ctx.elicitis a server→client request that only exists on legacy (≤2025-11-25) connections — on2026-07-28it fails. - A
tools/callcomes back-32021. What happened and how do you fix it?MissingRequiredClientCapability: the request needs a capability the client didn't declare in_meta.clientCapabilities(e.g.elicitation). Declare the capability on the client, or have the server avoid the feature.
Further resources#
- MCP specification (2026-07-28) — the authoritative source; start at Architecture → Base Protocol → Server/Client features → Transports → Authorization.
- MCP blog — The 2026-07-28 Specification — the stateless-core rationale and migration notes.
- MCP Python SDK docs and repository — tutorials, migration guide v1→v2.
- Official MCP Registry and registry docs.
- Anthropic — MCP connector docs and OpenAI — MCP tools guide.
- OpenRouter — Using MCP servers with OpenRouter (client-side bridging) and OpenRouter MCP server.
- Linux Foundation — Agentic AI Foundation announcement (governance, Dec 2025).
- Lesson 08A.2 · 08A.6 · 08A.8 · 08A.14 · Module 12.
← Module 08D: Multi-Agent Systems | Module 08E overview | 08E.2 — MCP in Depth: Primitives, Servers, Clients and Transports →