08E.2 MCP in Depth: Primitives, Servers, Clients and Transports

Agents & multimodalLesson 2 of 49,325 words9 parts
Module 08E · 0 of 4 lessons done
  1. 1
  2. 2
  3. 3
  4. 4

Lesson 08E.1 introduced the Model Context Protocol (MCP): what it is, the three server primitives, the SDK and the security model. This lesson goes one level down. You will build a real MCP server and a real MCP client that talk to each other over stdio, using only the Python standard library, so you can see every byte that crosses the wire. Then you will see how that pair maps onto the official Python SDK, learn exactly how capability negotiation and the connection lifecycle work in the current protocol revision (including the legacy handshake and the probe that tells the two apart), and compare the two transports (stdio for local servers, Streamable HTTP for remote ones) so you can choose between them. The next lesson, 08E.3, covers what changes when a server is remote: OAuth, gateways and managing many servers.

What you'll learn

  • The three server primitives, tools, resources and prompts, as design choices: who controls each one, which to pick for a given need, and what a good definition looks like
  • The JSON-RPC shape of an MCP exchange, field by field, and the difference between a protocol error and a tool error
  • Capability negotiation and lifecycle in the current revision (2026-07-28): no handshake, per-request capabilities, server/discover, version errors, and how a client works out whether it is talking to a modern or a legacy server
  • The client-side features, elicitation, sampling and roots, briefly, with their current status (sampling and roots are deprecated)
  • How to build an MCP server and an MCP client over stdio from scratch (stdlib only, run for real), and how that pair maps onto the official mcp SDK
  • stdio vs Streamable HTTP: framing, headers, shutdown, statelessness, security checks, and how to choose
  • How provider APIs reach MCP servers (OpenAI Responses remote MCP tool, Anthropic MCP connector) and when to use your own client instead
  • How to evaluate MCP tool use, with pointers into Modules 10A and 10B

What you don't need

  • API keys. The server and client you build run locally with no network and no key. The SDK and provider facts are checked against the official docs, and no provider call is made here.
  • Docker or any running service. The server is a subprocess of the client, and the Streamable HTTP part is pure functions with no sockets.
  • To have read the whole of 08E.1. You do need its basics (what MCP is, who host, client and server are). This lesson links to the exact sections instead of repeating them.

Setup

The runnable programs need Python 3.11 or newer and nothing to install. As of 1 December 2026 the official SDK is the mcp package (pip install "mcp[cli]" or uv add "mcp[cli]"), but none of the programs in this lesson import it, and nothing here needs a key or a network.

bash
mkdir mcp-in-depth && cd mcp-in-depth
python3 --version        # 3.11 or newer

Save each program under the name in its first comment and run it with python3 <file>.


What you must be able to do after this lesson#

  • Choose between a tool, a resource and a prompt for a given capability, and say who controls each
  • Read an MCP request and reply field by field, and tell a protocol error from a tool execution error
  • Explain how a client works out whether a server speaks the modern or the legacy protocol, and what it does in each case
  • Build and run an MCP server and client over stdio with the standard library, keeping stdout for protocol messages only
  • Check the Streamable HTTP headers against the request body and reject a mismatch
  • Choose between stdio, Streamable HTTP and a provider connector for a given server, with a reason
  • Write a small eval for an MCP server (conformance checks) and for an agent using it (tool-call precision and recall)

Why this matters for an AI engineer#

Most engineers meet MCP as a config line: paste a server URL into a host and tools appear. That works until something breaks. A tool call fails with an error code you have never seen. A server works on your laptop and fails behind the company load balancer. Two servers disagree about a version. The agent works with one client and not another. To debug any of that you must know what is actually on the wire, and the quickest way to learn it is to build both ends once.

You'll hear... You'll understand it after...
"Should that be a tool, a resource or a prompt?" Part 2
"Which MCP spec version do we target?" 1.2 The specification revision
"Why is there no initialize any more?" Part 3
"The client says MissingRequiredClientCapability." 3.4 Capability gating
"Sampling and roots are deprecated?" Part 4
"Show me the actual bytes." Part 5
"How do I write this with the SDK?" Part 6
"stdio or Streamable HTTP?" Part 7
"Can the model provider call my MCP server directly?" Part 8

Part 1: What this lesson adds to 08E.1, and which spec we target#

Reference

This part is a short recap. 08E.1, Parts 1 and 2 already explain the revision, the JSON-RPC shapes and the per-request _meta. Read them first. Here is only what you need in your head for the rest of this lesson.

1.1 Where this lesson fits#

08E.1, Part 1 explains the N by M problem and the host, client and server roles. 08E.1, Part 3 builds a server with the SDK, and 12.6, Part 4 covers MCP security. This lesson adds three things.

  1. A wire-level build. SDK code hides the protocol. Here you write both ends yourself, so each rule in the specification becomes a few lines of code you can read and break.
  2. Precision about negotiation and lifecycle. The modern shape is in 08E.1, 2.2. Here you also see the legacy shape and the probe that tells them apart.
  3. A transport comparison you can act on. stdio and Streamable HTTP differ in more than "local vs remote": framing, headers, who owns the process, what shutdown means, and what a gateway can see.

1.2 The specification revision, and what is deprecated#

MCP versions its specification by date: the identifier is the last date on which a backwards-incompatible change was made (08E.1, 1.4 has the side-by-side of the old and new designs). Facts checked against the official versioning page and deprecated features registry on 2 December 2026 (as of 1 December 2026):

  • The current revision is 2026-07-28. Earlier revisions you will still meet: 2025-11-25, 2025-06-18, 2025-03-26 (Streamable HTTP introduced) and 2024-11-05 (HTTP+SSE).
  • Every request declares its version in _meta under io.modelcontextprotocol/protocolVersion, and on Streamable HTTP also in the MCP-Protocol-Version header. The server accepts or rejects each request independently.
  • Deprecated in 2026-07-28: Roots, Sampling, Logging (migration: tool parameters, provider APIs directly, stderr or OpenTelemetry) and Dynamic Client Registration (migration: Client ID Metadata Documents). The HTTP+SSE transport has been deprecated since 2025-03-26 (replaced by Streamable HTTP).
  • Earliest removal of the four newly deprecated features: the first revision released on or after 2027-07-28. The registry says no feature has been removed under the policy yet.

"Deprecated" means the feature still exists and still works. It means new code should not adopt it and existing code should plan to leave.

1.3 The anatomy of one exchange#

The shape of one tools/call is shown field by field in 08E.1, 2.1, 2.2 and 2.7: a request has an id, a method and params (with _meta carrying the version, the client info and the client capabilities), and the reply has the same id and a result with resultType, content (read by the model) and structuredContent (typed data for your code). The rest of this lesson is variations on it. One distinction matters from here on, because Part 5 shows both shapes:

Protocol error Tool execution error
Looks like {"id": 7, "error": {"code": -32602, "message": "..."}} A normal result with "isError": true and a text content block
Means The request was wrong: unknown method, bad parameters, unsupported version, missing capability The request was fine and the tool failed: bad business input, record not found
Who should react Your code The model, which reads the message and tries again
Example in this lesson Reading notes://99; wrong protocol version; missing capability delete_note with an id that does not exist

Part 2: Tools, Resources and Prompts as design choices#

08E.1, 2.3 defines the three primitives and 6.5 lists server design guidelines. This part extends them with a decision table, what a good definition contains and the rules for resources. The question here is different: given something your server should offer, which primitive is it, and how do you make the definition good?

2.1 Who is in control#

