Skip to content

Commit e9ab702

Browse files
committed
fix(server): return HTTP 200 for handler-origin INVALID_PARAMS in modern streamable HTTP
1 parent 77001c9 commit e9ab702

3 files changed

Lines changed: 138 additions & 15 deletions

File tree

‎src/mcp/server/_streamable_http_modern.py‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
as a sibling task and defers committing to `text/event-stream` until the
1414
handler emits a notification or `_SSE_PING_INTERVAL` elapses, whichever
1515
comes first: a handler that completes (or raises) within that window without
16-
emitting still gets a JSON response with the table-mapped HTTP status, so
17-
the spec's `404`/`400` MUSTs hold for kernel-dispatch errors; a handler that
16+
emitting still gets a JSON response with the handler error status map (`404`/`400`
17+
only for the spec-assigned codes, `200` for handler `INVALID_PARAMS`); a handler that
1818
runs silent past the window commits SSE so the keepalive ping can keep the
1919
connection open behind a proxy idle-read timeout.
2020
"""
@@ -25,6 +25,7 @@
2525
import logging
2626
from collections.abc import Awaitable, Mapping
2727
from dataclasses import dataclass, field
28+
from types import MappingProxyType
2829
from typing import TYPE_CHECKING, Any, Final, cast
2930

3031
import anyio
@@ -34,8 +35,11 @@
3435
CLIENT_INFO_META_KEY,
3536
HEADER_MISMATCH,
3637
INVALID_REQUEST,
38+
METHOD_NOT_FOUND,
39+
MISSING_REQUIRED_CLIENT_CAPABILITY,
3740
PARSE_ERROR,
3841
PROTOCOL_VERSION_META_KEY,
42+
UNSUPPORTED_PROTOCOL_VERSION,
3943
ErrorData,
4044
JSONRPCError,
4145
JSONRPCNotification,
@@ -171,14 +175,33 @@ async def _write_rejection(
171175
await _write(rej, scope, receive, send)
172176

173177

178+
_HANDLER_ERROR_HTTP_STATUS: Final[Mapping[int, int]] = MappingProxyType(
179+
{
180+
HEADER_MISMATCH: 400,
181+
MISSING_REQUIRED_CLIENT_CAPABILITY: 400,
182+
UNSUPPORTED_PROTOCOL_VERSION: 400,
183+
METHOD_NOT_FOUND: 404,
184+
}
185+
)
186+
"""HTTP statuses assigned to dispatched (post-ladder) JSON-RPC errors.
187+
188+
Streamable HTTP 2026-07-28 (§Sending Messages item 6) assigns non-200 HTTP
189+
statuses only to these four codes once a request clears the inbound validation
190+
ladder. Other dispatched errors — including handler-origin `INVALID_PARAMS`
191+
(-32602, e.g. unknown resources) — travel in-band with HTTP 200.
192+
"""
193+
194+
174195
async def _write(
175196
msg: JSONRPCResponse | JSONRPCError,
176197
scope: Scope,
177198
receive: Receive,
178199
send: Send,
200+
*,
201+
error_statuses: Mapping[int, int] = ERROR_CODE_HTTP_STATUS,
179202
) -> None:
180-
"""Serialise a JSON-RPC reply with the table-mapped HTTP status."""
181-
status = ERROR_CODE_HTTP_STATUS.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200
203+
"""Serialise a JSON-RPC reply with its origin-appropriate HTTP status."""
204+
status = error_statuses.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200
182205
body = msg.model_dump(mode="json", by_alias=True, exclude_none=True)
183206
if isinstance(msg, JSONRPCError) and msg.id is None:
184207
# JSON-RPC requires `id: null` to appear on the wire when the request
@@ -459,7 +482,7 @@ async def handle_modern_request(
459482
msg = await _to_jsonrpc_response(
460483
req.id, serve_one(app, dctx, req.method, req.params, connection=connection, lifespan_state=lifespan_state)
461484
)
462-
await _write(msg, scope, receive, send)
485+
await _write(msg, scope, receive, send, error_statuses=_HANDLER_ERROR_HTTP_STATUS)
463486
return
464487

465488
send_ch, recv_ch = anyio.create_memory_object_stream[bytes](0)
@@ -494,10 +517,9 @@ async def watch_disconnect(cancel_scope: anyio.CancelScope) -> None:
494517

495518
if done:
496519
# Handler completed within the deferral window without emitting:
497-
# `application/json` with the table-mapped status. Kernel-dispatch
498-
# errors (METHOD_NOT_FOUND, missing-capability, INVALID_PARAMS)
499-
# resolve here in practice.
500-
await _write(result[0], scope, receive, send)
520+
# `application/json` with the handler error status map (404/400 for
521+
# spec-assigned codes; 200 in-band for handler INVALID_PARAMS / INTERNAL_ERROR).
522+
await _write(result[0], scope, receive, send, error_statuses=_HANDLER_ERROR_HTTP_STATUS)
501523
else:
502524
# First notification arrived, or the deferral window elapsed: commit
503525
# `text/event-stream` and start pinging so a proxy idle-read timeout

‎src/mcp/shared/inbound.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -316,11 +316,12 @@ def _value_at_path(arguments: Mapping[str, Any], path: tuple[str, ...]) -> Any:
316316
METHOD_NOT_FOUND: 404,
317317
}
318318
)
319-
"""HTTP status to send for a JSON-RPC `error.code`.
319+
"""HTTP status to send for an inbound/boundary JSON-RPC `error.code`.
320320
321-
Consulted for classifier-origin *and* handler-origin errors, so one table
322-
decides the wire status regardless of where the error was produced. Unmapped
323-
codes fall back to the caller's default (typically 200).
321+
Consulted for pre-dispatch ladder rejections and malformed-body/parse errors.
322+
Dispatched handler errors consult only the narrower spec-assigned status map
323+
so handler-origin `INVALID_PARAMS` stays in-band on HTTP 200. Unmapped codes
324+
fall back to the caller's default (typically 200).
324325
"""
325326

