Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/mcp/server/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ async def run_server():
```
"""

import json
import os
import re
import sys
import threading
from collections.abc import Callable
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions tests/server/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
Loading