The three primitives are separated by who decides to use them: the model uses tools during its loop, the application (host) attaches resources, and the user picks prompts (08E.1, 2.3 has the table). The practical test: if the model should decide when it is needed, make it a tool. If the host or the user should decide, make it a resource or a prompt. A common mistake is to expose everything as a tool, because tools are the primitive every host supports. Resources and prompts are not supported equally everywhere (check your host), so some servers deliberately offer a read tool next to each important resource. The lesson on tool design, 08A.6, applies to every tool you expose, whether it is local or served over MCP.

2.2 What a good tool definition contains#

A tool is defined by name, description, inputSchema (JSON Schema), and optionally title, outputSchema, annotations and icons. The demo server's delete_note:

json
{
  "name": "delete_note",
  "description": "Delete a note by id. Asks the user to confirm first.",
  "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},
  "annotations": {"readOnlyHint": false, "destructiveHint": true, "idempotentHint": true}
}

Three points worth knowing.

  1. The description is a prompt. The model reads it to decide when to call the tool. "Delete a note by id. Asks the user to confirm first." tells the model both what the tool does and what to expect. 08A.6, 1.4 goes deep on this.
  2. Annotations are hints, not security. readOnlyHint, destructiveHint, idempotentHint and openWorldHint help a host decide whether to ask for approval. The specification tells clients to treat them as untrusted unless the server itself is trusted, because a malicious server can claim readOnlyHint: true on a tool that deletes things. Your policy layer must not depend on them. See 12.6, 4.2 on tool poisoning and rug pulls.
  3. The schema is the contract. The server should validate arguments against it before running anything. The SDK does this for you. In the stdlib server you will see where it belongs.

2.3 Resources and resource templates#

