@@ -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
101135def _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