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: 36 additions & 1 deletion src/mcp/server/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@ async def run_server():
```
"""

import json
import os
import sys
import threading
from collections.abc import Callable
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
import mcp_types as types
from pydantic import ValidationError

from mcp.os.win32.utilities import rebind_std_handle_to_fd
from mcp.shared._context_streams import create_context_streams
Expand Down Expand Up @@ -158,6 +160,35 @@ def release() -> None:
return os.fdopen(private_fd, mode, closefd=False), release


def _validation_error_response(line: str, exc: Exception) -> types.JSONRPCError | None:
"""Build a JSON-RPC error response for a stdin line that failed validation."""
try:
decoded: Any = json.loads(line)
except (ValueError, RecursionError):
return types.JSONRPCError(
jsonrpc="2.0",
id=None,
error=types.ErrorData(code=types.PARSE_ERROR, message="Parse error"),
)

if isinstance(decoded, dict):
obj = cast(dict[str, Any], decoded)
if "id" not in obj and "method" in obj:
# Notifications must not receive a JSON-RPC reply.
return None
raw_id = obj.get("id")
req_id: types.RequestId | None = (
raw_id if isinstance(raw_id, str | int) and not isinstance(raw_id, bool) else None
)
else:
req_id = None

is_json_error = isinstance(exc, ValidationError) and any(err.get("type") == "json_invalid" for err in exc.errors())
code = types.PARSE_ERROR if is_json_error else types.INVALID_REQUEST
message = "Parse error" if is_json_error else "Invalid request"
return types.JSONRPCError(jsonrpc="2.0", id=req_id, error=types.ErrorData(code=code, message=message))


@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.
Expand Down Expand Up @@ -189,6 +220,10 @@ 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)
error_response = _validation_error_response(line, exc)
if error_response is not None:
with suppress(anyio.ClosedResourceError, anyio.BrokenResourceError):
await write_stream.send(SessionMessage(error_response))
continue

session_message = SessionMessage(message)
Expand Down
51 changes: 51 additions & 0 deletions tests/server/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
from mcp_types import (
CLIENT_CAPABILITIES_META_KEY,
CLIENT_INFO_META_KEY,
PARSE_ERROR,
PROTOCOL_VERSION_META_KEY,
SERVER_INFO_META_KEY,
JSONRPCError,
JSONRPCMessage,
JSONRPCRequest,
JSONRPCResponse,
Expand Down Expand Up @@ -692,3 +694,52 @@ 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"


def _serve_raw_stdio_and_collect(
monkeypatch: pytest.MonkeyPatch, server: MCPServer, lines: list[bytes], responses: int
) -> list[JSONRPCMessage]:
"""Serve raw wire lines over process stdio and return parsed response lines."""
payload = b"".join(line + b"\n" for line in lines)
stdin = _GatedStdin(payload)
stdout = _NotifyingStdout()
monkeypatch.setattr(sys, "stdin", TextIOWrapper(stdin, encoding="utf-8"))
monkeypatch.setattr(sys, "stdout", TextIOWrapper(stdout, encoding="utf-8"))

thread = threading.Thread(target=lambda: server.run("stdio"), daemon=True)
thread.start()
arrived = stdout.wait_for_lines(responses, timeout=2.0)
stdin.release()
thread.join(5)
assert not thread.is_alive(), 'run("stdio") did not return after stdin EOF'
assert arrived, f"expected {responses} response line(s); stdout carried: {stdout.getvalue()!r}"
return [jsonrpc_message_adapter.validate_json(line) for line in stdout.getvalue().decode().splitlines()]


def test_mcpserver_run_stdio_replies_to_lone_surrogate_request(monkeypatch: pytest.MonkeyPatch) -> None:
"""A request line with a lone UTF-16 surrogate escape receives a JSON-RPC error instead of hanging (#3894)."""
bad_line = (
b'{"jsonrpc":"2.0","id":3,"method":"tools/call",'
b'"params":{"name":"echo","arguments":{"text":"bad \\ud83d bad"}}}'
)
ping = JSONRPCRequest(jsonrpc="2.0", id=4, method="ping").model_dump_json(by_alias=True, exclude_none=True).encode()

responses = _serve_raw_stdio_and_collect(monkeypatch, MCPServer(name="SurrogateStdioServer"), [bad_line, ping], 2)

assert isinstance(responses[0], JSONRPCError)
assert responses[0].id == 3
assert responses[0].error.code == PARSE_ERROR
assert responses[1] == JSONRPCResponse(jsonrpc="2.0", id=4, result={})


def test_mcpserver_run_stdio_replies_parse_error_on_malformed_json(monkeypatch: pytest.MonkeyPatch) -> None:
"""A malformed JSON line on stdin receives a PARSE_ERROR with id=None and does not stall later requests."""
bad_line = b"{not valid json"
ping = JSONRPCRequest(jsonrpc="2.0", id=2, method="ping").model_dump_json(by_alias=True, exclude_none=True).encode()

responses = _serve_raw_stdio_and_collect(monkeypatch, MCPServer(name="MalformedStdioServer"), [bad_line, ping], 2)

assert isinstance(responses[0], JSONRPCError)
assert responses[0].id is None
assert responses[0].error.code == PARSE_ERROR
assert responses[1] == JSONRPCResponse(jsonrpc="2.0", id=2, result={})
Loading