A resource is data identified by a URI. The server lists concrete resources with resources/list (our server has notes://index) and parameterised ones with resources/templates/list (notes://{id}, an RFC 6570 URI template). A client reads one with resources/read, and the reply is a list of contents, each with a uri, a mimeType and either text or a base64 blob.

Two design rules:

  • A resource is stable, addressable context. If the content is "whatever is true now about X", with an identifier, it is a resource. If it needs search or computation, it is a tool.
  • Not found is a protocol error. In the current revision reading a URI the server does not have returns -32602 (invalid params), where older revisions used -32002. A tolerant client treats both as "no such resource". You will see this in the demo output.

2.4 Prompts#

A prompt is a template the user invokes by name. prompts/list shows the names and arguments. prompts/get with arguments returns ready-to-send messages. The point of serving prompts over MCP is that the server author, who knows the domain, ships the instruction text. "Here is how our support team triages refunds" travels with the tools that make the triage possible.

2.5 A decision table#

You want to offer... Use Why
Search over notes Tool The model decides when to search and with what query
One note by id Resource template (and often a read tool too) Stable URI the host can attach
An index of all notes Resource Context the host can load once
"Delete note 3" Tool, with approval An action with side effects: annotate it and gate it
"Summarize my notes as bullets" Prompt The user picks the workflow, the server supplies the wording
A long report that takes minutes Tool (and the Tasks extension, or a job-id pattern) See 08E.1, 6.6

Part 3: Capability negotiation and lifecycle#

08E.1, 2.2 shows the modern, handshake-free lifecycle. This part adds what 08E.1 leaves out: the legacy handshake side by side, the probe a client uses to tell the two eras apart, and per-call capability gating.

Capabilities are declarations of what each side supports. Negotiation is how the two sides find out what the other declared, so neither calls something the other cannot do. The design changed completely in 2026-07-28, and the old design is still common, so you need both.

3.1 The modern design: nothing to open, everything per request#

In 2026-07-28 there is no connection handshake. A client may send tools/call as its very first message. Each request is self-contained because it carries three things in _meta (see 1.3): the protocol version and the client's capabilities are required, and the client info is optional but recommended. A request missing a required field is malformed: the server must reject it with -32602 (and with HTTP 400 on Streamable HTTP). The demo shows this in step 3b. (Source: versioning page, "Negotiation", read 2 December 2026.)

An open connection, such as a stdio process, is not a conversation or a session. A client may interleave unrelated requests on one process, and a server must not treat process identity as a stand-in for conversation identity. State that must span requests (a long task, a shopping cart) is referenced by an explicit identifier the client passes on each request. 08E.1, 1.4 explains why this design scales: any request can land on any instance behind a plain load balancer.

If a client wants to know what a server supports before calling anything, it sends server/discover, which servers MUST implement. The reply carries supportedVersions, capabilities, optional instructions (guidance for the model on using this server), _meta with io.modelcontextprotocol/serverInfo, and caching hints (ttlMs, cacheScope). Calling it is optional. It is useful for two things: showing the user what a server offers in one request, and, on stdio, probing whether the server is modern or legacy.

3.2 The legacy design: initialize#

Revisions up to 2025-11-25 open a connection with a handshake:

  1. The client sends initialize with its protocolVersion, its capabilities and its clientInfo.
  2. The server replies with the version it will use, its own capabilities, and its serverInfo.
  3. The client sends the notification notifications/initialized.
  4. Only then are other requests allowed.

Capabilities were negotiated once per connection, and over Streamable HTTP the server could hand out a session id in the Mcp-Session-Id header. Servers could also send their own requests (sampling, elicitation, roots) down an open stream. Many servers and clients in the wild still work this way, and the Python SDK serves both eras from one server object (see 08E.1, 2.2).

Legacy (2025-11-25 and earlier) Modern (2026-07-28)
First message initialize Any request, or optionally server/discover
Version agreed Once, in the handshake Declared on every request; each request accepted or rejected alone
Client capabilities Sent once in initialize Sent in _meta on every request
Server capabilities In the initialize result In the server/discover result
Server asks the client something A server-to-client request on an open stream An input_required result the client answers by retrying (MRTR)
HTTP session Mcp-Session-Id header None. A server that sees the header ignores it
Keepalive ping None. Liveness is the transport's job

3.3 The compatibility probe: modern or legacy?#

A client that wants to talk to both must find out which era a server speaks. The specification gives the rule for each transport.

On stdio, there is no status code to react to, so the client sends server/discover first (with its preferred modern version in _meta). Three outcomes:

Server's answer to the probe Meaning Client action
A DiscoverResult Modern server Pick a version from supportedVersions and continue
A recognised modern error such as UnsupportedProtocolVersionError Modern server, but it does not support the version you asked for Retry with a version from its supported list. Do not fall back to initialize
Any other error, or no answer in a reasonable time Legacy server Fall back to the initialize handshake

The fallback must not be keyed to one specific error code, because legacy servers answer an unknown pre-initialize request with implementation-defined errors (commonly -32601 or -32602) or not at all.

On Streamable HTTP, the client tries a modern request first. If the server returns 400 Bad Request, the client inspects the body before falling back: modern servers also use 400 for version errors, missing capabilities and header mismatches. A recognised modern JSON-RPC error means "this is a modern server, fix the request". An empty or unrecognised body means "legacy, fall back to initialize". (Both rules are in the transport pages of the 2026-07-28 specification, read 1 December 2026.)

You will implement the stdio probe in Part 5 and watch it work against a legacy server.

3.4 Capability gating and the three protocol errors#

Because capabilities arrive on every request, a server can check them per call. Our demo server's delete_note needs to ask the user to confirm, which needs the client's elicitation capability. If the request does not declare it, the server rejects the call with -32021 (MissingRequiredClientCapability) before it does anything, instead of failing halfway. The other two negotiation errors from the reserved MCP range are -32020 (HeaderMismatch, Part 7) and -32022 (UnsupportedProtocolVersion, with data.supported listing what the server does speak). 08E.1, 2.1 has the table.

(Source: the specification's base protocol page under "Error Codes", read 1 December 2026. For -32021 the error's data.requiredCapabilities lists the missing capabilities, and on HTTP the status must be 400. The demo uses that field name. The exact shape of its value is in the schema and was not checked here, so the demo's value is a guess: unverified as of 2026-12-02.)

3.5 Extensions ride on capabilities too#

Extensions (Tasks for long-running work, MCP Apps for inline UI) are always opt-in: the client lists them under an extensions key in its per-request capabilities, the server lists them in server/discover, and a server must never use an extension the client did not declare. 08E.1, 6.6 covers them.


Part 4: Client features: elicitation, sampling and roots#

Reference

So far requests flow from client to server. MCP also lets a server ask the client for something. 08E.1, 2.4 and 3.6 have the full treatment, the wire exchange and the SDK code, and 12.6, 4.3 and 4.4 give the security controls (elicitation can phish the user, sampling spends your quota on the server's prompt, roots can ask for too much). Status on 1 December 2026, from the deprecated features registry (read 2 December 2026):

  • Elicitation ("ask the user for structured input", in form or url mode) is current. It is not deprecated.
  • Sampling ("run an LLM completion for me"), Roots ("which directories are in scope?") and Logging are deprecated in 2026-07-28. Earliest removal: the first revision released on or after 2027-07-28.
  • How a server asks, with no open stream: MRTR. A modern server cannot send its own request. It replies resultType: "input_required" with inputRequests and an opaque requestState, the client gets the answer and retries the same call with inputResponses and the echoed requestState under a new id. requestState travels through the client, so a hostile client can modify, replay or transplant it: the specification requires servers to integrity-protect it whenever it can influence authorisation or business logic. The SDK does this for you. A hand-written server must do it itself, and the demo in Part 5 does (an HMAC).

Part 5: Build a server and a client over stdio#

08E.1, 2.8 shows a minimal stateless server over an in-memory pipe. This part goes further: two real processes talking over stdio, a client with a compatibility probe, a signed requestState, capability gating and a legacy mode.

Now the build. You will write an MCP server and an MCP client in the standard library, and run them against each other as two real processes.

5.1 The design#

Choice Decision Why
Transport stdio: the client launches the server with subprocess.Popen, messages are newline-delimited JSON The simplest transport, and the one a local host uses
Protocol era Modern (2026-07-28) by default. A --legacy flag makes the same server behave like a 2025-11-25 server So the client's compatibility probe has something to detect
Server content A notes store: tools search_notes, add_note, delete_note; resource template notes://{id}; resource notes://index; prompt summarize_notes One of each primitive
Interesting behaviour delete_note needs the client's elicitation capability and asks to confirm using MRTR with a signed requestState Shows capability gating and the round trip
Logging To stderr only stdout is the wire. One stray print to stdout breaks the protocol

The stdio rules from the specification, all of which the code follows:

  • Each message is one line of JSON and must not contain embedded newlines.
  • The server must not write anything to stdout that is not a valid MCP message, and must not write JSON-RPC requests to stdout (in the modern design).
  • The server may log to stderr. The client may capture it, forward it or ignore it, and should not assume stderr output means an error.
  • Shutdown: the client closes the server's stdin and waits. The server should exit promptly when stdin reaches end of file.

5.2 The server#

python
# mcp_stdio_server.py - a stdlib-only MCP server speaking newline-delimited JSON-RPC on stdin/stdout.
# Modern mode follows the 2026-07-28 wire shape (no handshake). `--legacy` mimics a 2025-11-25-era server.
import argparse, base64, hashlib, hmac, json, sys, time

MODERN, LEGACY = "2026-07-28", "2025-11-25"
SECRET = b"demo-only-secret"            # seals requestState; a real server loads this from a secret store
NOTES = {"1": "Buy milk", "2": "Ship the A5 lesson draft", "3": "Rotate the staging API key"}
META = "io.modelcontextprotocol/"

TOOLS = [
    {"name": "search_notes", "description": "Search notes by keyword. Returns matching ids and text.",
     "inputSchema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]},
     "annotations": {"readOnlyHint": True}},
    {"name": "add_note", "description": "Add a note and return its new id.",
     "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]},
     "annotations": {"readOnlyHint": False, "destructiveHint": False, "idempotentHint": False}},
    {"name": "delete_note", "description": "Delete a note by id. Asks the user to confirm first.",
     "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},
     "annotations": {"readOnlyHint": False, "destructiveHint": True, "idempotentHint": True}},
]
RESOURCES = [{"uri": "notes://index", "name": "index", "mimeType": "text/plain"}]
TEMPLATES = [{"uriTemplate": "notes://{id}", "name": "note", "mimeType": "text/plain"}]
PROMPTS = [{"name": "summarize_notes", "description": "Ask the model to summarize all notes.",
            "arguments": [{"name": "style", "description": "bullets or prose", "required": False}]}]

def log(text):                           # stdout is the wire, so logs go to stderr
    print(f"[server] {text}", file=sys.stderr, flush=True)

def seal(payload):                       # requestState travels through the client, so it is signed
    body = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
    return body + "." + hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()[:16]

def unseal(token):
    body, _, sig = token.partition(".")
    good = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()[:16]
    if not hmac.compare_digest(sig, good):
        raise ValueError("requestState failed integrity check")
    payload = json.loads(base64.urlsafe_b64decode(body))
    if payload["exp"] < time.time():
        raise ValueError("requestState expired")
    return payload

def text_result(text, **extra):
    return {"resultType": "complete", "content": [{"type": "text", "text": text}], **extra}

def call_tool(name, args, params, caps):
    if name == "search_notes":
        hits = {i: t for i, t in NOTES.items() if args["query"].lower() in t.lower()}
        return text_result(json.dumps(hits), structuredContent={"matches": hits})
    if name == "add_note":
        new_id = str(max(map(int, NOTES)) + 1)
        NOTES[new_id] = args["text"]
        return text_result(f"added note {new_id}")
    if name == "delete_note":
        if "elicitation" not in caps:    # this tool cannot work without asking the user
            return ("error", -32021, "MissingRequiredClientCapability: delete_note needs elicitation",
                    {"requiredCapabilities": {"elicitation": {}}})   # field name per spec; the value shape is this demo's guess
        if args["id"] not in NOTES:
            return {"resultType": "complete", "isError": True,
                    "content": [{"type": "text", "text": f"No note with id {args['id']}. Valid ids: {sorted(NOTES)}"}]}
        answers = params.get("inputResponses")
        if not answers:                  # round trip 1: ask the user (MRTR)
            state = seal({"tool": name, "id": args["id"], "exp": time.time() + 60})
            return {"resultType": "input_required", "requestState": state, "inputRequests": {"confirm": {
                "method": "elicitation/create", "params": {"mode": "form",
                "message": f"Delete note {args['id']}: {NOTES[args['id']]!r}?",
                "requestedSchema": {"type": "object", "properties": {"approve": {"type": "boolean"}},
                                    "required": ["approve"]}}}}}
        try:                             # round trip 2: verify the sealed state before trusting anything
            state = unseal(params.get("requestState", ""))
        except ValueError as exc:
            return ("error", -32602, str(exc), None)
        if state["tool"] != name or state["id"] != args["id"]:
            return ("error", -32602, "requestState was issued for a different call", None)
        answer = answers["confirm"]
        if answer.get("action") == "accept" and answer["content"].get("approve") is True:
            del NOTES[args["id"]]
            return text_result(f"deleted note {args['id']}")
        return text_result("cancelled by user")
    return ("error", -32602, f"Unknown tool: {name}", None)

def handle(msg, legacy, state):
    method, params, mid = msg.get("method"), msg.get("params") or {}, msg.get("id")
    meta = params.get("_meta", {})
    if mid is None:                      # notification: never answered
        log(f"notification {method}")
        return None
    def err(code, message, data=None):
        e = {"code": code, "message": message}
        if data is not None: e["data"] = data
        return {"jsonrpc": "2.0", "id": mid, "error": e}
    if legacy:
        if method == "initialize":
            state["initialized"] = True
            return {"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": LEGACY,
                    "capabilities": {"tools": {}, "resources": {}, "prompts": {}},
                    "serverInfo": {"name": "notes-legacy", "version": "0.9"}}}
        if not state.get("initialized"):
            return err(-32601, f"Method not found: {method}")
        caps = {}
    else:
        version = meta.get(META + "protocolVersion")
        if version is None or META + "clientCapabilities" not in meta:   # both fields are required on every request
            return err(-32602, "Invalid params: _meta needs protocolVersion and clientCapabilities")
        if version != MODERN:
            return err(-32022, "Unsupported protocol version", {"supported": [MODERN], "requested": version})
        caps = meta.get(META + "clientCapabilities", {})
    ttl = {"ttlMs": 60000, "cacheScope": "public"}
    if method == "server/discover" and not legacy:
        return {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete", "supportedVersions": [MODERN],
                "capabilities": {"tools": {}, "resources": {}, "prompts": {}},
                "instructions": "Personal notes. Search before adding. delete_note asks the user first.",
                "_meta": {META + "serverInfo": {"name": "notes", "version": "1.0"}}, **ttl}}
    table = {"tools/list": {"tools": TOOLS}, "resources/list": {"resources": RESOURCES},
             "resources/templates/list": {"resourceTemplates": TEMPLATES}, "prompts/list": {"prompts": PROMPTS}}
    if method in table:
        return {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete", **table[method], **ttl}}
    if method == "tools/call":
        log(f"tools/call {params['name']} args={params.get('arguments')}")
        out = call_tool(params["name"], params.get("arguments", {}), params, caps)
        if isinstance(out, tuple):
            return err(out[1], out[2], out[3])
        if legacy: out.pop("resultType", None)
        return {"jsonrpc": "2.0", "id": mid, "result": out}
    if method == "resources/read":
        uri = params["uri"]
        body = ", ".join(f"{i}: {t}" for i, t in NOTES.items()) if uri == "notes://index" else NOTES.get(uri.removeprefix("notes://"))
        if body is None:
            return err(-32602, f"Resource not found: {uri}")
        return {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete",
                "contents": [{"uri": uri, "mimeType": "text/plain", "text": body}]}}
    if method == "prompts/get":
        style = (params.get("arguments") or {}).get("style", "bullets")
        notes = "\n".join(f"- {t}" for t in NOTES.values())
        return {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete", "messages": [
                {"role": "user", "content": {"type": "text", "text": f"Summarize these notes as {style}:\n{notes}"}}]}}
    return err(-32601, f"Method not found: {method}")

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--legacy", action="store_true")
    legacy, state = parser.parse_args().legacy, {}
    log(f"started, mode={'legacy' if legacy else 'modern'}")
    for line in sys.stdin:               # EOF on stdin is the graceful-shutdown signal
        line = line.strip()
        if not line:
            continue
        try:
            reply = handle(json.loads(line), legacy, state)
        except json.JSONDecodeError:
            reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
        if reply is not None:
            sys.stdout.write(json.dumps(reply, separators=(",", ":")) + "\n")
            sys.stdout.flush()
    log("stdin closed, exiting")

