Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/run/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ Four processes, one socket. And now the question every deployment has to answer:

For a client speaking the **2026-07-28** protocol, no. A modern request is one self-contained POST: no `initialize` handshake before it, no `Mcp-Session-Id` on the response, nothing for a second request to come back *to*. Route it to any worker.

That is not a mode you switch on. `stateless_http=True` looks like it should be, but the transport routes on the `MCP-Protocol-Version` request header, hands a modern request to the modern handler, and **returns**. The line that reads `stateless_http` comes *after* that return. It isn't that the flag is ignored on the 2026-07-28 path; it is never reached. `stateless_http` is a knob for the **legacy** leg only, and the modern path is sessionless by construction.
That is not a mode you switch on. `stateless_http=True` looks like it should be, but the transport routes on the `MCP-Protocol-Version` request header (and the request's `_meta` envelope), hands a modern request to the modern handler, and **returns**. The line that reads `stateless_http` comes *after* that return. It isn't that the flag is ignored on the 2026-07-28 path; it is never reached. `stateless_http` is a knob for the **legacy** leg only, and the modern path is sessionless by construction.

For a legacy client on spec version 2025-11-25 or earlier, the answer depends on that flag:

Expand Down
4 changes: 2 additions & 2 deletions docs/run/legacy-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ MCP has two protocol eras: the `initialize`-handshake era, up to spec version `2

This page is about the server side of that split, and the answer fits in one sentence: **the `streamable_http_app()` you already deploy serves both.**

The SDK routes every request by its `MCP-Protocol-Version` header. A request naming `2026-07-28` goes to the modern handler. A request naming a handshake-era version, or carrying no header at all (which is how a pre-2026 client's `initialize` arrives), goes to the transport those clients expect: `initialize` handshake, sessions and all. It happens per request, before your code, on the one app.
The SDK routes every request by its `MCP-Protocol-Version` header and its body. A request naming `2026-07-28`, or carrying the 2026-07-28 `_meta` envelope, goes to the modern handler; if such a request's header is missing or names another version, it is rejected with `400` and `HeaderMismatch` (`-32020`). Any other request naming a handshake-era version, or carrying no header at all (which is how a pre-2026 client's `initialize` arrives), goes to the transport those clients expect: `initialize` handshake, sessions and all. It happens per request, before your code, on the one app.

So a legacy client is not something you build *for*. It is something that connects *to* the server you already wrote. You configure nothing.

Expand Down Expand Up @@ -163,7 +163,7 @@ Two lines, no `if`, no version check, and you are done. That is the entire list

## Recap

* One `streamable_http_app()` serves both protocol eras. The SDK routes each request by its `MCP-Protocol-Version` header; there is nothing to configure and no era knob to look for.
* One `streamable_http_app()` serves both protocol eras. The SDK routes each request by its `MCP-Protocol-Version` header and, for requests carrying the 2026-07-28 envelope, its body; there is nothing to configure and no era knob to look for.
* A legacy client costs you a session: an in-process `Mcp-Session-Id` record with no distributed store behind it. More than one worker means **sticky routing**, or the wrong worker answers `404 Session not found`. **[Deploy & scale](deploy.md)** has the multi-worker story.
* `stateless_http=True` is the one knob, and it is **legacy-leg-only**. It buys free load balancing for legacy clients at the price of both server-to-client channels on that leg: server-initiated requests raise `NoBackChannelError` (a top-level error at the client, not an `is_error` result), and notifications are dropped.
* A `2026-07-28` connection is sessionless either way. `stateless_http` never touches it.
Expand Down
22 changes: 3 additions & 19 deletions src/mcp/server/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
from mcp.shared._stream_protocols import ReadStream, WriteStream
from mcp.shared.dispatcher import CallOptions, DispatchContext, Dispatcher, OnNotify, OnRequest
from mcp.shared.exceptions import MCPError, NoBackChannelError
from mcp.shared.inbound import InboundLadderRejection, classify_inbound_request
from mcp.shared.inbound import InboundLadderRejection, classify_inbound_request, has_modern_envelope
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher, handler_exception_to_error_data
from mcp.shared.message import MessageMetadata, ServerMessageMetadata, SessionMessage
from mcp.shared.transport_context import TransportContext
Expand Down Expand Up @@ -501,22 +501,6 @@ async def serve_loop(
)


def _has_modern_envelope(params: Mapping[str, Any] | None) -> bool:
"""Whether `params._meta` carries the reserved protocol-version key.

The `io.modelcontextprotocol/protocolVersion` key exists only in
2026-07-28+ envelopes and its prefix is spec-reserved, so legacy traffic
never mints it (a bare `_meta` is not evidence - legacy requests carry
`progressToken` there). The version key alone is the signal, not the full
required pair, so a half-built envelope still routes modern and gets the
classifier's INVALID_PARAMS naming the missing key.
"""
if not params:
return False
meta = params.get("_meta")
return isinstance(meta, Mapping) and PROTOCOL_VERSION_META_KEY in meta


def _initialize_after_modern_data(params: Mapping[str, Any] | None) -> dict[str, Any]:
"""Error data for an `initialize` arriving on a modern-locked connection.

Expand Down Expand Up @@ -626,7 +610,7 @@ async def serve_dual_era_loop(
try:
async with _replay_from_opening_request(read_stream) as (opening, replayed):
opens_modern = (
opening is not None and opening.method != "initialize" and _has_modern_envelope(opening.params)
opening is not None and opening.method != "initialize" and has_modern_envelope(opening.params)
)
if opens_modern:
await _serve_modern_stream(
Expand Down Expand Up @@ -738,7 +722,7 @@ async def _serve_legacy_stream(
async def on_request(
dctx: DispatchContext[TransportContext], method: str, params: Mapping[str, Any] | None
) -> dict[str, Any]:
if method != "initialize" and _has_modern_envelope(params):
if method != "initialize" and has_modern_envelope(params):
raise MCPError(
code=INVALID_REQUEST,
message="this connection serves the handshake protocol era; "
Expand Down
61 changes: 54 additions & 7 deletions src/mcp/server/streamable_http_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
from __future__ import annotations

import contextlib
import json
import logging
import math
from collections import deque
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING, Any, Final
from typing import TYPE_CHECKING, Any, Final, cast
from uuid import uuid4

import anyio
Expand All @@ -26,7 +28,7 @@
from mcp.server.transport_security import RequestBodyLimitMiddleware as RequestBodyLimitMiddleware
from mcp.server.transport_security import TransportSecuritySettings
from mcp.shared._compat import resync_tracer
from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER
from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER, has_modern_envelope
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher
from mcp.shared.transport_context import TransportContext

Expand All @@ -42,6 +44,42 @@
"""Default maximum number of concurrent stateful Streamable HTTP sessions per session manager."""


async def _peek_modern_envelope(receive: Receive) -> tuple[Receive, bool]:
"""Read the POST body and report whether it is a request carrying the 2026-07-28 envelope.

Returns a `receive` that replays everything read, so the chosen handler sees the body untouched.
The body is already complete and size-limited by `RequestBodyLimitMiddleware`. An unparseable
body, a notification and a batch are not routed on the envelope and stay on the legacy path,
which owns their errors. `initialize` is routed like any other request: a handshake never carries
the reserved version key, so an enveloped one is judged against its header by the modern entry.
"""
messages: deque[Message] = deque()
body = bytearray()
while True:
message = await receive()
messages.append(message)
if message["type"] != "http.request":
break
body.extend(message.get("body", b""))
if not message.get("more_body", False):
break

async def replay() -> Message:
return messages.popleft() if messages else await receive()

try:
decoded: Any = json.loads(body)
except (ValueError, RecursionError):
return replay, False
if not isinstance(decoded, dict):
return replay, False
request = cast("dict[str, Any]", decoded)
if "id" not in request:
return replay, False
params: Any = request.get("params")
return replay, isinstance(params, dict) and has_modern_envelope(cast("dict[str, Any]", params))


class StreamableHTTPSessionManager:
"""Manages StreamableHTTP sessions with optional resumability via event store.

Expand Down Expand Up @@ -184,18 +222,27 @@ async def _handle_request(self, scope: Scope, receive: Receive, send: Send) -> N
if self._task_group is None:
raise RuntimeError("Task group is not initialized. Make sure to use run().")

# TODO(L49): header-only era-routing for now; body-primary classification
# is a follow-up. The legacy paths below own only the known
# initialize-handshake versions; anything else (including unknown
# values) goes to the modern entry so the classifier can validate it
# and return a structured rejection. 2025 paths below remain unchanged.
# The legacy paths below own only the known initialize-handshake versions;
# anything else (including unknown values) goes to the modern entry so
# the classifier can validate it and return a structured rejection. A
# request that carries the 2026-07-28 `_meta` envelope goes there too,
# whatever its header says, so the classifier answers a header that
# disagrees with the envelope (or is absent) with HeaderMismatch rather
# than the legacy path serving it as a 2025 request.
header = MCP_PROTOCOL_VERSION_HEADER.encode("ascii")
pv = next((v.decode("latin-1") for k, v in scope["headers"] if k == header), None)
if pv is not None and pv not in HANDSHAKE_PROTOCOL_VERSIONS:
await handle_modern_request(
self.app, self.security_settings, self.json_response, self._lifespan_state, scope, receive, send
)
return
if scope["method"] == "POST":
receive, carries_modern_envelope = await _peek_modern_envelope(receive)
if carries_modern_envelope:
await handle_modern_request(
self.app, self.security_settings, self.json_response, self._lifespan_state, scope, receive, send
)
return

# Dispatch to the appropriate handler
if self.stateless:
Expand Down
17 changes: 17 additions & 0 deletions src/mcp/shared/inbound.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"encode_header_value",
"find_duplicated_routing_header",
"find_invalid_x_mcp_header",
"has_modern_envelope",
"mcp_param_headers",
"unsupported_protocol_version_rejection",
"validate_mcp_param_headers",
Expand Down Expand Up @@ -351,6 +352,22 @@ class InboundLadderRejection:
_ROUTING_HEADER_NAMES: Final = frozenset({MCP_PROTOCOL_VERSION_HEADER, MCP_METHOD_HEADER, MCP_NAME_HEADER})


def has_modern_envelope(params: Mapping[str, Any] | None) -> bool:
"""Whether `params._meta` carries the reserved protocol-version key.

The `io.modelcontextprotocol/protocolVersion` key exists only in
2026-07-28+ envelopes and its prefix is spec-reserved, so legacy traffic
never mints it (a bare `_meta` is not evidence - legacy requests carry
`progressToken` there). The version key alone is the signal, not the full
required pair, so a half-built envelope still routes modern and gets the
classifier's INVALID_PARAMS naming the missing key.
"""
if not params:
return False
meta = params.get("_meta")
return isinstance(meta, Mapping) and PROTOCOL_VERSION_META_KEY in meta


def find_duplicated_routing_header(headers: Iterable[tuple[str, str]]) -> str | None:
"""Name of a routing header supplied more than once in raw header lines, or `None`.

Expand Down
16 changes: 8 additions & 8 deletions tests/server/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@
from mcp.server.runner import (
ServerRunner,
_extract_meta,
_has_modern_envelope,
_initialize_after_modern_data,
_NoServerRequestsDispatchContext,
aclose_shielded,
Expand All @@ -78,6 +77,7 @@
from mcp.shared._context_streams import create_context_streams
from mcp.shared.dispatcher import CallOptions
from mcp.shared.exceptions import MCPError, NoBackChannelError
from mcp.shared.inbound import has_modern_envelope
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher
from mcp.shared.message import MessageMetadata, SessionMessage
from mcp.shared.peer import dump_params
Expand Down Expand Up @@ -1931,15 +1931,15 @@ def test_has_modern_envelope_keys_on_the_protocol_version_key():
never mints it (bare `_meta` / `progressToken` is not evidence), and a
half-built envelope still routes modern so the classifier - not the legacy
path - names its missing required key."""
assert not _has_modern_envelope(None)
assert not _has_modern_envelope({})
assert not _has_modern_envelope({"_meta": None})
assert not _has_modern_envelope({"_meta": {"progressToken": 1}})
assert not has_modern_envelope(None)
assert not has_modern_envelope({})
assert not has_modern_envelope({"_meta": None})
assert not has_modern_envelope({"_meta": {"progressToken": 1}})
version_only = {PROTOCOL_VERSION_META_KEY: LATEST_MODERN_VERSION}
assert _has_modern_envelope({"_meta": version_only})
assert has_modern_envelope({"_meta": version_only})
pair_only = {k: v for k, v in _modern_envelope().items() if k != CLIENT_INFO_META_KEY}
assert _has_modern_envelope({"_meta": pair_only})
assert _has_modern_envelope(_modern_params())
assert has_modern_envelope({"_meta": pair_only})
assert has_modern_envelope(_modern_params())


def test_initialize_after_modern_data_arms():
Expand Down
Loading
Loading