2525import logging
2626from collections .abc import Awaitable , Mapping
2727from dataclasses import dataclass , field
28+ from types import MappingProxyType
2829from typing import TYPE_CHECKING , Any , Final , cast
2930
3031import anyio
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 ,
5559from mcp .server .streamable_http import check_accept_headers
5660from mcp .server .transport_security import TransportSecurityMiddleware , TransportSecuritySettings
5761from mcp .shared .dispatcher import CallOptions
58- from mcp .shared .exceptions import NoBackChannelError
62+ from mcp .shared .exceptions import MCPError , NoBackChannelError
5963from mcp .shared .inbound import (
6064 ERROR_CODE_HTTP_STATUS ,
6165 MCP_PARAM_HEADER_PREFIX ,
@@ -123,21 +127,25 @@ async def progress(self, progress: float, total: float | None = None, message: s
123127 await self .notify ("notifications/progress" , params )
124128
125129
126- async def _to_jsonrpc_response (
130+ async def _execute_jsonrpc (
127131 request_id : RequestId , coro : Awaitable [dict [str , Any ]]
128- ) -> JSONRPCResponse | JSONRPCError :
129- """Await ``coro`` and wrap its outcome as the JSON-RPC reply for ``request_id``.
130-
131- The exception-to-wire boundary for the modern HTTP entry, composed around
132- `serve_one`: `modern_error_data` maps the shared ladder and surfaces
133- anything else as a generic `INTERNAL_ERROR` so handler internals never
134- reach the wire.
132+ ) -> tuple [JSONRPCResponse | JSONRPCError , bool ]:
133+ """Await ``coro`` and return ``(reply, from_handler)``.
134+
135+ ``MCPError`` originates from dispatch/handlers (including ``MCPError``
136+ conversions inside ``ServerRunner``) so HTTP status selection uses
137+ ``_HANDLER_ERROR_HTTP_STATUS``. Request/envelope ``ValidationError``
138+ (e.g. a mis-shaped ``_meta`` envelope) keeps ``from_handler=False`` so it
139+ maps through ``ERROR_CODE_HTTP_STATUS`` (400), and unmapped exceptions map
140+ to ``INTERNAL_ERROR`` (HTTP 200).
135141 """
136142 try :
137143 result = await coro
144+ except MCPError as exc :
145+ return JSONRPCError (jsonrpc = "2.0" , id = request_id , error = modern_error_data (exc )), True
138146 except Exception as exc :
139- return JSONRPCError (jsonrpc = "2.0" , id = request_id , error = modern_error_data (exc ))
140- return JSONRPCResponse (jsonrpc = "2.0" , id = request_id , result = result )
147+ return JSONRPCError (jsonrpc = "2.0" , id = request_id , error = modern_error_data (exc )), False
148+ return JSONRPCResponse (jsonrpc = "2.0" , id = request_id , result = result ), False
141149
142150
143151_SSE_PING_INTERVAL : float = 15.0
@@ -171,14 +179,35 @@ async def _write_rejection(
171179 await _write (rej , scope , receive , send )
172180
173181
182+ _HANDLER_ERROR_HTTP_STATUS : Final [Mapping [int , int ]] = MappingProxyType (
183+ {
184+ HEADER_MISMATCH : 400 ,
185+ MISSING_REQUIRED_CLIENT_CAPABILITY : 400 ,
186+ UNSUPPORTED_PROTOCOL_VERSION : 400 ,
187+ METHOD_NOT_FOUND : 404 ,
188+ }
189+ )
190+ """HTTP status overrides for handler/dispatch-origin JSON-RPC errors.
191+
192+ Only error codes with a transport HTTP status in the 2026-07-28 spec map
193+ above `200`. `-32602 INVALID_PARAMS` is intentionally omitted here because
194+ handler-origin `-32602` (such as a missing resource URI) is an in-band JSON-RPC
195+ error on HTTP 200, whereas malformed request envelopes fail on the inbound
196+ ladder via :func:`_write_rejection` (`400`).
197+ """
198+
199+
174200async def _write (
175201 msg : JSONRPCResponse | JSONRPCError ,
176202 scope : Scope ,
177203 receive : Receive ,
178204 send : Send ,
205+ * ,
206+ from_handler : bool = False ,
179207) -> 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
208+ """Serialise a JSON-RPC reply with the origin-appropriate HTTP status."""
209+ status_map = _HANDLER_ERROR_HTTP_STATUS if from_handler else ERROR_CODE_HTTP_STATUS
210+ status = status_map .get (msg .error .code , 200 ) if isinstance (msg , JSONRPCError ) else 200
182211 body = msg .model_dump (mode = "json" , by_alias = True , exclude_none = True )
183212 if isinstance (msg , JSONRPCError ) and msg .id is None :
184213 # JSON-RPC requires `id: null` to appear on the wire when the request
@@ -456,20 +485,20 @@ async def handle_modern_request(
456485 # A listen response IS a notification stream, so it always takes the
457486 # SSE path below regardless of the JSON-response preference (the
458487 # TypeScript and Go SDKs route it the same way).
459- msg = await _to_jsonrpc_response (
488+ msg , is_handler_error = await _execute_jsonrpc (
460489 req .id , serve_one (app , dctx , req .method , req .params , connection = connection , lifespan_state = lifespan_state )
461490 )
462- await _write (msg , scope , receive , send )
491+ await _write (msg , scope , receive , send , from_handler = is_handler_error )
463492 return
464493
465494 send_ch , recv_ch = anyio .create_memory_object_stream [bytes ](0 )
466495 dctx .sink = send_ch
467- result : list [JSONRPCResponse | JSONRPCError ] = []
496+ result : list [tuple [ JSONRPCResponse | JSONRPCError , bool ] ] = []
468497
469498 async def run_handler () -> None :
470499 async with send_ch :
471500 result .append (
472- await _to_jsonrpc_response (
501+ await _execute_jsonrpc (
473502 req .id ,
474503 serve_one (app , dctx , req .method , req .params , connection = connection , lifespan_state = lifespan_state ),
475504 )
@@ -494,10 +523,11 @@ async def watch_disconnect(cancel_scope: anyio.CancelScope) -> None:
494523
495524 if done :
496525 # 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 )
526+ # `application/json` with the handler-mapped status. Spec-assigned
527+ # dispatch errors (`METHOD_NOT_FOUND`, missing-capability) still map
528+ # to 404/400, while handler `INVALID_PARAMS` stays in-band on 200.
529+ msg , is_handler_error = result [0 ]
530+ await _write (msg , scope , receive , send , from_handler = is_handler_error )
501531 else :
502532 # First notification arrived, or the deferral window elapsed: commit
503533 # `text/event-stream` and start pinging so a proxy idle-read timeout
@@ -522,6 +552,6 @@ async def watch_disconnect(cancel_scope: anyio.CancelScope) -> None:
522552 event = await recv_ch .receive ()
523553 except anyio .EndOfStream :
524554 done = True
525- await send ({"type" : "http.response.body" , "body" : _sse_event (result [0 ]), "more_body" : False })
555+ await send ({"type" : "http.response.body" , "body" : _sse_event (result [0 ][ 0 ] ), "more_body" : False })
526556
527557 tg .cancel_scope .cancel ()
0 commit comments