if __name__ == "__main__":
    main()

Read these parts of it:

  • handle() is the whole protocol. It looks at method, checks the era, and returns a response or None (notifications get no answer). Everything else is application code.
  • call_tool() is where tool semantics live. It returns either a result dictionary or a tuple that handle() turns into a JSON-RPC error. That mirrors the split from 1.3: isError results for things the model can fix, JSON-RPC errors for protocol problems.
  • seal() and unseal() sign and verify requestState. The comparison uses hmac.compare_digest so the check does not leak timing information.
  • The for line in sys.stdin loop ends on end of file. That is the graceful-shutdown signal.

5.3 The client#

python
# mcp_stdio_client.py - a stdlib-only MCP client: launches the server as a subprocess and speaks JSON-RPC.
import json, subprocess, sys, threading

MODERN = "2026-07-28"
META = "io.modelcontextprotocol/"

class McpError(Exception):
    def __init__(self, error):
        super().__init__(f"{error['code']}: {error['message']}")
        self.error = error

class StdioClient:
    def __init__(self, command, capabilities=None, version=MODERN):
        self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE, text=True, bufsize=1)
        self.stderr_lines = []           # drain stderr in a thread so a chatty server can never block
        threading.Thread(target=lambda: [self.stderr_lines.append(l.rstrip()) for l in self.proc.stderr],
                         daemon=True).start()
        self.capabilities, self.version, self.next_id, self.era = capabilities or {}, version, 0, None

    def request(self, method, params=None, modern=None):
        self.next_id += 1
        params = dict(params or {})
        if modern if modern is not None else self.era != "legacy":
            params["_meta"] = {META + "protocolVersion": self.version,
                               META + "clientInfo": {"name": "demo-client", "version": "0.1"},
                               META + "clientCapabilities": self.capabilities}
        message = {"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}
        self.proc.stdin.write(json.dumps(message) + "\n")
        self.proc.stdin.flush()
        reply = json.loads(self.proc.stdout.readline())      # one request in flight, so the next line is ours
        assert reply["id"] == message["id"], "response id does not match request id"
        if "error" in reply:
            raise McpError(reply["error"])
        return reply["result"]

    def notify(self, method):
        self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": method}) + "\n")
        self.proc.stdin.flush()

    def connect(self):
        """Probe with server/discover; on an unrecognised error fall back to the initialize handshake."""
        try:
            info = self.request("server/discover", modern=True)
            self.era = "modern"
            return info
        except McpError as exc:
            if exc.error["code"] == -32022:                  # modern server, wrong version: do NOT fall back
                raise
            self.era = "legacy"
            result = self.request("initialize", {"protocolVersion": "2025-11-25", "capabilities": {},
                                  "clientInfo": {"name": "demo-client", "version": "0.1"}}, modern=False)
            self.notify("notifications/initialized")
            return result

    def call_tool(self, name, arguments):
        """tools/call with the MRTR retry loop: answer input_required, then retry the same call."""
        params = {"name": name, "arguments": arguments}
        for _ in range(3):
            result = self.request("tools/call", params)
            if result.get("resultType") != "input_required":
                return result
            answers = {key: self.ask_user(req) for key, req in result["inputRequests"].items()}
            params = {"name": name, "arguments": arguments, "inputResponses": answers,
                      "requestState": result["requestState"]}
        raise RuntimeError("too many input_required rounds")

    def ask_user(self, req):             # a real host shows UI; the demo auto-approves and says so
        print(f"   (host UI) server asks: {req['params']['message']} -> auto-approving")
        return {"action": "accept", "content": {"approve": True}}

    def close(self):
        self.proc.stdin.close()          # graceful shutdown: close stdin, wait for the server to exit
        code = self.proc.wait(timeout=5)
        return code

def show(label, value):
    print(f"{label}: {json.dumps(value, separators=(',', ':'))}")

Read these parts of it:

  • request() adds the _meta block on every modern request, which is the per-request capability declaration. In legacy mode it adds nothing.
  • A thread drains stderr. If the server writes more log lines than the pipe buffer holds and nobody reads them, the server blocks and the whole thing hangs. Always drain the child's stderr.
  • connect() is the compatibility probe from 3.3: try server/discover; on -32022 re-raise (modern server, wrong version); on any other error assume legacy and run the initialize handshake.
  • call_tool() has the MRTR loop. If the result is input_required, answer each request and retry the same call, at most three rounds.
  • close() closes stdin and waits, which is the shutdown sequence the specification describes.

5.4 The driver and the real output#

python
# run_a51_demo.py - drives the stdio server with the stdlib client (no SDK, no network).
import sys
from mcp_stdio_client import StdioClient, McpError, show

SERVER = [sys.executable, "mcp_stdio_server.py"]

print("== 1. Modern server: discover, then the three primitives ==")
c = StdioClient(SERVER, capabilities={"elicitation": {"form": {}}})
info = c.connect()
show("server/discover", {k: info[k] for k in ("supportedVersions", "capabilities", "instructions")})
show("tools/list names", [t["name"] for t in c.request("tools/list")["tools"]])
show("search_notes", c.call_tool("search_notes", {"query": "key"})["structuredContent"])
show("resources/templates/list", c.request("resources/templates/list")["resourceTemplates"])
show("resources/read notes://2", c.request("resources/read", {"uri": "notes://2"})["contents"][0]["text"])
show("prompts/get", c.request("prompts/get", {"name": "summarize_notes", "arguments": {"style": "bullets"}})["messages"][0]["content"]["text"])

print("\n== 2. Errors: protocol error vs tool error ==")
try:
    c.request("resources/read", {"uri": "notes://99"})
except McpError as exc:
    print("protocol error ->", exc)
show("tool error (isError result)", c.call_tool("delete_note", {"id": "99"}))

print("\n== 3. Elicitation round trip (MRTR) with a sealed requestState ==")
show("delete_note final result", c.call_tool("delete_note", {"id": "3"}))
show("remaining notes", c.call_tool("search_notes", {"query": ""})["structuredContent"])

print("\n== 3b. A request with no _meta is malformed ==")
try:
    c.request("tools/list", modern=False)
except McpError as exc:
    print("no _meta ->", exc)

print("\n== 4. Tampered requestState is rejected ==")
first = c.request("tools/call", {"name": "delete_note", "arguments": {"id": "1"}})
forged = first["requestState"][:-1] + ("0" if first["requestState"][-1] != "0" else "1")
try:
    c.request("tools/call", {"name": "delete_note", "arguments": {"id": "1"}, "requestState": forged,
              "inputResponses": {"confirm": {"action": "accept", "content": {"approve": True}}}})
except McpError as exc:
    print("forged state ->", exc)

print("\n== 5. Wrong protocol version ==")
bad = StdioClient(SERVER, version="2099-01-01")
try:
    bad.connect()
except McpError as exc:
    print("version error ->", exc, exc.error["data"])
bad.close()

print("\n== 6. Client without the elicitation capability ==")
plain = StdioClient(SERVER, capabilities={})
plain.connect()
try:
    plain.call_tool("delete_note", {"id": "1"})
except McpError as exc:
    print("capability error ->", exc, exc.error["data"])
plain.close()

print("\n== 7. Shutdown: close stdin and wait ==")
print("exit code:", c.close())
print("server stderr (never on the wire):")
for line in c.stderr_lines:
    print("  ", line)

print("\n== 8. Legacy server: probe fails, client falls back to initialize ==")
old = StdioClient(SERVER + ["--legacy"])
init = old.connect()
print("era:", old.era, "| protocolVersion:", init["protocolVersion"], "| serverInfo:", init["serverInfo"])
show("tools/list names (no _meta sent)", [t["name"] for t in old.request("tools/list")["tools"]])
show("legacy search_notes", old.call_tool("search_notes", {"query": "milk"})["structuredContent"])
print("exit code:", old.close())

Run it with python3 run_a51_demo.py. The output below is real (run on 1 December 2026 with Python 3.14, standard library only, no network):

text
== 1. Modern server: discover, then the three primitives ==
server/discover: {"supportedVersions":["2026-07-28"],"capabilities":{"tools":{},"resources":{},"prompts":{}},"instructions":"Personal notes. Search before adding. delete_note asks the user first."}
tools/list names: ["search_notes","add_note","delete_note"]
search_notes: {"matches":{"3":"Rotate the staging API key"}}
resources/templates/list: [{"uriTemplate":"notes://{id}","name":"note","mimeType":"text/plain"}]
resources/read notes://2: "Ship the A5 lesson draft"
prompts/get: "Summarize these notes as bullets:\n- Buy milk\n- Ship the A5 lesson draft\n- Rotate the staging API key"

== 2. Errors: protocol error vs tool error ==
protocol error -> -32602: Resource not found: notes://99
tool error (isError result): {"resultType":"complete","isError":true,"content":[{"type":"text","text":"No note with id 99. Valid ids: ['1', '2', '3']"}]}

== 3. Elicitation round trip (MRTR) with a sealed requestState ==
   (host UI) server asks: Delete note 3: 'Rotate the staging API key'? -> auto-approving
delete_note final result: {"resultType":"complete","content":[{"type":"text","text":"deleted note 3"}]}
remaining notes: {"matches":{"1":"Buy milk","2":"Ship the A5 lesson draft"}}

== 3b. A request with no _meta is malformed ==
no _meta -> -32602: Invalid params: _meta needs protocolVersion and clientCapabilities

== 4. Tampered requestState is rejected ==
forged state -> -32602: requestState failed integrity check

== 5. Wrong protocol version ==
version error -> -32022: Unsupported protocol version {'supported': ['2026-07-28'], 'requested': '2099-01-01'}

== 6. Client without the elicitation capability ==
capability error -> -32021: MissingRequiredClientCapability: delete_note needs elicitation {'requiredCapabilities': {'elicitation': {}}}

== 7. Shutdown: close stdin and wait ==
exit code: 0
server stderr (never on the wire):
   [server] started, mode=modern
   [server] tools/call search_notes args={'query': 'key'}
   [server] tools/call delete_note args={'id': '99'}
   [server] tools/call delete_note args={'id': '3'}
   [server] tools/call delete_note args={'id': '3'}
   [server] tools/call search_notes args={'query': ''}
   [server] tools/call delete_note args={'id': '1'}
   [server] tools/call delete_note args={'id': '1'}
   [server] stdin closed, exiting

== 8. Legacy server: probe fails, client falls back to initialize ==
era: legacy | protocolVersion: 2025-11-25 | serverInfo: {'name': 'notes-legacy', 'version': '0.9'}
tools/list names (no _meta sent): ["search_notes","add_note","delete_note"]
legacy search_notes: {"matches":{"1":"Buy milk"}}
exit code: 0

5.5 What the output proves#

Go through it section by section. This is the lesson in miniature.

  1. Discovery and the three primitives. server/discover returned the supported version, the capabilities and the instructions string in one call. The client then listed tools, called one, read a resource template and fetched a prompt. Every one is a single JSON line each way.
  2. Protocol error vs tool error. Reading notes://99 produced a JSON-RPC error with -32602. Deleting note 99 produced a successful response with isError: true and a message that names the valid ids, which a model can use on its next turn.
  3. The MRTR round trip. The first delete_note call did not delete anything. It returned input_required. The client "asked the user" (auto-approved here, and the code says so) and retried the same call with the answer and the sealed state. Only then did the server delete note 3. Note the server log on stderr: two tools/call delete_note lines for one logical deletion. Because the retry is a new request, that is how MRTR looks in logs.
  4. A malformed request is rejected. A request with no _meta (step 3b) got -32602, because the version and capabilities are required on every request.
  5. A tampered requestState is rejected. The client changed the last character of the signature, and the server refused with -32602. Without the HMAC a client could have swapped in a state for a different note.
  6. Version errors carry the fix. Asking for 2099-01-01 returned -32022 and the list of versions the server speaks, so a client can retry with one of them.
  7. Capability gating. A client that did not declare elicitation could not call delete_note. It got -32021 before the server did anything.
  8. Shutdown and stderr. Closing stdin ended the server with exit code 0. The server's log lines never appeared on the wire, only in the captured stderr.
  9. The legacy server. The server/discover probe failed with -32601, so the client ran initialize, sent notifications/initialized, and carried on without _meta. Its tools/list worked and its results had no resultType.

Part 6: The same pair with the official SDK#

Reference

In production you use the SDK, and 08E.1 already teaches it: your first MCPServer (3.1), the ops server (3.2), the in-memory test (3.4), running and packaging (3.5), the approval-gated tool with a sealed requestState (3.6) and the Client (4.1). So this part only maps the wire demo onto the SDK. Facts the author read in the Python SDK documentation on 1 December 2026 (not re-read on 2 December, see the unverified list): the high-level server class is MCPServer (from mcp.server import MCPServer, called FastMCP in v1); mcp.run() serves stdio by default; mcp.run(transport="streamable-http", port=3001) serves Streamable HTTP; the client class is Client, and its argument decides the transport (a URL string, a StdioServerParameters, or the server object itself for an in-memory test).

6.1 Wire demo to SDK: the mapping#

In the wire demo In the SDK
handle() dispatch on method The SDK's request router
TOOLS list with hand-written inputSchema Derived from type hints and docstrings
Hand-written seal() / unseal() Done for you in MRTR flows
connect() probe and fallback Done by Client when it connects (the default is automatic version detection, see 08E.1, 4.1)
Reading stderr in a thread Handled by the SDK's stdio transport
close() closes stdin Leaving async with Client(...)

In-memory tests cover tool behaviour. Use a real subprocess test (like the demo in Part 5) for the one thing they cannot cover: that your server writes nothing but protocol messages to stdout.


Part 7: stdio (local) vs Streamable HTTP (remote)#

08E.1, 2.6 describes the transports in a paragraph each. This part adds a side-by-side table, the Streamable HTTP details that trip people up, a runnable header check and a decision table.

A transport is how messages travel. The protocol meaning is identical on both. What differs is who starts the server, how messages are framed, what an intermediary can see, and how security works.

7.1 Side by side#

| | stdio |---|---|---| | Who runs the server | The client launches it as a child process | It runs independently (a service) and many clients connect | | Typical use | Local tools: files, git, a local database, a desktop host | Remote and shared servers, SaaS integrations, anything with several users | | Framing | One JSON message per line on stdin and stdout | Each message is its own HTTP POST to one endpoint (conventionally /mcp) | | Reply | A line on stdout | Either one JSON object or a stream of server-sent events (SSE) scoped to that request | | Logs | stderr | Normal server logging | | Metadata | Inline in the message body | In the body and mirrored in HTTP headers | | Authentication | None in the protocol. Credentials come from the environment | OAuth, see 08E.3 | | Cancellation | The client sends notifications/cancelled | Closing the response stream is the cancellation | | Shutdown | Close stdin, wait, then terminate if needed | Not applicable: the server keeps running | | If the server dies | The client restarts it and retries | The client retries the request (maybe on another instance) | | Isolation | The server is code running as the user. Not a security boundary | A network service behind your normal controls |

(Source: the stdio and Streamable HTTP pages of the 2026-07-28 specification, read 1 December 2026.)

7.2 Streamable HTTP in the current revision#

The details that trip people up, all from the current specification:

  • One endpoint, POST only. Every JSON-RPC message from the client is a new POST. A server that supports only this revision answers GET or DELETE with 405, ignores an Mcp-Session-Id header and does not mint session ids. (The standalone GET stream and protocol-level sessions were removed in 2026-07-28.)
  • The client sends Accept: application/json, text/event-stream and must handle both reply types. The server picks per request.
  • No server-initiated requests on the stream. A server cannot send a request to the client on an SSE stream. It returns input_required instead (MRTR).
  • Streams cannot be resumed. Last-Event-ID resumption is not supported. A broken response stream loses the in-flight request, and the client re-issues it as a new request. Make tool calls safe to repeat: the retry may land on another instance, and the first attempt may or may not have run. This is the idempotency discipline from 08A.6, 4.3.
  • Change notifications use subscriptions/listen. One long-lived request opens a stream for the notification types the client chose.
  • Headers mirror the body so intermediaries need not parse it. Every POST must carry MCP-Protocol-Version and Mcp-Method, and for tools/call, resources/read and prompts/get also Mcp-Name (the tool name or the resource URI). A server that processes the body must reject a request whose headers disagree with the body, with HTTP 400 and error -32020 (HeaderMismatch). Values that are not plain ASCII are carried as =?base64?...?=.
  • Security checks. The server must validate the Origin header and answer 403 for a bad one (this defends against DNS rebinding, where a website tricks your browser into talking to a local server). When running locally it should bind to 127.0.0.1, not 0.0.0.0. It should authenticate every connection.

7.3 Run the header checks yourself#

Because the headers exist so that a gateway or load balancer can route and rate-limit without parsing JSON, the validation is worth seeing. This program has no sockets. It builds requests, runs the checks a server or gateway should run and prints the result.

python
# http_headers_demo.py - the Streamable HTTP request checks a server or gateway can do WITHOUT a socket (stdlib only).
import base64, json

MODERN = "2026-07-28"
ALLOWED_ORIGINS = {"https://app.example.com"}

def encode_header_value(value: str) -> str:
    """Plain ASCII passes through; anything else is carried as =?base64?...?= (spec 2026-07-28)."""
    plain = all(0x20 <= ord(c) <= 0x7E for c in value) and value == value.strip()
    sentinel = value.startswith("=?base64?") and value.endswith("?=")
    if plain and not sentinel:
        return value
    return "=?base64?" + base64.b64encode(value.encode()).decode() + "?="

def decode_header_value(value: str) -> str:
    if value.startswith("=?base64?") and value.endswith("?="):
        return base64.b64decode(value[9:-2]).decode()
    return value

def build_post(method, params, name=None):
    body = {"jsonrpc": "2.0", "id": 1, "method": method, "params": {**params, "_meta": {
        "io.modelcontextprotocol/protocolVersion": MODERN,
        "io.modelcontextprotocol/clientInfo": {"name": "demo", "version": "0.1"},
        "io.modelcontextprotocol/clientCapabilities": {}}}}
    headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
               "MCP-Protocol-Version": MODERN, "Mcp-Method": method}
    if name is not None:
        headers["Mcp-Name"] = encode_header_value(name)
    return headers, body

