diff --git a/src/mcp/server/stdio.py b/src/mcp/server/stdio.py index de8bbae5f1..09bc5ed32c 100644 --- a/src/mcp/server/stdio.py +++ b/src/mcp/server/stdio.py @@ -11,6 +11,7 @@ async def run_server(): ``` """ +import json import os import sys import threading @@ -18,7 +19,7 @@ async def run_server(): from contextlib import asynccontextmanager, suppress from dataclasses import dataclass from io import TextIOWrapper -from typing import BinaryIO, Literal, TextIO +from typing import Any, BinaryIO, Literal, TextIO, cast import anyio import anyio.lowlevel @@ -158,6 +159,19 @@ def release() -> None: return os.fdopen(private_fd, mode, closefd=False), release +def _extract_request_id(line: str) -> types.RequestId | None: + """Best-effort extraction of JSON-RPC request `id` when `validate_json` fails.""" + try: + raw: Any = json.loads(line) + except Exception: + return None + if isinstance(raw, dict): + raw_id: Any = cast(dict[str, Any], raw).get("id") + if isinstance(raw_id, str) or (isinstance(raw_id, int) and not isinstance(raw_id, bool)): + return raw_id + return None + + @asynccontextmanager async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.AsyncFile[str] | None = None): """Serve MCP over the process's stdin and stdout. @@ -188,6 +202,16 @@ async def stdin_reader(): try: message = types.jsonrpc_message_adapter.validate_json(line, by_name=False) except Exception as exc: + error_response = types.JSONRPCError( + jsonrpc="2.0", + id=_extract_request_id(line), + error=types.ErrorData( + code=types.PARSE_ERROR, + message=f"Invalid JSON-RPC message: {exc}", + ), + ) + with suppress(anyio.ClosedResourceError): + await write_stream.send(SessionMessage(error_response)) await read_stream_writer.send(exc) continue diff --git a/tests/server/test_stdio.py b/tests/server/test_stdio.py index eafd1fca59..122b4c061d 100644 --- a/tests/server/test_stdio.py +++ b/tests/server/test_stdio.py @@ -692,3 +692,33 @@ def test_mcpserver_run_stdio_serves_a_modern_connection(monkeypatch: pytest.Monk # resultType is modern-only: proves the request was served at the discovered version. assert responses[1].result["tools"] == [] assert responses[1].result["resultType"] == "complete" + + +@pytest.mark.anyio +async def test_stdio_server_replies_parse_error_on_invalid_json_line() -> None: + """Invalid JSON-RPC request lines (such as lone surrogates) must return -32700 instead of hanging.""" + import json + + lone_surrogate_line = ( + '{"jsonrpc":"2.0","id":3,"method":"tools/call",' + '"params":{"name":"echo","arguments":{"text":"bad \\ud83d bad"}}}\n' + ) + malformed_line = "{not valid json\n" + stdin = anyio.wrap_file(io.StringIO(lone_surrogate_line + malformed_line)) + out_buf = io.StringIO() + stdout = anyio.wrap_file(out_buf) + + with anyio.fail_after(5): + async with stdio_server(stdin=stdin, stdout=stdout) as (read_stream, write_stream): + async with read_stream, write_stream: + received = [item async for item in read_stream] + + assert len(received) == 2 + assert all(isinstance(item, Exception) for item in received) + + lines = [json.loads(line) for line in out_buf.getvalue().splitlines() if line.strip()] + assert len(lines) == 2 + assert lines[0]["id"] == 3 + assert lines[0]["error"]["code"] == -32700 + assert lines[1]["id"] is None + assert lines[1]["error"]["code"] == -32700