MCP Messages, Transports and Advanced Features

The messages, headers and rules underneath every MCP connection, with real requests you can reproduce.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Since the 2026-07-28 revision, every MCP request stands on its own: it states its protocol version and client capabilities, and any server instance can answer it. When a server needs more from the person, it returns an input required result and the client sends the request again with the answers. Long-running work and other extras are handled by optional extensions.

What you will learn: the anatomy of a request and a result, both transports, required HTTP headers, multi round-trip requests, change subscriptions, caching, the Tasks extension and error handling.
Prerequisites: What Is MCP? Hosts, Clients, Servers and Capabilities and Build an MCP Server and Client.

Versions used

Checked against the 2026-07-28 specification in November 2026. Examples were run in process with the official Python SDK, package mcp 2.3.0.

Beginner Messages and transports

Three kinds of message

MCP uses JSON-RPC 2.0. Everything on the wire is one of three shapes.

KindHasExpects a reply?
Requestid, method, paramsYes, exactly one
ResponseThe same id with result or errorNo
Notificationmethod and optional params, no idNo

Requests flow from client to server. In this revision a server no longer sends its own requests to the client; it asks for what it needs inside a result, as described below.

What every request carries

The earlier connection handshake and protocol-level session are gone. Instead, each request describes itself in a _meta object inside params.

{"jsonrpc": "2.0", "id": 7, "method": "tools/call",
 "params": {
   "name": "list_orders", "arguments": {},
   "_meta": {
     "io.modelcontextprotocol/protocolVersion": "2026-07-28",
     "io.modelcontextprotocol/clientInfo": {"name": "probe", "version": "1.0"},
     "io.modelcontextprotocol/clientCapabilities": {"elicitation": {}}
   }
 }}
Metadata key (prefix io.modelcontextprotocol/)Purpose
protocolVersionWhich revision this request follows
clientCapabilitiesWhat the client can handle, such as elicitation or an extension
clientInfoClient name and version; recommended
logLevelAsks for log notifications for this request only

Results can identify the server in the same way through serverInfo. The specification also describes how to pass OpenTelemetry trace context (traceparent, tracestate, baggage) in _meta, so a single trace can cross client and server.

A server must implement server/discover, which reports supported versions, capabilities and identity. A client may call it first, but is not required to.

The two standard transports

stdioThe client starts the server as a local process and exchanges one JSON message per line on standard input and output
Streamable HTTPThe server is a web service with one endpoint; each message is its own HTTP POST
The messages are the same. Only the way they travel differs.

On stdio, standard output belongs to the protocol. Send logs to standard error. On HTTP, the server answers each request with either a single JSON object or a server-sent event stream that belongs to that request alone, and a client must accept both.

Intermediate The HTTP rules and interactive requests

Headers that mirror the body

Selected body fields are copied into headers so that load balancers, gateways and monitoring tools can act without parsing JSON.

HeaderValueRequired on
MCP-Protocol-VersionMust match the version in _metaEvery POST
Mcp-MethodThe JSON-RPC methodEvery request
Mcp-NameTool or prompt name, or resource URItools/call, resources/read, prompts/get
Mcp-Param-…A tool argument marked with x-mcp-header in its schemaWhen the tool declares it and a value is present
Acceptapplication/json and text/event-streamEvery POST

A server that reads the body must reject a request whose headers disagree with it. This matters for security: a gateway that allows a request because of its header must not be followed by a server that does something else because of the body. Values that are not safe as plain header text are sent in a defined Base64 form, which servers decode before comparing.

Do not put secrets in mirrored parameters

Headers are routinely logged by proxies. Mark only routing values such as a region or tenant identifier, never tokens or personal data.

Multi round-trip requests

Suppose a tool must confirm before canceling an order. The server cannot hold the connection and ask a question. It answers with resultType: "input_required", listing what it needs in inputRequests, often with an opaque requestState. The client collects the answers and sends the original request again with inputResponses and the same state.

