1313from mcp_types import (
1414 CLIENT_CAPABILITIES_META_KEY ,
1515 CLIENT_INFO_META_KEY ,
16+ PARSE_ERROR ,
1617 PROTOCOL_VERSION_META_KEY ,
1718 SERVER_INFO_META_KEY ,
19+ ErrorData ,
20+ JSONRPCError ,
1821 JSONRPCMessage ,
1922 JSONRPCRequest ,
2023 JSONRPCResponse ,
@@ -97,6 +100,127 @@ async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch) -> Non
97100 assert second .message == valid
98101
99102
103+ def _bad_text_line (id_json : str = "3" ) -> str :
104+ """A pure-ASCII request line pydantic rejects: a lone surrogate escape (issue #3894)."""
105+ return f'{{"jsonrpc":"2.0","id":{ id_json } ,"method":"ping","params":{{"text":"bad \\ ud83d bad"}}}}'
106+
107+
108+ @pytest .mark .anyio
109+ @pytest .mark .parametrize (
110+ ("line" , "expected_id" ),
111+ [
112+ ("not json at all" , None ),
113+ ("[1,2,3]" , None ),
114+ ('{"foo": 1}' , None ),
115+ (_bad_text_line ("true" ), None ),
116+ (_bad_text_line ("{}" ), None ),
117+ (_bad_text_line ("3" ), 3 ),
118+ (_bad_text_line ('"s3"' ), "s3" ),
119+ ],
120+ ids = ["not-json" , "array" , "no-id-no-method" , "boolean-id" , "object-id" , "int-id" , "str-id" ],
121+ )
122+ async def test_stdio_server_answers_an_invalid_line_with_a_parse_error (
123+ line : str , expected_id : str | int | None
124+ ) -> None :
125+ """A line that fails validation is answered with -32700 echoing a recoverable id, and serving continues.
126+
127+ Spec-mandated reply shape (JSON-RPC 2.0) with SDK-defined id recovery: the
128+ raw line is re-parsed with stdlib json, which tolerates the lone surrogate
129+ escapes pydantic-core rejects, so a client's pending call can correlate.
130+ The typed API cannot produce these lines, so they are scripted raw.
131+ """
132+ ping = JSONRPCRequest (jsonrpc = "2.0" , id = 4 , method = "ping" )
133+ stdin = io .StringIO (line + "\n " + ping .model_dump_json (by_alias = True , exclude_none = True ) + "\n " )
134+ stdout = io .StringIO ()
135+
136+ with anyio .fail_after (5 ):
137+ async with stdio_server (stdin = anyio .AsyncFile (stdin ), stdout = anyio .AsyncFile (stdout )) as (
138+ read_stream ,
139+ write_stream ,
140+ ):
141+ async with read_stream :
142+ failure = await read_stream .receive ()
143+ assert isinstance (failure , Exception )
144+
145+ followup = await read_stream .receive ()
146+ assert isinstance (followup , SessionMessage )
147+ assert followup .message == ping
148+ await write_stream .aclose ()
149+
150+ stdout .seek (0 )
151+ output_lines = stdout .readlines ()
152+ assert len (output_lines ) == 1
153+ assert jsonrpc_message_adapter .validate_json (output_lines [0 ].strip ()) == JSONRPCError (
154+ jsonrpc = "2.0" , id = expected_id , error = ErrorData (code = PARSE_ERROR , message = "Parse error" )
155+ )
156+
157+
158+ @pytest .mark .anyio
159+ async def test_stdio_server_does_not_answer_a_notification_shaped_line () -> None :
160+ """A notification-shaped line that fails validation is dropped, never answered.
161+
162+ JSON-RPC 2.0 §4.1: the server MUST NOT reply to a notification; the
163+ unreadable line surfaces as an in-stream exception and later traffic
164+ continues (issue #3894).
165+ """
166+ notification_line = (
167+ '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"echo","arguments":{"text":"bad \\ ud83d bad"}}}'
168+ )
169+ ping = JSONRPCRequest (jsonrpc = "2.0" , id = 4 , method = "ping" )
170+ response = JSONRPCResponse (jsonrpc = "2.0" , id = 4 , result = {})
171+ stdin = io .StringIO (notification_line + "\n " + ping .model_dump_json (by_alias = True , exclude_none = True ) + "\n " )
172+ stdout = io .StringIO ()
173+
174+ with anyio .fail_after (5 ):
175+ async with stdio_server (stdin = anyio .AsyncFile (stdin ), stdout = anyio .AsyncFile (stdout )) as (
176+ read_stream ,
177+ write_stream ,
178+ ):
179+ async with read_stream :
180+ failure = await read_stream .receive ()
181+ assert isinstance (failure , Exception )
182+
183+ followup = await read_stream .receive ()
184+ assert isinstance (followup , SessionMessage )
185+ assert followup .message == ping
186+
187+ await write_stream .send (SessionMessage (response ))
188+ await write_stream .aclose ()
189+
190+ stdout .seek (0 )
191+ assert [jsonrpc_message_adapter .validate_json (line ) for line in stdout .readlines ()] == [response ]
192+
193+
194+ @pytest .mark .anyio
195+ async def test_stdio_server_drops_the_parse_error_reply_when_the_write_stream_is_closed () -> None :
196+ """A parse error reply racing a closed write stream is dropped without killing the reader.
197+
198+ SDK-defined: the dispatcher closes the write stream when the connection
199+ ends, and the transport's best-effort reply must not turn that shutdown
200+ into an error; stdin keeps being read afterwards.
201+ """
202+ ping = JSONRPCRequest (jsonrpc = "2.0" , id = 4 , method = "ping" )
203+ stdin = io .StringIO (_bad_text_line ("3" ) + "\n " + ping .model_dump_json (by_alias = True , exclude_none = True ) + "\n " )
204+ stdout = io .StringIO ()
205+
206+ with anyio .fail_after (5 ):
207+ async with stdio_server (stdin = anyio .AsyncFile (stdin ), stdout = anyio .AsyncFile (stdout )) as (
208+ read_stream ,
209+ write_stream ,
210+ ):
211+ write_stream .close ()
212+ async with read_stream :
213+ failure = await read_stream .receive ()
214+ assert isinstance (failure , Exception )
215+
216+ followup = await read_stream .receive ()
217+ assert isinstance (followup , SessionMessage )
218+ assert followup .message == ping
219+ await write_stream .aclose ()
220+
221+ assert stdout .getvalue () == ""
222+
223+
100224@contextmanager
101225def _pipe_planted_on_fd0 (monkeypatch : pytest .MonkeyPatch ) -> Iterator [tuple [int , int ]]:
102226 """Plants a fresh pipe on fd 0 and rebinds sys.stdin over it; yields (read_fd, write_fd).
@@ -607,15 +731,18 @@ def close(self) -> None:
607731 pass
608732
609733
610- def _serve_stdio_and_collect (
611- monkeypatch : pytest .MonkeyPatch , server : MCPServer , frames : list [JSONRPCRequest ], responses : int
734+ def _serve_stdio_lines_and_collect (
735+ monkeypatch : pytest .MonkeyPatch , server : MCPServer , lines : list [str ], responses : int
612736) -> list [JSONRPCMessage ]:
613- """Serve `frames` over process stdio and return the parsed response lines.
737+ """Serve raw wire lines over process stdio and return the parsed response lines.
614738
615- Runs the blocking server.run("stdio") in a daemon thread and signals stdin EOF only after
616- `responses` lines arrive - as a real client would - so handlers never race EOF cancellation.
739+ `_serve_stdio_and_collect` frames typed messages; malformed wire input can
740+ only be produced as raw lines, so this twin takes them verbatim. Runs the
741+ blocking server.run("stdio") in a daemon thread and signals stdin EOF only
742+ after `responses` lines arrive - as a real client would - so handlers
743+ never race EOF cancellation.
617744 """
618- payload = "" .join (f . model_dump_json ( by_alias = True , exclude_none = True ) + "\n " for f in frames ).encode ()
745+ payload = "" .join (line + "\n " for line in lines ).encode ()
619746 stdin = _GatedStdin (payload )
620747 stdout = _NotifyingStdout ()
621748 monkeypatch .setattr (sys , "stdin" , TextIOWrapper (stdin , encoding = "utf-8" ))
@@ -634,6 +761,18 @@ def target() -> None:
634761 return [jsonrpc_message_adapter .validate_json (line ) for line in stdout .getvalue ().decode ().splitlines ()]
635762
636763
764+ def _serve_stdio_and_collect (
765+ monkeypatch : pytest .MonkeyPatch , server : MCPServer , frames : list [JSONRPCRequest ], responses : int
766+ ) -> list [JSONRPCMessage ]:
767+ """Serve `frames` over process stdio and return the parsed response lines."""
768+ return _serve_stdio_lines_and_collect (
769+ monkeypatch ,
770+ server ,
771+ [frame .model_dump_json (by_alias = True , exclude_none = True ) for frame in frames ],
772+ responses ,
773+ )
774+
775+
637776def test_mcpserver_run_stdio_serves_until_stdin_closes (monkeypatch : pytest .MonkeyPatch ) -> None :
638777 """`MCPServer.run("stdio")` serves over process stdio and returns at stdin EOF."""
639778 ping = JSONRPCRequest (jsonrpc = "2.0" , id = 1 , method = "ping" )
@@ -692,3 +831,26 @@ def test_mcpserver_run_stdio_serves_a_modern_connection(monkeypatch: pytest.Monk
692831 # resultType is modern-only: proves the request was served at the discovered version.
693832 assert responses [1 ].result ["tools" ] == []
694833 assert responses [1 ].result ["resultType" ] == "complete"
834+
835+
836+ def test_mcpserver_run_stdio_answers_a_malformed_line_and_keeps_serving (monkeypatch : pytest .MonkeyPatch ) -> None :
837+ """`run("stdio")` replies -32700 with the recovered id to a lone-surrogate line, then serves normally.
838+
839+ Regression for issue #3894: the reply rides the real dispatcher path, so
840+ the wire carries the Parse error for id 3 followed by the response to id 4.
841+ """
842+ bad_line = (
843+ '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"bad \\ ud83d bad"}}}'
844+ )
845+ ping = JSONRPCRequest (jsonrpc = "2.0" , id = 4 , method = "ping" )
846+
847+ server = MCPServer (name = "ParseErrorStdioServer" )
848+ responses = _serve_stdio_lines_and_collect (
849+ monkeypatch ,
850+ server ,
851+ [bad_line , ping .model_dump_json (by_alias = True , exclude_none = True )],
852+ 2 ,
853+ )
854+
855+ assert responses [0 ] == JSONRPCError (jsonrpc = "2.0" , id = 3 , error = ErrorData (code = PARSE_ERROR , message = "Parse error" ))
856+ assert responses [1 ] == JSONRPCResponse (jsonrpc = "2.0" , id = 4 , result = {})
0 commit comments