Skip to content

Commit f0c1c20

Browse files
andrevegasclaude
andcommitted
Route Streamable HTTP era from the request envelope, not only the header
StreamableHTTPSessionManager chose the protocol era from the MCP-Protocol-Version header alone, so a request carrying the 2026-07-28 `_meta` envelope with a 2025-era or missing header was served by the legacy path: tools/list answered 200 with a 2025-shaped result and modern-only methods such as server/discover answered 200 with -32601. The 2026-07-28 transport requires 400 with HeaderMismatch (-32020) when the header does not match the envelope. Peek at the POST body (already buffered and size-limited by RequestBodyLimitMiddleware) and send requests that carry the envelope to the modern entry, whose classifier already produces HeaderMismatch. The body is replayed untouched. Unparseable bodies, notifications, batches and `initialize` stay on the legacy path, as in the stdio runner. Share the era predicate as mcp.shared.inbound.has_modern_envelope so stdio and HTTP use one definition. Refs #3863 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 77001c9 commit f0c1c20

5 files changed

Lines changed: 243 additions & 35 deletions

File tree

‎src/mcp/server/runner.py‎

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464
from mcp.shared._stream_protocols import ReadStream, WriteStream
6565
from mcp.shared.dispatcher import CallOptions, DispatchContext, Dispatcher, OnNotify, OnRequest
6666
from mcp.shared.exceptions import MCPError, NoBackChannelError
67-
from mcp.shared.inbound import InboundLadderRejection, classify_inbound_request
67+
from mcp.shared.inbound import InboundLadderRejection, classify_inbound_request, has_modern_envelope
6868
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher, handler_exception_to_error_data
6969
from mcp.shared.message import MessageMetadata, ServerMessageMetadata, SessionMessage
7070
from mcp.shared.transport_context import TransportContext
@@ -501,22 +501,6 @@ async def serve_loop(
501501
)
502502

503503

504-
def _has_modern_envelope(params: Mapping[str, Any] | None) -> bool:
505-
"""Whether `params._meta` carries the reserved protocol-version key.
506-
507-
The `io.modelcontextprotocol/protocolVersion` key exists only in
508-
2026-07-28+ envelopes and its prefix is spec-reserved, so legacy traffic
509-
never mints it (a bare `_meta` is not evidence - legacy requests carry
510-
`progressToken` there). The version key alone is the signal, not the full
511-
required pair, so a half-built envelope still routes modern and gets the
512-
classifier's INVALID_PARAMS naming the missing key.
513-
"""
514-
if not params:
515-
return False
516-
meta = params.get("_meta")
517-
return isinstance(meta, Mapping) and PROTOCOL_VERSION_META_KEY in meta
518-
519-
520504
def _initialize_after_modern_data(params: Mapping[str, Any] | None) -> dict[str, Any]:
521505
"""Error data for an `initialize` arriving on a modern-locked connection.
522506
@@ -626,7 +610,7 @@ async def serve_dual_era_loop(
626610
try:
627611
async with _replay_from_opening_request(read_stream) as (opening, replayed):
628612
opens_modern = (
629-
opening is not None and opening.method != "initialize" and _has_modern_envelope(opening.params)
613+
opening is not None and opening.method != "initialize" and has_modern_envelope(opening.params)
630614
)
631615
if opens_modern:
632616
await _serve_modern_stream(
@@ -738,7 +722,7 @@ async def _serve_legacy_stream(
738722
async def on_request(
739723
dctx: DispatchContext[TransportContext], method: str, params: Mapping[str, Any] | None
740724
) -> dict[str, Any]:
741-
if method != "initialize" and _has_modern_envelope(params):
725+
if method != "initialize" and has_modern_envelope(params):
742726
raise MCPError(
743727
code=INVALID_REQUEST,
744728
message="this connection serves the handshake protocol era; "

‎src/mcp/server/streamable_http_manager.py‎

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
from __future__ import annotations
44

55
import contextlib
6+
import json
67
import logging
78
import math
9+
from collections import deque
810
from collections.abc import AsyncIterator
9-
from typing import TYPE_CHECKING, Any, Final
11+
from typing import TYPE_CHECKING, Any, Final, cast
1012
from uuid import uuid4
1113

1214
import anyio
@@ -26,7 +28,7 @@
2628
from mcp.server.transport_security import RequestBodyLimitMiddleware as RequestBodyLimitMiddleware
2729
from mcp.server.transport_security import TransportSecuritySettings
2830
from mcp.shared._compat import resync_tracer
29-
from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER
31+
from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER, has_modern_envelope
3032
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher
3133
from mcp.shared.transport_context import TransportContext
3234

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

4446

47+
async def _peek_modern_envelope(receive: Receive) -> tuple[Receive, bool]:
48+
"""Read the POST body and report whether it is a request carrying the 2026-07-28 envelope.
49+
50+
Returns a `receive` that replays everything read, so the chosen handler sees the body untouched.
51+
The body is already complete and size-limited by `RequestBodyLimitMiddleware`. An unparseable
52+
body, a notification, a batch and `initialize` are not evidence of the modern era and stay on the
53+
legacy path, which owns their errors.
54+
"""
55+
messages: deque[Message] = deque()
56+
body = bytearray()
57+
while True:
58+
message = await receive()
59+
messages.append(message)
60+
if message["type"] != "http.request":
61+
break
62+
body.extend(message.get("body", b""))
63+
if not message.get("more_body", False):
64+
break
65+
66+
async def replay() -> Message:
67+
return messages.popleft() if messages else await receive()
68+
69+
try:
70+
decoded: Any = json.loads(body)
71+
except (ValueError, RecursionError):
72+
return replay, False
73+
if not isinstance(decoded, dict):
74+
return replay, False
75+
request = cast("dict[str, Any]", decoded)
76+
if "id" not in request or request.get("method") == "initialize":
77+
return replay, False
78+
params: Any = request.get("params")
79+
return replay, isinstance(params, dict) and has_modern_envelope(cast("dict[str, Any]", params))
80+
81+
4582
class StreamableHTTPSessionManager:
4683
"""Manages StreamableHTTP sessions with optional resumability via event store.
4784
@@ -184,18 +221,27 @@ async def _handle_request(self, scope: Scope, receive: Receive, send: Send) -> N
184221
if self._task_group is None:
185222
raise RuntimeError("Task group is not initialized. Make sure to use run().")
186223

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