326327

‎tests/server/test_streamable_http_modern.py‎

Lines changed: 102 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@
3737
LoggingMessageNotificationParams,
3838
NotificationParams,
3939
PaginatedRequestParams,
40+
ReadResourceRequestParams,
41+
ReadResourceResult,
4042
Tool,
4143
)
4244
from mcp_types.version import LATEST_MODERN_VERSION, MODERN_PROTOCOL_VERSIONS
@@ -1202,13 +1204,13 @@ async def test_modern_post_rejects_a_duplicated_routing_header() -> None:
12021204
async def test_modern_tools_call_mis_shaped_envelope_skips_validation_without_an_error_log(
12031205
caplog: pytest.LogCaptureFixture,
12041206
) -> None:
1205-
"""A mis-shaped envelope value is a debug-logged client fault; the wire reply is dispatch's INVALID_PARAMS."""
1207+
"""A mis-shaped optional envelope value clears the ladder and fails during dispatch: in-band 200 INVALID_PARAMS."""
12061208
body = _tool_call_body({"region": "eu"})
12071209
body["params"]["_meta"][CLIENT_INFO_META_KEY] = "not-an-object"
12081210
with caplog.at_level(logging.DEBUG, logger=_streamable_http_modern.__name__):
12091211
async with _asgi_client(_x_mcp_server()) as http:
12101212
response = await http.post("/mcp", json=body, headers=_TOOL_CALL_HEADERS | {"mcp-param-region": "eu"})
1211-
assert response.status_code == 400
1213+
assert response.status_code == 200
12121214
assert response.json()["error"]["code"] == INVALID_PARAMS
12131215
module_records = [r for r in caplog.records if r.name == _streamable_http_modern.__name__]
12141216
assert all(r.levelno < logging.ERROR for r in module_records)
@@ -1353,3 +1355,101 @@ async def post() -> None:
13531355
"io.modelcontextprotocol/subscriptionId": 9,
13541356
SERVER_INFO_META_KEY: {"name": "test", "version": "1.2.3"},
13551357
}
1358+
1359+
1360+
def _read_resource_body(uri: str = "demo://does-not-exist", *, progress_token: str | None = None) -> dict[str, Any]:
1361+
meta: dict[str, Any] = {
1362+
PROTOCOL_VERSION_META_KEY: LATEST_MODERN_VERSION,
1363+
CLIENT_INFO_META_KEY: {"name": "raw", "version": "0.0.0"},
1364+
CLIENT_CAPABILITIES_META_KEY: {},
1365+
}
1366+
if progress_token is not None:
1367+
meta["progressToken"] = progress_token
1368+
return {
1369+
"jsonrpc": "2.0",
1370+
"id": 7800,
1371+
"method": "resources/read",
1372+
"params": {"uri": uri, "_meta": meta},
1373+
}
1374+
1375+
1376+
def _unknown_resource_mcp_server() -> MCPServer:
1377+
mcp = MCPServer("repro")
1378+
1379+
@mcp.resource("demo://widget")
1380+
def widget() -> str:
1381+
return "<html></html>"
1382+
1383+
return mcp
1384+
1385+
1386+
@pytest.mark.parametrize(
1387+
("json_response", "accept"),
1388+
[
1389+
pytest.param(True, "application/json", id="json-mode"),
1390+
pytest.param(False, "application/json, text/event-stream", id="sse-deferral-fallback"),
1391+
],
1392+
)
1393+
async def test_modern_handler_invalid_params_returns_http_200_in_json_and_sse_deferral(
1394+
json_response: bool, accept: str
1395+
) -> None:
1396+
"""Spec-mandated: a dispatched handler INVALID_PARAMS (-32602, e.g. unknown resource)
1397+
MUST return HTTP 200 with the JSON-RPC error in-band, in both JSON mode and SSE
1398+
deferral fallback when the handler returns without emitting a notification."""
1399+
mcp = _unknown_resource_mcp_server()
1400+
headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"}
1401+
async with _asgi_client(mcp._lowlevel_server, json_response=json_response, accept=accept) as http:
1402+
with anyio.fail_after(5):
1403+
response = await http.post("/mcp", json=_read_resource_body(), headers=headers)
1404+
1405+
assert response.status_code == 200
1406+
assert response.headers["content-type"].split(";", 1)[0] == "application/json"
1407+
payload = response.json()
1408+
assert payload["id"] == 7800
1409+
assert payload["error"]["code"] == INVALID_PARAMS
1410+
1411+
1412+
async def test_modern_handler_invalid_params_after_progress_streams_sse_200() -> None:
1413+
"""Spec-mandated: in SSE mode, emitting a progress notification before raising
1414+
handler INVALID_PARAMS (-32602) returns HTTP 200 text/event-stream with the progress
1415+
event followed by the terminal -32602 error."""
1416+
1417+
async def read_resource(ctx: ServerRequestContext, params: ReadResourceRequestParams) -> ReadResourceResult:
1418+
await ctx.session.report_progress(1.0, total=1.0)
1419+
raise MCPError(
1420+
code=INVALID_PARAMS,
1421+
message=f"Unknown resource: {params.uri}",
1422+
data={"uri": str(params.uri)},
1423+
)
1424+
1425+
server: Server[Any] = Server("test", on_read_resource=read_resource)
1426+
headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"}
1427+
async with _asgi_client(server, json_response=False) as http:
1428+
with anyio.fail_after(5):
1429+
response = await http.post(
1430+
"/mcp", json=_read_resource_body(progress_token="tok-missing"), headers=headers
1431+
)
1432+
1433+
assert response.status_code == 200
1434+
assert response.headers["content-type"].split(";", 1)[0] == "text/event-stream"
1435+
events = _sse_payloads(response.text)
1436+
assert len(events) == 2
1437+
assert events[0]["method"] == "notifications/progress"
1438+
assert events[0]["params"]["progressToken"] == "tok-missing"
1439+
assert events[1]["id"] == 7800
1440+
assert events[1]["error"]["code"] == INVALID_PARAMS
1441+
1442+
1443+
async def test_modern_ladder_invalid_params_rejection_stays_http_400() -> None:
1444+
"""Spec-mandated: a pre-dispatch ladder rejection carrying -32602 (missing required
1445+
`_meta` envelope key) MUST still answer HTTP 400, preserving the origin split."""
1446+
mcp = _unknown_resource_mcp_server()
1447+
body = _read_resource_body()
1448+
del body["params"]["_meta"][CLIENT_CAPABILITIES_META_KEY]
1449+
headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"}
1450+
async with _asgi_client(mcp._lowlevel_server, json_response=True, accept="application/json") as http:
1451+
response = await http.post("/mcp", json=body, headers=headers)
1452+
1453+
assert response.status_code == 400
1454+
assert response.headers["content-type"].split(";", 1)[0] == "application/json"
1455+
assert response.json()["error"]["code"] == INVALID_PARAMS

0 commit comments

Comments
 (0)