Skip to content

Commit 076def2

Browse files
fix(stdio): emit JSON-RPC Parse error (-32700) on malformed request lines (#3894)
1 parent 77001c9 commit 076def2

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

‎src/mcp/server/stdio.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ async def run_server():
1111
```
1212
"""
1313

14+
import json
1415
import os
16+
import re
1517
import sys
1618
import threading
1719
from collections.abc import Callable
@@ -42,6 +44,27 @@ async def run_server():
4244
_claims: dict[int, "_StreamClaim"] = {}
4345
_claims_lock = threading.Lock()
4446

47+
_JSONRPC_ID_RE = re.compile(r'"id"\s*:\s*(-?\d+|"(?:[^"\\]|\\.)*"|null)')
48+
49+
50+
def _extract_jsonrpc_id(line: str) -> types.RequestId | None:
51+
"""Extract the JSON-RPC request ID from an invalid or unparseable JSON line, if present."""
52+
match = _JSONRPC_ID_RE.search(line)
53+
if not match:
54+
return None
55+
val = match.group(1).strip()
56+
if val == "null":
57+
return None
58+
if val.startswith('"') and val.endswith('"'):
59+
try:
60+
return json.loads(val)
61+
except Exception:
62+
return val[1:-1]
63+
try:
64+
return int(val)
65+
except ValueError:
66+
return None
67+
4568

4669
@dataclass
4770
class _StreamClaim:
@@ -189,6 +212,20 @@ async def stdin_reader():
189212
message = types.jsonrpc_message_adapter.validate_json(line, by_name=False)
190213
except Exception as exc:
191214
await read_stream_writer.send(exc)
215+
# When a request line fails JSON validation, emit a standard JSON-RPC
216+
# Parse error (-32700) to stdout per JSON-RPC 2.0 §5 so the client's
217+
# call does not hang indefinitely.
218+
req_id = _extract_jsonrpc_id(line)
219+
error_response = types.JSONRPCError(
220+
jsonrpc="2.0",
221+
id=req_id,
222+
error=types.ErrorData(
223+
code=types.PARSE_ERROR,
224+
message=f"Parse error: {exc}",
225+
),
226+
)
227+
with suppress(anyio.BrokenResourceError, anyio.ClosedResourceError):
228+
await write_stream.send(SessionMessage(error_response))
192229
continue
193230

194231
session_message = SessionMessage(message)

‎tests/server/test_stdio.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,40 @@ async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch) -> Non
9797
assert second.message == valid
9898

9999

100+
@pytest.mark.anyio
101+
async def test_stdio_server_invalid_json_emits_parse_error() -> None:
102+
"""When a line fails JSON validation, stdio_server emits a JSON-RPC Parse error (-32700) to stdout."""
103+
bad_line = '{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"text": "bad \\ud83d bad"}}\n'
104+
valid_line = '{"jsonrpc": "2.0", "id": 4, "method": "ping"}\n'
105+
106+
stdin = io.StringIO(bad_line + valid_line)
107+
stdout = io.StringIO()
108+
109+
with anyio.fail_after(5):
110+
async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as (
111+
read_stream,
112+
write_stream,
113+
):
114+
async with read_stream:
115+
first = await read_stream.receive()
116+
assert isinstance(first, Exception)
117+
118+
second = await read_stream.receive()
119+
assert isinstance(second, SessionMessage)
120+
assert second.message == JSONRPCRequest(jsonrpc="2.0", id=4, method="ping")
121+
122+
await write_stream.aclose()
123+
124+
stdout.seek(0)
125+
output_lines = stdout.readlines()
126+
assert len(output_lines) == 1
127+
128+
error_resp = jsonrpc_message_adapter.validate_json(output_lines[0].strip())
129+
assert error_resp.id == 3
130+
assert error_resp.error.code == -32700
131+
assert "Parse error" in error_resp.error.message
132+
133+
100134
@contextmanager
101135
def _pipe_planted_on_fd0(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[int, int]]:
102136
"""Plants a fresh pipe on fd 0 and rebinds sys.stdin over it; yields (read_fd, write_fd).

0 commit comments

Comments
 (0)