MCP reference guide for AI engineers: the 2026-07-28 spec, primitives, transports and auth
MCP as of Nov 2026: primitives, stateless requests, server/discover, input_required, transports, OAuth, deprecations and real wire traffic.
This is a reference page for the Model Context Protocol (MCP) as it stands on 22 November 2026. The current revision is 2026-07-28, and https://modelcontextprotocol.io/specification/latest redirects to it. The Python SDK on PyPI is mcp 2.3.0, and its LATEST_PROTOCOL_VERSION constant is 2026-07-28.
The 2026-07-28 revision changed the protocol more than any release since Streamable HTTP arrived. There is no initialize handshake any more, no sessions, and servers no longer send requests to clients. Many tutorials, including some on this blog, were written against the older handshake model, so the first job of this page is to say which parts still hold.
If you have never run an MCP server, start with MCP from zero. If you are deciding between MCP and agent-to-agent protocols, read MCP vs A2A vs ANP. For several agents sharing servers with per-agent scoping, see multi-agent systems on MCP. This page covers what sits between them: the method surface, what goes over the wire, and what breaks.
Everything below was run with Python 3.15.2 and mcp 2.3.0 in a fresh venv. No model and no API key are involved; the "user" in the elicitation example is a stub callback.
Roles and message format#
MCP has three roles. The host is the LLM application: Claude Desktop, an IDE, or your own agent loop. The host runs one client per server connection. The server is a separate program that exposes capabilities. Messages are JSON-RPC 2.0, UTF-8 encoded.
+-------------------- host (LLM app) --------------------+
| model <--> agent loop |
| | | | |
| client A client B client C |
+-----------------|------------|--------------|-----------+
| stdio | HTTP POST | HTTP POST
+-----v----+ +----v-----+ +----v------+
| server A | | server B | | server C |
| (local) | | (remote) | | (remote) |
+----------+ +----------+ +-----------+
In 2026-07-28 there are only two message directions. Clients send requests and notifications; servers send responses and notifications (transports overview). A server that needs something from the client, such as a user's answer, has to ask for it inside a response. That one rule explains most of the other changes.
The primitives, and who controls each#
Servers offer three things, and the spec ties each to a different decision-maker.
| Primitive | Methods | Who decides to use it | Example |
|---|---|---|---|
| Tools | tools/list, tools/call |
The model | order_total(order_id) |
| Resources | resources/list, resources/read, resources/templates/list |
The host application | orders://index |
| Prompts | prompts/list, prompts/get |
The user | a "refund email" template |
The control column matters for security review. A tool can be called because of text the model read in a web page, so tools are where prompt injection does damage. A prompt runs only when a person picks it.
Clients used to offer three features back to servers. Their status in 2026-07-28:
| Client feature | Status | What to do instead |
|---|---|---|
| Elicitation (form and URL modes) | Active | Use it for confirmations and missing input |
| Sampling (server asks the client's LLM to generate) | Deprecated | Call an LLM provider API from the server |
| Roots (client tells the server which directories it may use) | Deprecated | Pass paths as tool arguments or server config |
Logging (notifications/message) |
Deprecated | Log to stderr on stdio, or use OpenTelemetry |
Deprecated features still work. The feature lifecycle policy sets a minimum twelve-month window before removal, and the spec keeps a registry of deprecated features. New code should not adopt them.
Elicitation has one hard rule worth repeating. Form mode must not be used to ask for sensitive data such as passwords or API keys; those go through URL mode, where the user completes the step in a browser and the value never passes through the client (elicitation spec).
What replaced the lifecycle handshake#
Before 2026-07-28 a connection started with initialize, the server answered with its version and capabilities, and the client sent notifications/initialized. Everything after that depended on session state.
Now each request carries its own context in params._meta (versioning page):
io.modelcontextprotocol/protocolVersionio.modelcontextprotocol/clientCapabilitiesio.modelcontextprotocol/clientInfo(should be sent)
Servers put io.modelcontextprotocol/serverInfo in each result's _meta. Servers must also implement server/discover, which returns supported versions and capabilities. Clients may call it first but do not have to. If the version is wrong, the server returns UnsupportedProtocolVersionError (code -32022) with a supported list, and the client retries with a version from that list.
The spec defines "legacy" (2025-11-25 and earlier) and "modern" (2026-07-28 and later) implementations, plus "dual-era" ones that speak both. On stdio, a dual-era client sends server/discover as a probe and falls back to initialize if the reply is not a recognised modern answer. The versioning page has a seven-row compatibility matrix. The row that bites people is legacy client against a modern-only server: it fails, and the old client has no way to move forward.
The SDK's Client class is dual-era by default (mode="auto"). You can see both behaviours with a small wiretap script that copies every line between client and server to a log file (it is in the next section).
Default Client(params), first two exchanges, lightly trimmed:
C->S {"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"mcp","version":"0.1.0"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{},"url":{}}}}}}
S->C {"jsonrpc":"2.0","id":1,"result":{"cacheScope":"private","capabilities":{"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":true},"tools":{"listChanged":true}},"resultType":"complete","supportedVersions":["2026-07-28"],"ttlMs":0,"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":""}}}}
C->S {"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28", ...}}}
The same server with Client(params, mode="legacy"):
C->S {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"mcp","version":"0.1.0"}}}
S->C {"jsonrpc":"2.0","id":1,"result":{"capabilities":{...},"protocolVersion":"2025-11-25","serverInfo":{"name":"orders","version":""}}}
C->S {"jsonrpc":"2.0","method":"notifications/initialized"}
C->S {"jsonrpc":"2.0","id":2,"method":"tools/list"}
In this test an MCPServer on 2.3.0 answered both, so it behaved as dual-era without extra setup. Note the new fields on every result: resultType (required, "complete" or "input_required"), and on list and read results, ttlMs plus cacheScope. Those two are caching hints from the new CacheableResult interface; the SDK client honours them by default.
A server that uses all three primitives and elicitation#
Setup:
python3 -m venv .venv
.venv/bin/pip install mcp # resolved to 2.3.0 on 2026-11-22
The server has two tools, one resource and one prompt. cancel_order asks the user before it deletes anything.
# server.py: one tool, one resource, one prompt, one tool that asks the user first
from typing import Annotated
from pydantic import BaseModel
from mcp.server.mcpserver import Elicit, ElicitationResult, MCPServer, Resolve
from mcp.server.mcpserver.exceptions import ToolError
server = MCPServer("orders")
ORDERS = {"A-1001": {"item": "USB-C cable", "price": 250.0, "qty": 4}}
@server.tool()
def order_total(order_id: str) -> float:
"""Return price * qty for an order, in rupees. Fails if the id is unknown."""
if order_id not in ORDERS:
# ToolError text goes back to the model; a bare KeyError would be hidden.
raise ToolError(f"unknown order id {order_id!r}; known ids: {sorted(ORDERS)}")
o = ORDERS[order_id]
return o["price"] * o["qty"]
class Confirm(BaseModel):
confirm: bool
def ask_confirm(order_id: str) -> Elicit[Confirm]:
# Runs before the tool body. On 2026-07-28 the SDK turns this into an
# InputRequiredResult and finishes the call when the client retries.
return Elicit(f"Cancel {order_id}? This cannot be undone.", Confirm)
@server.tool()
def cancel_order(
order_id: str,
answer: Annotated[ElicitationResult[Confirm], Resolve(ask_confirm)],
) -> str:
"""Cancel an order. Asks the user to confirm before doing anything."""
if answer.action == "accept" and answer.data.confirm:
ORDERS.pop(order_id, None)
return f"cancelled {order_id}"
return f"kept {order_id} (user action: {answer.action})"
@server.resource("orders://index", mime_type="text/plain")
def orders_index() -> str:
"""One line per open order."""
return "\n".join(f"{k}: {v['item']} x{v['qty']}" for k, v in ORDERS.items()) or "(none)"
@server.prompt()
def refund_email(order_id: str) -> str:
"""Draft a polite refund email for one order."""
return f"Write a short, polite refund confirmation email for order {order_id}."
if __name__ == "__main__":
server.run() # stdio
Calling await ctx.elicit(...) inside the tool body, the older SDK pattern, does not work here. Over a modern stdio connection it fails with MCPError: Cannot send 'elicitation/create': this transport context has no back-channel for server-initiated requests. That error is the spec working as designed: a modern server cannot send requests. Resolve(...) with an Elicit marker is the SDK's way to express the question so it can be carried in a response on modern connections and sent as a normal request on legacy ones.
The wiretap sits between client and server:
# wiretap.py: sits between client and server, copies every JSON line to wire.log
import subprocess, sys, threading
log = open("wire.log", "w")
proc = subprocess.Popen([sys.executable, "server.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def pump(src, dst, tag):
for line in iter(src.readline, b""):
log.write(f"{tag} {line.decode().strip()}\n"); log.flush()
dst.write(line); dst.flush()
threading.Thread(target=pump, args=(proc.stdout, sys.stdout.buffer, "S->C"), daemon=True).start()
pump(sys.stdin.buffer, proc.stdin, "C->S")
And the client:
# client.py: discover, list, call, read, get prompt, and answer an elicitation
import asyncio
import sys
from mcp import Client, StdioServerParameters
from mcp.types import ElicitResult
async def on_elicit(ctx, params):
# A real host shows params.message to a person and waits. This stub always says yes.
print(" [elicitation] server asks:", params.message)
return ElicitResult(action="accept", content={"confirm": True})
async def main() -> None:
params = StdioServerParameters(command=sys.executable, args=["wiretap.py"])
async with Client(params, elicitation_callback=on_elicit) as client:
tools = await client.list_tools()
for t in tools.tools:
print("tool:", t.name, "| required args:", t.input_schema.get("required"))
r = await client.call_tool("order_total", {"order_id": "A-1001"})
print("order_total ->", r.structured_content, "| is_error:", r.is_error)
r = await client.call_tool("order_total", {"order_id": "B-9"})
print("order_total(bad id) -> is_error:", r.is_error, "|", r.content[0].text[:70])
idx = await client.read_resource("orders://index")
print("orders://index ->", idx.contents[0].text)
p = await client.get_prompt("refund_email", {"order_id": "A-1001"})
print("prompt ->", p.messages[0].role, ":", p.messages[0].content.text)
r = await client.call_tool("cancel_order", {"order_id": "A-1001"})
print("cancel_order ->", r.content[0].text)
idx = await client.read_resource("orders://index")
print("orders://index ->", idx.contents[0].text)
asyncio.run(main())
Output of .venv/bin/python client.py 2>/dev/null (stderr hides the server's own log line about the failed call):
tool: order_total | required args: ['order_id']
tool: cancel_order | required args: ['order_id']
order_total -> {'result': 1000.0} | is_error: False
order_total(bad id) -> is_error: True | Error executing tool order_total: unknown order id 'B-9'; known ids: [
orders://index -> A-1001: USB-C cable x4
prompt -> user : Write a short, polite refund confirmation email for order A-1001.
[elicitation] server asks: Cancel A-1001? This cannot be undone.
cancel_order -> cancelled A-1001
orders://index -> (none)
The arithmetic is 250.0 x 4 = 1000.0. The answer parameter does not appear in cancel_order's input schema, so the model never sees it and cannot fill it in.
Multi round-trip requests on the wire#
The interesting traffic is the cancel_order call. It takes two tools/call requests with different ids (MRTR pattern). requestState is shortened here:
C->S {"id":7,"method":"tools/call","params":{"name":"cancel_order","arguments":{"order_id":"A-1001"},"_meta":{...}}}
S->C {"id":7,"result":{"resultType":"input_required",
"inputRequests":{"__main__:ask_confirm":{"method":"elicitation/create","params":{"message":"Cancel A-1001? This cannot be undone.","mode":"form","requestedSchema":{"properties":{"confirm":{"title":"Confirm","type":"boolean"}},"required":["confirm"],"type":"object"}}}},
"requestState":"v1.tZs5C5cU...rXrw8jJnoHZqKlMiV8"}}
C->S {"id":8,"method":"tools/call","params":{"name":"cancel_order","arguments":{"order_id":"A-1001"},
"inputResponses":{"__main__:ask_confirm":{"action":"accept","content":{"confirm":true}}},
"requestState":"v1.tZs5C5cU...rXrw8jJnoHZqKlMiV8","_meta":{...}}}
S->C {"id":8,"result":{"resultType":"complete","content":[{"type":"text","text":"cancelled A-1001"}], ...}}
client server
| tools/call id=7 |
|--------------------------------------->| needs confirmation
| input_required + requestState |
|<---------------------------------------|
| (host asks the user) |
| tools/call id=8 + inputResponses |
| + requestState echoed |
|--------------------------------------->| verifies state, runs body
| complete |
|<---------------------------------------|
The server keeps nothing between the two calls; everything it needs comes back in requestState. The spec says servers must treat that string as attacker-controlled and protect its integrity with an HMAC or AEAD if it affects authorization or business logic. The SDK's request_state.py seals it with AES-GCM, which is why the value is opaque. If you write a server on the low-level API, this is your job.
Transports#
There are two standard bindings (transports):
- stdio: the client launches the server as a subprocess. One JSON-RPC message per line, no embedded newlines. The server may write logs to stderr, and clients should not treat stderr output as an error. Cancellation is a
notifications/cancelledmessage. - Streamable HTTP: every message is a POST to one endpoint. The reply is a JSON object or a request-scoped SSE stream. Cancellation is closing that stream. The old HTTP+SSE transport is deprecated.
On HTTP, the client must mirror some body fields into headers so gateways can route without parsing JSON: MCP-Protocol-Version, Mcp-Method on every request, and Mcp-Name (tool name or resource URI) on tools/call, resources/read and prompts/get. A mismatch between header and body is rejected with 400 and a HeaderMismatch error (-32020). Servers must validate the Origin header. Session ids (Mcp-Session-Id), the GET endpoint and SSE resumability with Last-Event-ID are gone; a broken stream loses the in-flight request and the client re-sends it with a new id.
Running the same server over HTTP is one line, server.run(transport="streamable-http", host="127.0.0.1", port=8765), and Client("http://127.0.0.1:8765/mcp") returned {'result': 1000.0} for the same call. Two raw curl calls show the dual-era behaviour. A plain POST with no MCP headers and no _meta:
HTTP/1.1 400 Bad Request
mcp-session-id: b15dc100bf244b6483e91f23d5756bec
{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Bad Request: Missing session ID"}}
The server treated it as a legacy client and asked for a session. With the three headers and _meta set, the same POST got a complete result with no session at all:
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"1000.0","type":"text"}],"isError":false,"resultType":"complete","structuredContent":{"result":1000.0}, ...}}
If you debug a remote server with curl and see "Missing session ID", you are speaking the legacy dialect by accident.
Change notifications moved to one method, subscriptions/listen, a long-lived POST stream where the client opts into toolsListChanged, resourcesListChanged and similar. resources/subscribe and resources/unsubscribe are removed. Progress notifications still travel on the response stream of the request they belong to.
Authorization#
Authorization is optional in MCP, and for stdio servers the spec says to take credentials from the environment. For HTTP, the authorization spec builds on OAuth 2.1:
- The MCP server is an OAuth 2.1 resource server. It must publish Protected Resource Metadata (RFC 9728) so clients can find its authorization server.
- Clients use PKCE and send the
resourceparameter (RFC 8707), so tokens are bound to one MCP server. - The server must check that each token was issued for it as the audience. Passing a client's token through to an upstream API is the classic mistake here; get a separate token for the upstream call.
- Client registration: Client ID Metadata Documents are preferred. Dynamic Client Registration is deprecated in this revision but kept for authorization servers that lack CIMD support.
- New in 2026-07-28: clients must validate the
issparameter in the authorization response when present (RFC 9207), and must key stored credentials by issuer and re-register if the authorization server changes.
On top of the spec, a production checklist: HTTPS only, least-privilege scopes per tool, no secrets in tool descriptions (the model reads them), argument validation on every tool, and human confirmation (elicitation) for anything destructive. Clients must treat tool annotations such as destructiveHint as untrusted unless the server is trusted.
Long-running work and other extensions#
Tasks moved out of core into an official Tasks extension, io.modelcontextprotocol/tasks. A server can return a task handle; the client polls tasks/get and sends input with tasks/update. Extensions are negotiated through a new extensions map in client and server capabilities. If one side lacks an extension, the other must fall back to core behaviour or reject the request.
Error codes you will see#
| Code | Meaning |
|---|---|
-32602 |
Invalid params. Also "resource not found" since this revision (was -32002) |
-32020 |
HeaderMismatch (HTTP header disagrees with body) |
-32021 |
MissingRequiredClientCapability |
-32022 |
UnsupportedProtocolVersion, with supported and requested in data |
-32000 to -32019 |
Left to implementations |
A tool that fails is not a JSON-RPC error. It is a normal result with isError: true and text the model can read, as the B-9 call showed. Raise ToolError with a message that helps the model retry; the server above lists the valid ids so the next call can succeed.
Testing a server without a model#
Client accepts an MCPServer instance directly and connects in-process, which makes contract tests fast. This one checks the tool list, the happy path, the error path, and that a declined confirmation deletes nothing:
# test_server.py: contract checks, run in-process (no subprocess, no model)
import asyncio
from mcp import Client
from mcp.types import ElicitResult
import server as srv
async def user_declines(ctx, params):
return ElicitResult(action="decline")
async def main() -> None:
srv.ORDERS["A-1001"] = {"item": "USB-C cable", "price": 250.0, "qty": 4}
async with Client(srv.server, elicitation_callback=user_declines) as c:
names = [t.name for t in (await c.list_tools()).tools]
assert names == ["order_total", "cancel_order"], names
r = await c.call_tool("order_total", {"order_id": "A-1001"})
assert r.structured_content == {"result": 1000.0}
r = await c.call_tool("order_total", {"order_id": "nope"})
assert r.is_error and "unknown order id" in r.content[0].text
r = await c.call_tool("cancel_order", {"order_id": "A-1001"})
assert r.content[0].text == "kept A-1001 (user action: decline)", r.content[0].text
assert "A-1001" in srv.ORDERS
print("4 checks passed")
asyncio.run(main())
4 checks passed
The tool-order assertion is deliberate. The spec now says servers should return tools/list in a deterministic order, because a changing order breaks client caches and LLM prompt caching. Run this on every change, then point the MCP Inspector at the server for manual checks. The model-side question, whether the model picks the right tool, needs a separate eval with real prompts.
Failure modes#
- Old client, new server. A client that only knows
initializecannot talk to a modern-only server. Keep servers dual-era until your hosts upgrade. - Server-initiated requests in tool bodies.
ctx.elicit()inside a tool fails on modern transports, as shown above. UseResolve/Elicit. - Trusting
requestState. An unsigned state blob that carries "user approved: true" is a bypass. Seal it, and include expiry and request binding as the MRTR page recommends. - Session-shaped state. With no sessions, state that must survive across calls needs an explicit handle passed as a tool argument and stored somewhere shared, such as a database or Redis, so any replica can serve it.
- Opaque tool errors. An uncaught exception reaches the model as "Error executing tool X" with no detail, and the model guesses. Raise
ToolErrorwith the fix in the message. - Leaning on deprecated features. Sampling and Roots still work, but the twelve-month clock is running.
Sources#
- MCP specification 2026-07-28: key changes
- Versioning and compatibility
- server/discover
- Multi round-trip requests
- Transports overview, stdio, Streamable HTTP
- Authorization
- Tools, Resources, Prompts, Elicitation
- Deprecated features registry and feature lifecycle policy
- Tasks extension
- Previous revision, 2025-11-25
- mcp on PyPI, Python SDK repository, Python SDK docs
- MCP Inspector
- JSON-RPC 2.0, RFC 9728, RFC 8707