From 076def2a5a5f28072f65fd5ad34b6b0ce76feeef Mon Sep 17 00:00:00 2001 From: MilindChatrabhuji Date: Tue, 24 Nov 2026 14:00:30 +0530 Subject: [PATCH] fix(stdio): emit JSON-RPC Parse error (-32700) on malformed request lines (#3894) --- src/mcp/server/stdio.py | 37 +++++++++++++++++++++++++++++++++++++ tests/server/test_stdio.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/src/mcp/server/stdio.py b/src/mcp/server/stdio.py index de8bbae5f1..d8c5b9f707 100644 --- a/src/mcp/server/stdio.py +++ b/src/mcp/server/stdio.py @@ -11,7 +11,9 @@ async def run_server(): ``` """ +import json import os +import re import sys import threading from collections.abc import Callable @@ -42,6 +44,27 @@ async def run_server(): _claims: dict[int, "_StreamClaim"] = {} _claims_lock = threading.Lock() +_JSONRPC_ID_RE = re.compile(r'"id"\s*:\s*(-?\d+|"(?:[^"\\]|\\.)*"|null)') + + +def _extract_jsonrpc_id(line: str) -> types.RequestId | None: + """Extract the JSON-RPC request ID from an invalid or unparseable JSON line, if present.""" + match = _JSONRPC_ID_RE.search(line) + if not match: + return None + val = match.group(1).strip() + if val == "null": + return None + if val.startswith('"') and val.endswith('"'): + try: + return json.loads(val) + except Exception: + return val[1:-1] + try: + return int(val) + except ValueError: + return None + @dataclass class _StreamClaim: @@ -189,6 +212,20 @@ async def stdin_reader(): message = types.jsonrpc_message_adapter.validate_json(line, by_name=False) except Exception as exc: await read_stream_writer.send(exc) + # When a request line fails JSON validation, emit a standard JSON-RPC + # Parse error (-32700) to stdout per JSON-RPC 2.0 ยง5 so the client's + # call does not hang indefinitely. + req_id = _extract_jsonrpc_id(line) + error_response = types.JSONRPCError( + jsonrpc="2.0", + id=req_id, + error=types.ErrorData( + code=types.PARSE_ERROR, + message=f"Parse error: {exc}", + ), + ) + with suppress(anyio.BrokenResourceError, anyio.ClosedResourceError): + await write_stream.send(SessionMessage(error_response)) continue session_message = SessionMessage(message) diff --git a/tests/server/test_stdio.py b/tests/server/test_stdio.py index eafd1fca59..c40464354d 100644 --- a/tests/server/test_stdio.py +++ b/tests/server/test_stdio.py @@ -97,6 +97,40 @@ async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch) -> Non assert second.message == valid +@pytest.mark.anyio +async def test_stdio_server_invalid_json_emits_parse_error() -> None: + """When a line fails JSON validation, stdio_server emits a JSON-RPC Parse error (-32700) to stdout.""" + bad_line = '{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"text": "bad \\ud83d bad"}}\n' + valid_line = '{"jsonrpc": "2.0", "id": 4, "method": "ping"}\n' + + stdin = io.StringIO(bad_line + valid_line) + stdout = io.StringIO() + + with anyio.fail_after(5): + async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as ( + read_stream, + write_stream, + ): + async with read_stream: + first = await read_stream.receive() + assert isinstance(first, Exception) + + second = await read_stream.receive() + assert isinstance(second, SessionMessage) + assert second.message == JSONRPCRequest(jsonrpc="2.0", id=4, method="ping") + + await write_stream.aclose() + + stdout.seek(0) + output_lines = stdout.readlines() + assert len(output_lines) == 1 + + error_resp = jsonrpc_message_adapter.validate_json(output_lines[0].strip()) + assert error_resp.id == 3 + assert error_resp.error.code == -32700 + assert "Parse error" in error_resp.error.message + + @contextmanager def _pipe_planted_on_fd0(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[int, int]]: """Plants a fresh pipe on fd 0 and rebinds sys.stdin over it; yields (read_fd, write_fd).