def validate(headers, body):
    """What a gateway or server does first. Returns (http_status, detail)."""
    h = {k.lower(): v for k, v in headers.items()}           # header names are case-insensitive
    origin = h.get("origin")
    if origin is not None and origin not in ALLOWED_ORIGINS:
        return 403, "Origin not allowed (DNS-rebinding defence)"
    if "application/json" not in h.get("accept", "") or "text/event-stream" not in h.get("accept", ""):
        return 400, "Accept must list application/json and text/event-stream"
    version = h.get("mcp-protocol-version")
    meta_version = body.get("params", {}).get("_meta", {}).get("io.modelcontextprotocol/protocolVersion")
    if version is None or version != meta_version:
        return 400, f"-32020 HeaderMismatch: header {version!r} vs _meta {meta_version!r}"
    if version != MODERN:
        return 400, "-32022 UnsupportedProtocolVersion"
    if h.get("mcp-method") != body["method"]:
        return 400, f"-32020 HeaderMismatch: Mcp-Method {h.get('mcp-method')!r} vs body {body['method']!r}"
    if body["method"] in ("tools/call", "prompts/get", "resources/read"):
        body_name = body["params"].get("name", body["params"].get("uri"))
        header_name = h.get("mcp-name")
        if header_name is None or decode_header_value(header_name) != body_name:
            return 400, f"-32020 HeaderMismatch: Mcp-Name {header_name!r} vs body {body_name!r}"
    return 200, "ok: safe to route and rate-limit on the headers"

