diff --git a/src/mcp/server/_streamable_http_modern.py b/src/mcp/server/_streamable_http_modern.py index ad4257319d..33651c4720 100644 --- a/src/mcp/server/_streamable_http_modern.py +++ b/src/mcp/server/_streamable_http_modern.py @@ -13,8 +13,8 @@ as a sibling task and defers committing to `text/event-stream` until the handler emits a notification or `_SSE_PING_INTERVAL` elapses, whichever comes first: a handler that completes (or raises) within that window without -emitting still gets a JSON response with the table-mapped HTTP status, so -the spec's `404`/`400` MUSTs hold for kernel-dispatch errors; a handler that +emitting still gets a JSON response with the handler error status map (`404`/`400` +only for the spec-assigned codes, `200` for handler `INVALID_PARAMS`); a handler that runs silent past the window commits SSE so the keepalive ping can keep the connection open behind a proxy idle-read timeout. """ @@ -25,6 +25,7 @@ import logging from collections.abc import Awaitable, Mapping from dataclasses import dataclass, field +from types import MappingProxyType from typing import TYPE_CHECKING, Any, Final, cast import anyio @@ -34,8 +35,11 @@ CLIENT_INFO_META_KEY, HEADER_MISMATCH, INVALID_REQUEST, + METHOD_NOT_FOUND, + MISSING_REQUIRED_CLIENT_CAPABILITY, PARSE_ERROR, PROTOCOL_VERSION_META_KEY, + UNSUPPORTED_PROTOCOL_VERSION, ErrorData, JSONRPCError, JSONRPCNotification, @@ -171,14 +175,33 @@ async def _write_rejection( await _write(rej, scope, receive, send) +_HANDLER_ERROR_HTTP_STATUS: Final[Mapping[int, int]] = MappingProxyType( + { + HEADER_MISMATCH: 400, + MISSING_REQUIRED_CLIENT_CAPABILITY: 400, + UNSUPPORTED_PROTOCOL_VERSION: 400, + METHOD_NOT_FOUND: 404, + } +) +"""HTTP statuses assigned to dispatched (post-ladder) JSON-RPC errors. + +Streamable HTTP 2026-07-28 (§Sending Messages item 6) assigns non-200 HTTP +statuses only to these four codes once a request clears the inbound validation +ladder. Other dispatched errors — including handler-origin `INVALID_PARAMS` +(-32602, e.g. unknown resources) — travel in-band with HTTP 200. +""" + + async def _write( msg: JSONRPCResponse | JSONRPCError, scope: Scope, receive: Receive, send: Send, + *, + error_statuses: Mapping[int, int] = ERROR_CODE_HTTP_STATUS, ) -> None: - """Serialise a JSON-RPC reply with the table-mapped HTTP status.""" - status = ERROR_CODE_HTTP_STATUS.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200 + """Serialise a JSON-RPC reply with its origin-appropriate HTTP status.""" + status = error_statuses.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200 body = msg.model_dump(mode="json", by_alias=True, exclude_none=True) if isinstance(msg, JSONRPCError) and msg.id is None: # JSON-RPC requires `id: null` to appear on the wire when the request @@ -459,7 +482,7 @@ async def handle_modern_request( msg = await _to_jsonrpc_response( req.id, serve_one(app, dctx, req.method, req.params, connection=connection, lifespan_state=lifespan_state) ) - await _write(msg, scope, receive, send) + await _write(msg, scope, receive, send, error_statuses=_HANDLER_ERROR_HTTP_STATUS) return send_ch, recv_ch = anyio.create_memory_object_stream[bytes](0) @@ -494,10 +517,9 @@ async def watch_disconnect(cancel_scope: anyio.CancelScope) -> None: if done: # Handler completed within the deferral window without emitting: - # `application/json` with the table-mapped status. Kernel-dispatch - # errors (METHOD_NOT_FOUND, missing-capability, INVALID_PARAMS) - # resolve here in practice. - await _write(result[0], scope, receive, send) + # `application/json` with the handler error status map (404/400 for + # spec-assigned codes; 200 in-band for handler INVALID_PARAMS / INTERNAL_ERROR). + await _write(result[0], scope, receive, send, error_statuses=_HANDLER_ERROR_HTTP_STATUS) else: # First notification arrived, or the deferral window elapsed: commit # `text/event-stream` and start pinging so a proxy idle-read timeout diff --git a/src/mcp/shared/inbound.py b/src/mcp/shared/inbound.py index e33d6f502f..62a86d25db 100644 --- a/src/mcp/shared/inbound.py +++ b/src/mcp/shared/inbound.py @@ -316,11 +316,12 @@ def _value_at_path(arguments: Mapping[str, Any], path: tuple[str, ...]) -> Any: METHOD_NOT_FOUND: 404, } ) -"""HTTP status to send for a JSON-RPC `error.code`. +"""HTTP status to send for an inbound/boundary JSON-RPC `error.code`. -Consulted for classifier-origin *and* handler-origin errors, so one table -decides the wire status regardless of where the error was produced. Unmapped -codes fall back to the caller's default (typically 200). +Consulted for pre-dispatch ladder rejections and malformed-body/parse errors. +Dispatched handler errors consult only the narrower spec-assigned status map +so handler-origin `INVALID_PARAMS` stays in-band on HTTP 200. Unmapped codes +fall back to the caller's default (typically 200). """ diff --git a/tests/server/test_streamable_http_modern.py b/tests/server/test_streamable_http_modern.py index a539720d58..fdd0338828 100644 --- a/tests/server/test_streamable_http_modern.py +++ b/tests/server/test_streamable_http_modern.py @@ -37,6 +37,8 @@ LoggingMessageNotificationParams, NotificationParams, PaginatedRequestParams, + ReadResourceRequestParams, + ReadResourceResult, Tool, ) 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: async def test_modern_tools_call_mis_shaped_envelope_skips_validation_without_an_error_log( caplog: pytest.LogCaptureFixture, ) -> None: - """A mis-shaped envelope value is a debug-logged client fault; the wire reply is dispatch's INVALID_PARAMS.""" + """A mis-shaped optional envelope value clears the ladder and fails during dispatch: in-band 200 INVALID_PARAMS.""" body = _tool_call_body({"region": "eu"}) body["params"]["_meta"][CLIENT_INFO_META_KEY] = "not-an-object" with caplog.at_level(logging.DEBUG, logger=_streamable_http_modern.__name__): async with _asgi_client(_x_mcp_server()) as http: response = await http.post("/mcp", json=body, headers=_TOOL_CALL_HEADERS | {"mcp-param-region": "eu"}) - assert response.status_code == 400 + assert response.status_code == 200 assert response.json()["error"]["code"] == INVALID_PARAMS module_records = [r for r in caplog.records if r.name == _streamable_http_modern.__name__] assert all(r.levelno < logging.ERROR for r in module_records) @@ -1353,3 +1355,101 @@ async def post() -> None: "io.modelcontextprotocol/subscriptionId": 9, SERVER_INFO_META_KEY: {"name": "test", "version": "1.2.3"}, } + + +def _read_resource_body(uri: str = "demo://does-not-exist", *, progress_token: str | None = None) -> dict[str, Any]: + meta: dict[str, Any] = { + PROTOCOL_VERSION_META_KEY: LATEST_MODERN_VERSION, + CLIENT_INFO_META_KEY: {"name": "raw", "version": "0.0.0"}, + CLIENT_CAPABILITIES_META_KEY: {}, + } + if progress_token is not None: + meta["progressToken"] = progress_token + return { + "jsonrpc": "2.0", + "id": 7800, + "method": "resources/read", + "params": {"uri": uri, "_meta": meta}, + } + + +def _unknown_resource_mcp_server() -> MCPServer: + mcp = MCPServer("repro") + + @mcp.resource("demo://widget") + def widget() -> str: + return "" + + return mcp + + +@pytest.mark.parametrize( + ("json_response", "accept"), + [ + pytest.param(True, "application/json", id="json-mode"), + pytest.param(False, "application/json, text/event-stream", id="sse-deferral-fallback"), + ], +) +async def test_modern_handler_invalid_params_returns_http_200_in_json_and_sse_deferral( + json_response: bool, accept: str +) -> None: + """Spec-mandated: a dispatched handler INVALID_PARAMS (-32602, e.g. unknown resource) + MUST return HTTP 200 with the JSON-RPC error in-band, in both JSON mode and SSE + deferral fallback when the handler returns without emitting a notification.""" + mcp = _unknown_resource_mcp_server() + headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"} + async with _asgi_client(mcp._lowlevel_server, json_response=json_response, accept=accept) as http: + with anyio.fail_after(5): + response = await http.post("/mcp", json=_read_resource_body(), headers=headers) + + assert response.status_code == 200 + assert response.headers["content-type"].split(";", 1)[0] == "application/json" + payload = response.json() + assert payload["id"] == 7800 + assert payload["error"]["code"] == INVALID_PARAMS + + +async def test_modern_handler_invalid_params_after_progress_streams_sse_200() -> None: + """Spec-mandated: in SSE mode, emitting a progress notification before raising + handler INVALID_PARAMS (-32602) returns HTTP 200 text/event-stream with the progress + event followed by the terminal -32602 error.""" + + async def read_resource(ctx: ServerRequestContext, params: ReadResourceRequestParams) -> ReadResourceResult: + await ctx.session.report_progress(1.0, total=1.0) + raise MCPError( + code=INVALID_PARAMS, + message=f"Unknown resource: {params.uri}", + data={"uri": str(params.uri)}, + ) + + server: Server[Any] = Server("test", on_read_resource=read_resource) + headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"} + async with _asgi_client(server, json_response=False) as http: + with anyio.fail_after(5): + response = await http.post( + "/mcp", json=_read_resource_body(progress_token="tok-missing"), headers=headers + ) + + assert response.status_code == 200 + assert response.headers["content-type"].split(";", 1)[0] == "text/event-stream" + events = _sse_payloads(response.text) + assert len(events) == 2 + assert events[0]["method"] == "notifications/progress" + assert events[0]["params"]["progressToken"] == "tok-missing" + assert events[1]["id"] == 7800 + assert events[1]["error"]["code"] == INVALID_PARAMS + + +async def test_modern_ladder_invalid_params_rejection_stays_http_400() -> None: + """Spec-mandated: a pre-dispatch ladder rejection carrying -32602 (missing required + `_meta` envelope key) MUST still answer HTTP 400, preserving the origin split.""" + mcp = _unknown_resource_mcp_server() + body = _read_resource_body() + del body["params"]["_meta"][CLIENT_CAPABILITIES_META_KEY] + headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"} + async with _asgi_client(mcp._lowlevel_server, json_response=True, accept="application/json") as http: + response = await http.post("/mcp", json=body, headers=headers) + + assert response.status_code == 400 + assert response.headers["content-type"].split(";", 1)[0] == "application/json" + assert response.json()["error"]["code"] == INVALID_PARAMS