Callcancel A-100
Input requiredquestion and state
Person answershost shows the question
Retrysame call, answers, state
Complete
Two ordinary requests replace one long conversation held open on a server.

In the Python SDK a resolver function declares the question, and the tool receives the answer as a parameter.

"""An MCP server whose cancel tool asks the person to confirm."""
from typing import Annotated

from mcp.server import MCPServer
from mcp.server.mcpserver import Elicit, Resolve
from mcp.server.mcpserver.exceptions import ToolError
from pydantic import BaseModel

ORDERS = {"A-100": {"total": 40.0, "status": "open"}}
mcp = MCPServer("orders", log_level="WARNING")


class Confirm(BaseModel):
    confirm: bool


def ask_to_confirm(order_id: str) -> Elicit[Confirm]:
    if order_id not in ORDERS:
        raise ToolError(f"no order {order_id}; call list_orders to see valid ids")
    total = ORDERS[order_id]["total"]
    return Elicit(f"Cancel order {order_id} worth {total:.2f}?", Confirm)


@mcp.tool()
def list_orders() -> dict[str, dict]:
    """List orders with their total and status. Read only."""
    return ORDERS


@mcp.tool()
def cancel_order(order_id: str,
                 answer: Annotated[Confirm, Resolve(ask_to_confirm)]) -> str:
    """Cancel one open order after the person confirms. Changes records."""
    if not answer.confirm:
        return f"Kept {order_id}"
    ORDERS[order_id]["status"] = "canceled"
    return f"Canceled {order_id}"

A client supplies a callback that shows the question to the person. This script tries all three outcomes.

"""Watch one tool call pause for input and then finish."""
import asyncio

from mcp import Client
from mcp_types import ElicitResult

from orders import mcp


async def run(label, action, content=None):
    async def answer(context, params):
        print(f"  host shows: {params.message}")
        return ElicitResult(action=action, content=content)

    async with Client(mcp, elicitation_callback=answer) as client:
        print(label)
        result = await client.call_tool("cancel_order", {"order_id": "A-100"})
        text = result.content[0].text.split("\n")[0]
        print(f"  error={result.is_error}: {text}")


async def main():
    await run("person declines", "decline")
    await run("person says no", "accept", {"confirm": False})
    await run("person says yes", "accept", {"confirm": True})


asyncio.run(main())

Output:

person declines
  host shows: Cancel order A-100 worth 40.00?
  error=True: Error executing tool cancel_order: Resolver for parameter 'answer' could not resolve: elicitation was decline
person says no
  host shows: Cancel order A-100 worth 40.00?
  error=False: Kept A-100
person says yes
  host shows: Cancel order A-100 worth 40.00?
  error=False: Canceled A-100

Notice the difference between the first two cases. Declining the question stops the tool, which here surfaces as a tool error. Answering no is a normal answer that the tool handles. Design both.

The same exchange as raw HTTP

The next script uses no MCP client. It posts JSON to the server and then probes what happens when rules are broken.

"""Send raw Streamable HTTP requests to the server, in process."""
import json

from starlette.testclient import TestClient

from orders import mcp

VERSION = "2026-07-28"
META = {"io.modelcontextprotocol/protocolVersion": VERSION,
        "io.modelcontextprotocol/clientInfo": {"name": "probe", "version": "1.0"},
        "io.modelcontextprotocol/clientCapabilities": {"elicitation": {}}}


def post(http, method, params=None, **override):
    params = dict(params or {}, _meta=override.pop("meta", META))
    headers = {"Accept": "application/json, text/event-stream",
               "MCP-Protocol-Version": VERSION, "Mcp-Method": method}
    if "name" in params:
        headers["Mcp-Name"] = params["name"]
    headers.update(override)
    body = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
    return http.post("/mcp", json=body,
                     headers={k: v for k, v in headers.items() if v})