if __name__ == "__main__":
    headers, body = build_post("tools/call", {"name": "search_notes", "arguments": {"query": "key"}}, name="search_notes")
    print("good request          ->", validate(headers, body))
    print("bad Origin            ->", validate({**headers, "Origin": "https://evil.example"}, body))
    print("no Mcp-Name header    ->", validate({k: v for k, v in headers.items() if k != "Mcp-Name"}, body))
    swapped = {**headers, "Mcp-Name": "search_notes"}
    sneaky = json.loads(json.dumps(body)); sneaky["params"]["name"] = "delete_note"
    print("header says search, body says delete (a gateway allowed the header) ->", validate(swapped, sneaky))
    print("version mismatch      ->", validate({**headers, "MCP-Protocol-Version": "2025-11-25"}, body))
    print("lowercase header keys ->", validate({k.lower(): v for k, v in headers.items()}, body))
    print("\nnon-ASCII tool name encoding:")
    for value in ["search_notes", "recherche-été", " padded ", "=?base64?literal?="]:
        enc = encode_header_value(value)
        print(f"  {value!r:24} -> {enc:40} round-trips: {decode_header_value(enc) == value}")
Output · real, run on 1 December 2026, standard library only12 lines
good request          -> (200, 'ok: safe to route and rate-limit on the headers')
bad Origin            -> (403, 'Origin not allowed (DNS-rebinding defence)')
no Mcp-Name header    -> (400, "-32020 HeaderMismatch: Mcp-Name None vs body 'search_notes'")
header says search, body says delete (a gateway allowed the header) -> (400, "-32020 HeaderMismatch: Mcp-Name 'search_notes' vs body 'delete_note'")
version mismatch      -> (400, "-32020 HeaderMismatch: header '2025-11-25' vs _meta '2026-07-28'")
lowercase header keys -> (200, 'ok: safe to route and rate-limit on the headers')

