Skip to content

Commit 72bd9f3

Browse files
andrevegasclaude
andcommitted
Judge an enveloped initialize against its header, and update the routing docs
An `initialize` carrying the reserved 2026-07-28 version key with a 2025-era or missing header was still served by the legacy handshake, so the same body got a successful handshake or a modern rejection depending only on the header. A handshake never carries the reserved key, so route it like any other enveloped request and let the modern entry answer HeaderMismatch. Ordinary legacy `initialize` requests are unchanged and covered by tests. Document that routing now also considers the 2026-07-28 envelope. Refs #3863 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent f0c1c20 commit 72bd9f3

4 files changed

Lines changed: 24 additions & 23 deletions

File tree

‎docs/run/deploy.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ Four processes, one socket. And now the question every deployment has to answer:
7070

7171
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.
7272

73-
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.
73+
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.
7474

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

‎docs/run/legacy-clients.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ MCP has two protocol eras: the `initialize`-handshake era, up to spec version `2
44

55
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.**
66

7-
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.
7+
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.
88

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

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

164164
## Recap
165165

166-
* 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.
166+
* 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.
167167
* 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.
168168
* `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.
169169
* A `2026-07-28` connection is sessionless either way. `stateless_http` never touches it.

‎src/mcp/server/streamable_http_manager.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,9 @@ async def _peek_modern_envelope(receive: Receive) -> tuple[Receive, bool]:
4949
5050
Returns a `receive` that replays everything read, so the chosen handler sees the body untouched.
5151
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.
52+
body, a notification and a batch are not routed on the envelope and stay on the legacy path,
53+
which owns their errors. `initialize` is routed like any other request: a handshake never carries
54+
the reserved version key, so an enveloped one is judged against its header by the modern entry.
5455
"""
5556
messages: deque[Message] = deque()
5657
body = bytearray()
@@ -73,7 +74,7 @@ async def replay() -> Message:
7374
if not isinstance(decoded, dict):
7475
return replay, False
7576
request = cast("dict[str, Any]", decoded)
76-
if "id" not in request or request.get("method") == "initialize":
77+
if "id" not in request:
7778
return replay, False
7879
params: Any = request.get("params")
7980
return replay, isinstance(params, dict) and has_modern_envelope(cast("dict[str, Any]", params))

‎tests/server/test_streamable_http_manager.py‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,7 +1101,7 @@ def _rpc_message(response: httpx2.Response) -> dict[str, Any]:
11011101

11021102
@pytest.mark.anyio
11031103
@pytest.mark.parametrize("stateless", [True, False])
1104-
@pytest.mark.parametrize("method", ["tools/list", "server/discover"])
1104+
@pytest.mark.parametrize("method", ["tools/list", "server/discover", "initialize"])
11051105
@pytest.mark.parametrize("header_version", [LATEST_HANDSHAKE_VERSION, None])
11061106
async def test_modern_envelope_with_a_missing_or_2025_version_header_is_a_header_mismatch(
11071107
stateless: bool, method: str, header_version: str | None
@@ -1171,26 +1171,11 @@ async def test_unparseable_2025_body_keeps_its_legacy_parse_error() -> None:
11711171
202,
11721172
id="notification",
11731173
),
1174-
pytest.param(
1175-
{
1176-
"jsonrpc": "2.0",
1177-
"id": 1,
1178-
"method": "initialize",
1179-
"params": {
1180-
"protocolVersion": LATEST_HANDSHAKE_VERSION,
1181-
"capabilities": {},
1182-
"clientInfo": {"name": "client", "version": "1"},
1183-
**_modern_params(),
1184-
},
1185-
},
1186-
200,
1187-
id="initialize",
1188-
),
11891174
pytest.param([_rpc_body("tools/list", _modern_params())], 400, id="batch"),
11901175
],
11911176
)
11921177
async def test_messages_that_are_not_modern_requests_stay_on_the_legacy_path(body: Any, status: int) -> None:
1193-
"""Notifications, `initialize` and batches are not routed on the envelope, even if they carry one."""
1178+
"""Notifications and batches are not routed on the envelope, even if they carry one."""
11941179
headers = base_headers() | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION}
11951180
async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _):
11961181
response = await http.post("/mcp", json=body, headers=headers)
@@ -1226,3 +1211,18 @@ async def receive() -> Message:
12261211

12271212
assert carries_modern_envelope is False
12281213
assert await replay() == {"type": "http.disconnect"}
1214+
1215+
1216+
@pytest.mark.anyio
1217+
async def test_legacy_initialize_without_an_envelope_still_completes_the_handshake() -> None:
1218+
headers = base_headers() | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION}
1219+
params = {
1220+
"protocolVersion": LATEST_HANDSHAKE_VERSION,
1221+
"capabilities": {},
1222+
"clientInfo": {"name": "client", "version": "1"},
1223+
}
1224+
async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _):
1225+
response = await http.post("/mcp", json=_rpc_body("initialize", params), headers=headers)
1226+
1227+
assert response.status_code == 200
1228+
assert _rpc_message(response)["result"]["protocolVersion"] == LATEST_HANDSHAKE_VERSION

0 commit comments

Comments
 (0)