def show(label, reply):
    is_json = "json" in reply.headers.get("content-type", "")
    data = reply.json() if is_json else {}
    note = data.get("error", {}).get("code", "")
    if data.get("result", {}).get("isError"):
        note = "result with isError: true"
    print(f"{label:25} HTTP {reply.status_code}  {note}".rstrip())


def demo():
    app = mcp.streamable_http_app(json_response=True)
    with TestClient(app, base_url="http://127.0.0.1:8000") as http:
        call = {"name": "cancel_order", "arguments": {"order_id": "A-100"}}
        first = post(http, "tools/call", call).json()["result"]
        key = next(iter(first["inputRequests"]))
        print("resultType:", first["resultType"])
        print("asks for:  ", first["inputRequests"][key]["method"])
        print("has state: ", "requestState" in first)

        reply = {"action": "accept", "content": {"confirm": True}}
        retry = dict(call, inputResponses={key: reply},
                     requestState=first.get("requestState"))
        second = post(http, "tools/call", retry).json()["result"]
        print("resultType:", second["resultType"])
        print("text:      ", second["content"][0]["text"])
        print()

        listing = {"name": "list_orders", "arguments": {}}
        show("valid call", post(http, "tools/call", listing))
        show("wrong Mcp-Name",
             post(http, "tools/call", listing, **{"Mcp-Name": "other"}))
        show("missing Mcp-Method",
             post(http, "tools/list", **{"Mcp-Method": ""}))
        old = dict(META, **{"io.modelcontextprotocol/protocolVersion": "2099-01-01"})
        show("unknown protocol version",
             post(http, "tools/list", meta=old,
                  **{"MCP-Protocol-Version": "2099-01-01"}))
        show("unknown method", post(http, "orders/explode"))
        show("unknown tool", post(http, "tools/call", {"name": "nope"}))
        show("foreign Origin",
             post(http, "tools/list", Origin="https://evil.example"))
        show("GET on the endpoint", http.get("/mcp"))


if __name__ == "__main__":
    demo()

Output:

resultType: input_required
asks for:   elicitation/create
has state:  True
resultType: complete
text:       Canceled A-100

valid call                HTTP 200
wrong Mcp-Name            HTTP 400  -32020
missing Mcp-Method        HTTP 400  -32020
unknown protocol version  HTTP 400  -32022
unknown method            HTTP 404  -32601
unknown tool              HTTP 200  result with isError: true
foreign Origin            HTTP 403
GET on the endpoint       HTTP 400  -32600

Two results depend on the library rather than only the protocol. This SDK release reports an unknown tool as a tool result with isError, and it answered the GET with status 400 because it also serves older clients. The specification asks a server that supports only the new revision to answer GET with 405.

The request state comes back from the client

Treat requestState as untrusted input. This SDK encrypts and checks it for you. If you write your own server layer, protect its integrity, give it an expiry, and bind it to the request and the user. See MCP Deployment and Production Readiness for the multi-server consequences.

Reading results correctly

resultTypeMeaningClient action
completeThe final answerUse it; check isError for tools
input_requiredMore information neededGather it and retry, with a limit on rounds
taskTasks extension: work continues in the backgroundPoll the task
Field missingAn older serverTreat as complete

A tool that fails for an expected reason returns isError: true with text the model can act on. A protocol problem returns a JSON-RPC error. The output schema and structuredContent may now use any JSON Schema 2020-12 keywords and any JSON value, so validate what you receive rather than assuming an object.

Expert Notifications, caching, tasks and compatibility

Notifications, cancellation and subscriptions

NeedHow it works now
Progress for one requestnotifications/progress on that request's response stream
Cancel over HTTPClose the response stream
Cancel over stdioSend notifications/cancelled
Hear about list or resource changesOpen subscriptions/listen and name the kinds you want
Lost connection mid-responseThe request is lost; send a new one with a new id