non-ASCII tool name encoding:
  'search_notes'           -> search_notes                             round-trips: True
  'recherche-été'          -> =?base64?cmVjaGVyY2hlLcOpdMOp?=          round-trips: True
  ' padded '               -> =?base64?IHBhZGRlZCA=?=                  round-trips: True
  '=?base64?literal?='     -> =?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?=      round-trips: True

The fourth line is the important one. A gateway that allows Mcp-Name: search_notes while the body actually says delete_note has been fooled, because the header and the body disagree. The specification closes that hole by requiring every server that processes the body to reject mismatches. The note for intermediaries in the specification adds that a gateway enforcing policy on headers should also check that the version header names a revision that requires this validation, and reject older or missing versions instead of trusting unvalidated headers. 08E.3 builds a gateway on this idea.

7.4 Serving each transport with the SDK#

With the SDK the same server object serves both: mcp.run() for stdio, and mcp.run(transport="streamable-http", port=3001) for Streamable HTTP (defaults per the SDK docs read on 1 December 2026: host 127.0.0.1, port 8000, endpoint path /mcp; the transport options go to run(), not to the MCPServer(...) constructor). A client then connects with a URL such as Client("http://127.0.0.1:3001/mcp"). To put the server inside an existing web application, or to scale it, see the SDK's "Add to an existing app" and "Deploy & scale" pages and 08E.1, 3.5.

7.5 How to choose#

Question If yes
Does the server only wrap a remote API and need no local files? Prefer remote (Streamable HTTP). It runs no code on the user's machine and uses the protocol's authorization flow instead of a token in a local config file
Does it need the user's local files, local git repository or a local socket? stdio
Will many users or many agents share it? Streamable HTTP, behind a gateway (08E.3)
Is it for a single host on one machine and quick to try? stdio
Do you need per-user permissions and an audit trail? Streamable HTTP with OAuth
Do you need to reach it from a hosted model provider's API? Streamable HTTP (provider connectors cannot reach stdio, see Part 8)

Part 8: How provider APIs reach MCP servers#

Instead of running an MCP client in your code, you can let the model provider connect to a remote MCP server for you. You pass a server URL (and an OAuth token if needed), the provider lists the server's tools, the model calls them inside the provider's loop and the results come back in the response. 08E.1, 4.3 compares all four providers with an illustrative request for OpenAI and for Anthropic, and 08A.8, 2.8 and 3.8 have the provider details. This part adds only the decision. The facts below were re-checked against the official pages on 2 December 2026 (as of 1 December 2026):

  • OpenAI (MCP and connectors guide): add {"type": "mcp", ...} to tools in the Responses API. Fields include server_label, server_url, authorization (an OAuth access token), allowed_tools, require_approval ("always", "never" or an object that skips approval for named tools; approval is the default) and defer_loading. Streamable HTTP and HTTP/SSE are supported. The authorization value is not stored and does not appear in the response, so you send it on every request. tunnel_id reaches a private server through the Secure MCP Tunnel. connector_id is a legacy option, deprecated for models released after 1 September 2026. The guide says to use only remote servers you trust: OpenAI does not verify them, and a malicious server can extract data from the model's context.
  • Anthropic (MCP connector page): the feature is in beta, with beta header values mcp-client-2026-09-15 (adds tool-list pinning) and mcp-client-2025-11-20; mcp-client-2025-04-04 is deprecated, and header names have changed before. You pass mcp_servers (each with type: "url", a url, a unique name and an optional authorization_token) and one matching mcp_toolset per server in tools. Of the MCP specification only tool calls are supported (no resources, prompts or sampling). The server must be publicly exposed over HTTP (Streamable HTTP or SSE): local stdio servers cannot be connected. The feature is not eligible for zero data retention.

8.1 Your own client or the provider's connector?#

Provider connector (OpenAI mcp tool, Anthropic connector) Your own MCP client
Code you write A few request fields A client, plus the glue that maps MCP tools to the provider's tool format
Reaches stdio servers No (Anthropic says so explicitly. OpenAI offers a tunnel for private servers) Yes
Primitives Tools only on Anthropic's connector. Check OpenAI's page for the current list All of them, including resources and prompts
Where tool calls run In the provider's infrastructure, so definitions and results pass through it In your process
Control and audit The provider's approval items, plus what you log from responses Everything: your allowlist, your logs, your approvals
Data handling The provider's terms. Anthropic's connector is not ZDR eligible Yours
Best for Quick integration of a trusted remote server Anything needing policy, private servers, other primitives or provider independence

Part 9: Evaluate it#

You built a server and a client. How do you know an agent uses MCP tools correctly, and that your server is a good citizen? There are two different things to measure: the server (is it correct and well-formed?) and the agent using it (does it choose and call the right tools?).

Read the concept lessons first.

Then the DeepEval lessons (required track, tooling for the same ideas): 10B.2 fundamentals, 10B.3 judges and custom metrics, 10B.4 built-in metrics, 10B.5 tracing and agent evaluation, whose Part 12 covers the MCP metrics (what an MCP test case is, MCPUseMetric for one turn, the multi-turn variant and what these metrics can and cannot prove), 10B.6 datasets and simulation and 10B.7 red teaming, CI and platform.

Then, optionally, the Inspect lessons. The relevant one is 10B.14 Inspect: tools and agents (optional), whose Part 5 covers MCP tools in Inspect: the transports, how local stdio servers are host processes, the connection lifecycle and how to evaluate an MCP-using agent honestly. Its transport summary is the short version of Part 7 of this lesson. The rest of the Inspect track is in 10B.8, 10B.9, 10B.10, 10B.11, 10B.12, 10B.13, 10B.15, 10B.16 and 10B.17, all optional.

9.1 What to measure for this topic#

Two layers, in this order.

Layer 1: the server, with no model involved. These checks are deterministic and cheap, so run them on every change. The demo in Part 5 is already most of this test.

  • Conformance: server/discover answers; tools/list returns valid definitions; an unknown tool, a bad resource URI and a wrong version each produce the right error code.
  • Error shape: input errors come back as isError results with an actionable message, not as protocol errors or stack traces.
  • Transport hygiene: nothing but protocol messages on stdout; stderr carries the logs.
  • Safety properties: a forged requestState is rejected; a call without the needed capability is rejected before it does anything.