200246
# Dispatch to the appropriate handler
201247
if self.stateless:

‎src/mcp/shared/inbound.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
"encode_header_value",
5252
"find_duplicated_routing_header",
5353
"find_invalid_x_mcp_header",
54+
"has_modern_envelope",
5455
"mcp_param_headers",
5556
"unsupported_protocol_version_rejection",
5657
"validate_mcp_param_headers",
@@ -351,6 +352,22 @@ class InboundLadderRejection:
351352
_ROUTING_HEADER_NAMES: Final = frozenset({MCP_PROTOCOL_VERSION_HEADER, MCP_METHOD_HEADER, MCP_NAME_HEADER})
352353

353354

355+
def has_modern_envelope(params: Mapping[str, Any] | None) -> bool:
356+
"""Whether `params._meta` carries the reserved protocol-version key.
357+
358+
The `io.modelcontextprotocol/protocolVersion` key exists only in
359+
2026-07-28+ envelopes and its prefix is spec-reserved, so legacy traffic
360+
never mints it (a bare `_meta` is not evidence - legacy requests carry
361+
`progressToken` there). The version key alone is the signal, not the full
362+
required pair, so a half-built envelope still routes modern and gets the
363+
classifier's INVALID_PARAMS naming the missing key.
364+
"""
365+
if not params:
366+
return False
367+
meta = params.get("_meta")
368+
return isinstance(meta, Mapping) and PROTOCOL_VERSION_META_KEY in meta
369+
370+
354371
def find_duplicated_routing_header(headers: Iterable[tuple[str, str]]) -> str | None:
355372
"""Name of a routing header supplied more than once in raw header lines, or `None`.
356373

‎tests/server/test_runner.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@
6565
from mcp.server.runner import (
6666
ServerRunner,
6767
_extract_meta,
68-
_has_modern_envelope,
6968
_initialize_after_modern_data,
7069
_NoServerRequestsDispatchContext,
7170
aclose_shielded,
@@ -78,6 +77,7 @@
7877
from mcp.shared._context_streams import create_context_streams
7978
from mcp.shared.dispatcher import CallOptions
8079
from mcp.shared.exceptions import MCPError, NoBackChannelError
80+
from mcp.shared.inbound import has_modern_envelope
8181
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher
8282
from mcp.shared.message import MessageMetadata, SessionMessage
8383
from mcp.shared.peer import dump_params
@@ -1931,15 +1931,15 @@ def test_has_modern_envelope_keys_on_the_protocol_version_key():
19311931
never mints it (bare `_meta` / `progressToken` is not evidence), and a
19321932
half-built envelope still routes modern so the classifier - not the legacy
19331933
path - names its missing required key."""
1934-
assert not _has_modern_envelope(None)
1935-
assert not _has_modern_envelope({})
1936-
assert not _has_modern_envelope({"_meta": None})
1937-
assert not _has_modern_envelope({"_meta": {"progressToken": 1}})
1934+
assert not has_modern_envelope(None)
1935+
assert not has_modern_envelope({})
1936+
assert not has_modern_envelope({"_meta": None})
1937+
assert not has_modern_envelope({"_meta": {"progressToken": 1}})
19381938
version_only = {PROTOCOL_VERSION_META_KEY: LATEST_MODERN_VERSION}
1939-
assert _has_modern_envelope({"_meta": version_only})
1939+
assert has_modern_envelope({"_meta": version_only})
19401940
pair_only = {k: v for k, v in _modern_envelope().items() if k != CLIENT_INFO_META_KEY}
1941-
assert _has_modern_envelope({"_meta": pair_only})
1942-
assert _has_modern_envelope(_modern_params())
1941+
assert has_modern_envelope({"_meta": pair_only})
1942+
assert has_modern_envelope(_modern_params())
19431943

19441944

19451945
def test_initialize_after_modern_data_arms():

0 commit comments

Comments
 (0)