|
| 1 | +"""Experimental, unstable. Single-exchange HTTP serving for protocol version 2026-07-28. |
| 2 | +
|
| 3 | +No public API; everything in this module may change or vanish without |
| 4 | +deprecation. The legacy streamable-HTTP transport is untouched and remains the |
| 5 | +supported entry point. |
| 6 | +
|
| 7 | +A 2026-07-28 request is a self-contained POST: no `initialize` handshake, no |
| 8 | +`Mcp-Session-Id`, one JSON-RPC request in, one JSON-RPC response out. This |
| 9 | +module handles such a request directly in the ASGI task - no memory streams, |
| 10 | +no per-request task group, no `JSONRPCDispatcher`. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import logging |
| 16 | +from collections.abc import Mapping |
| 17 | +from dataclasses import dataclass, field |
| 18 | +from typing import TYPE_CHECKING, Any, Final |
| 19 | + |
| 20 | +import anyio |
| 21 | +import anyio.abc |
| 22 | +from pydantic import ValidationError |
| 23 | +from starlette.requests import Request |
| 24 | +from starlette.responses import Response |
| 25 | +from starlette.types import Receive, Scope, Send |
| 26 | + |
| 27 | +from mcp.server.runner import ServerRunner, otel_middleware |
| 28 | +from mcp.server.transport_security import TransportSecurityMiddleware |
| 29 | +from mcp.shared.dispatcher import CallOptions, OnNotify, OnRequest |
| 30 | +from mcp.shared.exceptions import MCPError, NoBackChannelError |
| 31 | +from mcp.shared.message import MessageMetadata, ServerMessageMetadata |
| 32 | +from mcp.shared.transport_context import TransportContext |
| 33 | +from mcp.types import ( |
| 34 | + INTERNAL_ERROR, |
| 35 | + INVALID_PARAMS, |
| 36 | + PARSE_ERROR, |
| 37 | + ErrorData, |
| 38 | + JSONRPCError, |
| 39 | + JSONRPCRequest, |
| 40 | + JSONRPCResponse, |
| 41 | + RequestId, |
| 42 | +) |
| 43 | + |
| 44 | +if TYPE_CHECKING: |
| 45 | + from mcp.server.streamable_http_manager import StreamableHTTPSessionManager |
| 46 | + |
| 47 | +logger = logging.getLogger(__name__) |
| 48 | + |
| 49 | +MODERN_PROTOCOL_VERSION: Final[str] = "2026-07-28" |
| 50 | +"""The protocol version this module serves. Kept local so it does not leak into |
| 51 | +`SUPPORTED_PROTOCOL_VERSIONS` or the legacy handshake.""" |
| 52 | + |
| 53 | + |
| 54 | +@dataclass |
| 55 | +class _SingleExchangeDispatchContext: |
| 56 | + """`DispatchContext` for one inbound HTTP request. |
| 57 | +
|
| 58 | + Structurally satisfies `mcp.shared.dispatcher.DispatchContext`. The |
| 59 | + back-channel is closed by construction: a 2026-07-28 server cannot send |
| 60 | + requests to the client. |
| 61 | + """ |
| 62 | + |
| 63 | + transport: TransportContext |
| 64 | + request_id: RequestId |
| 65 | + message_metadata: MessageMetadata |
| 66 | + cancel_requested: anyio.Event = field(default_factory=anyio.Event) |
| 67 | + can_send_request: bool = False |
| 68 | + |
| 69 | + async def send_raw_request( |
| 70 | + self, |
| 71 | + method: str, |
| 72 | + params: Mapping[str, Any] | None, |
| 73 | + opts: CallOptions | None = None, |
| 74 | + ) -> dict[str, Any]: |
| 75 | + raise NoBackChannelError(method) |
| 76 | + |
| 77 | + async def notify(self, method: str, params: Mapping[str, Any] | None) -> None: |
| 78 | + return None |
| 79 | + |
| 80 | + async def progress(self, progress: float, total: float | None = None, message: str | None = None) -> None: |
| 81 | + # TODO: no progressToken plumbing yet. |
| 82 | + return None |
| 83 | + |
| 84 | + |
| 85 | +class SingleExchangeDispatcher: |
| 86 | + """Dispatcher for exactly one inbound JSON-RPC request over a single HTTP POST. |
| 87 | +
|
| 88 | + The exception->wire boundary lives here (mirrors `JSONRPCDispatcher`'s |
| 89 | + role). Implements the `Dispatcher` Protocol so `ServerRunner` / |
| 90 | + `Connection` / `ServerSession` accept it; `run()` is never driven. |
| 91 | + """ |
| 92 | + |
| 93 | + def __init__(self, request: Request) -> None: |
| 94 | + self._request = request |
| 95 | + self._tctx = TransportContext( |
| 96 | + kind="streamable-http", |
| 97 | + can_send_request=False, |
| 98 | + headers=request.headers, |
| 99 | + ) |
| 100 | + |
| 101 | + async def send_raw_request( |
| 102 | + self, |
| 103 | + method: str, |
| 104 | + params: Mapping[str, Any] | None, |
| 105 | + opts: CallOptions | None = None, |
| 106 | + *, |
| 107 | + _related_request_id: RequestId | None = None, |
| 108 | + ) -> dict[str, Any]: |
| 109 | + raise NoBackChannelError(method) |
| 110 | + |
| 111 | + async def notify( |
| 112 | + self, |
| 113 | + method: str, |
| 114 | + params: Mapping[str, Any] | None, |
| 115 | + *, |
| 116 | + _related_request_id: RequestId | None = None, |
| 117 | + ) -> None: |
| 118 | + # TODO: buffer and stream as SSE once the response-mode design lands. |
| 119 | + return None |
| 120 | + |
| 121 | + async def run( |
| 122 | + self, |
| 123 | + on_request: OnRequest, |
| 124 | + on_notify: OnNotify, |
| 125 | + *, |
| 126 | + task_status: anyio.abc.TaskStatus[None] = anyio.TASK_STATUS_IGNORED, |
| 127 | + ) -> None: |
| 128 | + raise RuntimeError("SingleExchangeDispatcher.run() is never driven; use handle()") |
| 129 | + |
| 130 | + async def handle(self, req: JSONRPCRequest, on_request: OnRequest) -> JSONRPCResponse | JSONRPCError: |
| 131 | + """Dispatch one request and map any exception to a `JSONRPCError`.""" |
| 132 | + dctx = _SingleExchangeDispatchContext( |
| 133 | + transport=self._tctx, |
| 134 | + request_id=req.id, |
| 135 | + message_metadata=ServerMessageMetadata(request_context=self._request), |
| 136 | + ) |
| 137 | + try: |
| 138 | + result = await on_request(dctx, req.method, req.params) |
| 139 | + return JSONRPCResponse(jsonrpc="2.0", id=req.id, result=result) |
| 140 | + except MCPError as e: |
| 141 | + return JSONRPCError(jsonrpc="2.0", id=req.id, error=e.error) |
| 142 | + except ValidationError: |
| 143 | + return JSONRPCError( |
| 144 | + jsonrpc="2.0", |
| 145 | + id=req.id, |
| 146 | + error=ErrorData(code=INVALID_PARAMS, message="Invalid request parameters", data=""), |
| 147 | + ) |
| 148 | + # TODO: consolidate the three exception->ErrorData copies once the |
| 149 | + # code=0 compat pin in JSONRPCDispatcher is lifted. |
| 150 | + except Exception: |
| 151 | + logger.exception("handler for %r raised", req.method) |
| 152 | + return JSONRPCError( |
| 153 | + jsonrpc="2.0", |
| 154 | + id=req.id, |
| 155 | + error=ErrorData(code=INTERNAL_ERROR, message="Internal server error"), |
| 156 | + ) |
| 157 | + |
| 158 | + |
| 159 | +async def handle_modern_request( |
| 160 | + manager: StreamableHTTPSessionManager, |
| 161 | + scope: Scope, |
| 162 | + receive: Receive, |
| 163 | + send: Send, |
| 164 | +) -> None: |
| 165 | + """ASGI handler for a single 2026-07-28 POST. |
| 166 | +
|
| 167 | + Called from `StreamableHTTPSessionManager.handle_request` when the |
| 168 | + `MCP-Protocol-Version` header is `2026-07-28`. Never sets `Mcp-Session-Id`. |
| 169 | + """ |
| 170 | + request = Request(scope, receive) |
| 171 | + |
| 172 | + security = TransportSecurityMiddleware(manager.security_settings) |
| 173 | + err = await security.validate_request(request, is_post=(request.method == "POST")) |
| 174 | + if err is not None: |
| 175 | + await err(scope, receive, send) |
| 176 | + return |
| 177 | + |
| 178 | + # TODO: validate Accept header once the JSON-vs-SSE response-mode design is settled. |
| 179 | + |
| 180 | + if request.method != "POST": |
| 181 | + # TODO: GET/DELETE rejection (405 + -32601) lands with the validation ladder. |
| 182 | + await Response(status_code=405)(scope, receive, send) |
| 183 | + return |
| 184 | + |
| 185 | + body = await request.body() |
| 186 | + try: |
| 187 | + req = JSONRPCRequest.model_validate_json(body) |
| 188 | + except ValidationError: |
| 189 | + msg = JSONRPCError(jsonrpc="2.0", id=None, error=ErrorData(code=PARSE_ERROR, message="Parse error")) |
| 190 | + await Response( |
| 191 | + msg.model_dump_json(by_alias=True, exclude_none=True), |
| 192 | + status_code=400, |
| 193 | + media_type="application/json", |
| 194 | + )(scope, receive, send) |
| 195 | + return |
| 196 | + |
| 197 | + dispatcher = SingleExchangeDispatcher(request) |
| 198 | + # TODO: per-request lifespan re-entry matches stateless_http=True today; revisit in #2893. |
| 199 | + async with manager.app.lifespan(manager.app) as lifespan_state: |
| 200 | + runner = ServerRunner( |
| 201 | + server=manager.app, |
| 202 | + dispatcher=dispatcher, |
| 203 | + lifespan_state=lifespan_state, |
| 204 | + has_standalone_channel=False, |
| 205 | + stateless=True, |
| 206 | + dispatch_middleware=[otel_middleware], |
| 207 | + ) |
| 208 | + runner.connection.protocol_version = MODERN_PROTOCOL_VERSION |
| 209 | + try: |
| 210 | + msg = await dispatcher.handle(req, runner._compose_on_request()) # type: ignore[reportPrivateUsage] |
| 211 | + finally: |
| 212 | + await runner.connection.exit_stack.aclose() |
| 213 | + |
| 214 | + # TODO: error.code -> HTTP status mapping is a follow-up; 200 for all JSONRPCError bodies for now. |
| 215 | + await Response( |
| 216 | + msg.model_dump_json(by_alias=True, exclude_none=True), |
| 217 | + status_code=200, |
| 218 | + media_type="application/json", |
| 219 | + )(scope, receive, send) |
0 commit comments