Layer 2: the agent using the server. These need a model, or a scripted stand-in.

  • Tool selection: did the agent pick the right tool? (Tool-call precision and recall, 10A.7, 4.2.)
  • Argument correctness: were the arguments valid against the schema and right for the task?
  • No forbidden calls: did the agent avoid tools it was not allowed to use?
  • Task success and cost per successful task: the outcome metrics from 10A.7, 5.6.

9.2 A concrete tiny eval design#

Part Choice
Inputs 12 tasks against the notes server: 4 search tasks, 3 add tasks, 2 delete tasks (one with a valid id, one with an invalid id), 3 that should need no tool (a general question)
Layer 1 checks Run the Part 5 driver as a test: 8 conformance assertions (discover, list, call, resource read, prompt get, unknown resource error, wrong-version error, forged-state rejection)
Layer 2 metrics Tool-call precision and recall against the expected calls; argument validity rate; share of "no tool needed" tasks where the agent made no call; task success rate
Pass rule All 8 conformance assertions pass (no tolerance). For the agent: tool-call recall of at least 0.9, precision of at least 0.9, zero calls to delete_note without a user approval event, and no drop in task success compared with the previous server version beyond the noise (compare with intervals, 10A.7, 5.2)

Decide the pass rule before you run it. Re-run the same set whenever you change a tool's name or description, because a description change can change which tool the model picks even if no code changed. That sensitivity is the main reason tool definitions deserve tests.


Common misconceptions#

  • "MCP is an agent framework." It is a protocol for exposing tools, resources and prompts. The agent loop, the memory and the planning are yours (or your framework's).
  • "Every MCP session starts with initialize." That was true up to 2025-11-25. In 2026-07-28 there is no handshake: each request carries its version and capabilities. Older servers still expect initialize, so a robust client probes.
  • "stdio is more secure because it is local." A stdio server is a program running with your permissions. The transport does not isolate it. Remote servers can be safer because they run no code on your machine and use real authorization.
  • "Annotations make a tool safe." readOnlyHint and friends are hints from the server. A host may use them for approval UX. A policy that trusts them can be fooled by a malicious server.
  • "Everything should be a tool." Tools are for what the model decides to do. Resources are context the application attaches, and prompts are workflows the user picks.
  • "Sampling and roots are the future of MCP." Both are deprecated as of 2026-07-28, with removal no earlier than the first revision released on or after 2027-07-28. Elicitation is the client feature that remains.
  • "A tool error should be a JSON-RPC error." Failures the model can fix belong in a successful result with isError: true and a message the model can act on. JSON-RPC errors are for broken requests.
  • "Provider connectors can use my local server." Anthropic's connector needs a publicly reachable HTTP server and does not connect to stdio. OpenAI's connector needs a server URL, or its tunnel for private servers.

Key takeaways#

  • The three primitives are separated by who decides: the model uses tools, the application attaches resources, the user picks prompts.
  • An MCP message is JSON-RPC. A request has id, method and params. A reply has the same id and result or error. A message with no id is a notification.
  • Protocol errors and tool errors are different shapes. Write tool errors for the model to read and act on.
  • The current revision is 2026-07-28. There is no handshake. Every request carries version, client identity and client capabilities in _meta. server/discover is mandatory for servers and optional for clients.
  • Probe to find the era. On stdio send server/discover. A modern error means modern, anything else means fall back to initialize. On HTTP, inspect the body of a 400.
  • A server can gate a call on a client capability and reject with -32021. Declaring a capability is a promise.
  • Elicitation stays. Sampling, roots and logging are deprecated. The earliest removal is the first revision released on or after 2027-07-28.
  • stdio frames one JSON message per line, uses stdout only for protocol messages, stderr for logs, and shuts down when stdin closes.
  • Streamable HTTP mirrors the method and name into headers so gateways can act without parsing the body, and servers must reject mismatches with -32020.
  • The SDK does the heavy lifting, but building the pair once makes its behaviour and its errors readable.

Terms introduced in this lesson#

Term Meaning
Capability negotiation How each side learns what the other supports, so neither uses a feature the other lacks. In 2026-07-28, per request, not once per connection
_meta The metadata object in a request's params. It carries the protocol version, client info and client capabilities
Handshake (initialize) The legacy opening exchange of initialize and notifications/initialized. Gone in 2026-07-28
Compatibility probe Sending a modern request first and falling back to initialize only if the server is not a modern one
Protocol error A JSON-RPC error reply: the request itself was wrong
MissingRequiredClientCapability (-32021) The error for a request that needs a client capability the client did not declare
UnsupportedProtocolVersion (-32022) The error for a version the server does not speak, with the supported list in data
Streamable HTTP The remote transport: each message is a POST to one endpoint, with a JSON or SSE reply
HeaderMismatch (-32020) The error when mirrored headers disagree with the body
DNS rebinding An attack where a website makes your browser talk to a local server. Defended by validating Origin and binding to localhost

Exercises#

  1. Add a tool. Add a count_notes tool to mcp_stdio_server.py that returns the number of notes as structuredContent. Run the driver and show the tools/list names and a tools/call result. Hint: add an entry to TOOLS, add a branch to call_tool(), and return text_result(str(len(NOTES)), structuredContent={"count": len(NOTES)}).
  2. Break the wire on purpose. Add print("debug") to the server's call_tool and run the driver. Describe the failure and explain why it points at the wrong line. Then change it to write to stderr. Hint: stdout is the wire, so the client reads debug as a message and json.loads fails on the next readline.
  3. Validate arguments. The stdlib server does not check arguments against inputSchema. Write a small validator (required keys present, string types) and return an isError result with an actionable message. Add a client call that triggers it. Hint: check required first, then type; the message should name the missing key and list the schema's keys.
  4. Cancel. Add a slow slow_search tool (use time.sleep) and a client method that sends notifications/cancelled with the request id. What does the server need to do for the cancellation to mean anything? Hint: the server reads stdin on one thread, so it cannot see the cancel while it sleeps; run tool calls on a worker thread and check a cancelled-ids set.
  5. Header gateway. Extend http_headers_demo.py so that validate also rejects a tools/call whose tool name is not in an allowlist you pass in, returning 403. Test it with a header that lies about the name. Hint: allowlist on the decoded body name after the mismatch check, never on the header alone.
  6. Era matrix. Write a table of four client-and-server pairs (modern client or legacy client, modern server or legacy server) and predict what happens in each. Check two of them with the demo code. Hint: a client that only speaks modern against a legacy server gets a probe failure, so it must report an unsupported server instead of guessing.

Check yourself#

  1. Who decides when a tool is used, when a resource is used and when a prompt is used?
  2. What is the difference between a protocol error and a tool execution error, and which one should the model read?
  3. What three things does every request carry in _meta in revision 2026-07-28?
  4. Is server/discover mandatory? For whom?
  5. On stdio, what does a client do if the server answers its server/discover probe with -32601? What if it answers with -32022?
  6. What does error -32021 mean, and why can a server use it without a session?
  7. Which of elicitation, sampling and roots is not deprecated, and what is the earliest removal date of the others?
  8. Why must a stdio server never write a log line to stdout?
  9. What do the Mcp-Method and Mcp-Name headers let a gateway do, and what must a server do if they disagree with the body?
  10. Why can't Anthropic's MCP connector use a local stdio server, and what is OpenAI's answer for private servers?

Further resources#

Existing lessons:

Official sources (all read on 1 December 2026):


← 08E.1 — The Model Context Protocol (MCP) | Module 08E overview | 08E.3 — Remote MCP: OAuth, Gateways and Many Servers →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close