subscriptions/listen replaces the old standalone GET stream and per-resource subscribe calls. Its filter can request tool, prompt and resource list changes and updates to chosen resources. The server first acknowledges, then tags each notification with a subscription id. Event replay through Last-Event-ID was removed, so a client that reconnects should list or read again.

Retries can repeat actions

If the stream breaks after a server has charged a card, the client's repeat request arrives as new work. Give every tool that changes something an operation key, and make the server refuse to apply the same key twice. See Reliable Tool Execution and Error Recovery.

Caching hints

Results from discovery, the list methods and resource reads carry ttlMs, how long they may be treated as fresh, and cacheScope. A private result may be reused only in the authorization context that produced it; a public one may be cached by shared intermediaries. Mark anything that depends on who is asking as private. Servers should also return tools in a stable order, which helps both caching and model prompt caches.

Extensions and long-running work

Extensions are named additions that both sides declare in an extensions field of their capabilities. Examples include interactive MCP Apps, additional authorization methods and Tasks (io.modelcontextprotocol/tasks).

With Tasks, a server may answer a tools/call with a task handle instead of a result, provided the client declared the extension.

ElementRule
Statusesworking, input_required, completed, failed, cancelled
tasks/getPoll; a completed task includes its result
tasks/updateSend answers to outstanding input requests
tasks/cancelCooperative; the work may still finish
pollIntervalMs, ttlMsHow often to poll and how long the task is kept
Tool errorA result with isError counts as completed, not failed

This design differs from the experimental tasks of the 2025-11-25 revision: the blocking result call and the task list were removed. Task identifiers need enough randomness that nobody can guess them, and every task request still requires authorization. The listings here do not run the extension.

Error codes worth knowing

CodeName or meaning
-32601Method not found; HTTP 404 on the HTTP transport
-32602Invalid parameters, now also used for a missing resource
-32020Header mismatch
-32021A required client capability is missing
-32022Unsupported protocol version; the error lists supported ones

The specification reserves -32020 to -32099 for itself and leaves -32000 to -32019 to implementations. A fuller table is in MCP Troubleshooting, Versions and Message Reference.

Deprecated and removed features

FeatureStatusReplacement
Initialize handshake, session id, pingRemovedPer-request metadata
RootsDeprecatedTool parameters, resource URIs or configuration
SamplingDeprecatedCall a model provider directly
Logging featureDeprecatedStandard error or OpenTelemetry
HTTP with SSE transportDeprecatedStreamable HTTP
Dynamic client registrationDeprecatedClient ID Metadata Documents

The project's lifecycle policy gives deprecated features a window of at least twelve months before removal.

Common mistakes

MistakeBetter practice
Following a pre-2026 tutorial's handshakeCheck which revision your library speaks
Keeping user state in the connectionReturn an explicit handle and accept it as an argument
Routing on headers that are never validatedReject mismatches at the server
Looping forever on input requiredCap rounds and tell the person why it stopped
Printing to standard output in a stdio serverLog to standard error
Caching per-user results as publicUse private scope

Checklist

  • Every request carries version and capabilities
  • HTTP clients send the required headers and accept both content types
  • Decline, cancel and a negative answer are all handled
  • Operations that change data are safe to receive twice
  • Cache scope matches who may see the result
  • No new code depends on a deprecated feature

Frequently asked questions

Can a server still keep state between calls?

Yes, in your own storage. The server issues a handle, such as a basket id, and later calls pass it back as a normal argument. Check on each call that this user may use that handle.

Do old clients still work?

Only if the server also implements their revision. Many SDKs negotiate and fall back, so test the exact client and server versions you plan to support.

Is a server-sent event stream required?

No. A server may answer with plain JSON when it has nothing to send before the result. Clients must support both.

Where is the authoritative definition?

In the specification and its schema. SDK behavior can differ in details, as the probe above shows.

References and further reading

Next steps