From d7ef376b25f776cd79c610606f3ed697e7cfe1a6 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 12:14:53 -0600 Subject: [PATCH] test(mcp): make the request timeout test deterministic and keep a handshake timeout as the failure cause - The stall test's request timeout also bounded initialize, which races fake server startup. The stalled call now carries its own SDK timeout. - A late initialize reply broke the SDK's closed read stream and replaced the 408 with BrokenResourceError as the connection's cause. Record the handshake McpError and report it. - Fake server marker files are written atomically, so a poller never reads an empty file. - Fake server skips importing rfc3987_syntax, a Lark grammar compiled at import that dominated its startup. --- .../genkit-mcp/src/genkit_mcp/_connection.py | 11 ++++- packages/genkit-mcp/tests/fake_server.py | 28 ++++++++++--- .../genkit-mcp/tests/late_handshake_server.py | 42 +++++++++++++++++++ .../genkit-mcp/tests/mcp_connection_test.py | 34 ++++++++++++--- 4 files changed, 102 insertions(+), 13 deletions(-) create mode 100644 packages/genkit-mcp/tests/late_handshake_server.py diff --git a/packages/genkit-mcp/src/genkit_mcp/_connection.py b/packages/genkit-mcp/src/genkit_mcp/_connection.py index 092af01e9..75edba3da 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_connection.py +++ b/packages/genkit-mcp/src/genkit_mcp/_connection.py @@ -470,6 +470,7 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No ``_CLOSE_GRACE_SECONDS``. stop: Cancelled by ``close`` to end the session's work. """ + handshake_failure: McpError | None = None try: parameters = StdioServerParameters( command=self._config.command, @@ -490,7 +491,13 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No ) as session: # The SDK's stdio shutdown is not shielded, so no scope around it may be cancelled. with stop: - await session.initialize() + try: + await session.initialize() + except McpError as error: + # A reply that lands after the timeout breaks the read stream the session + # closed, and the SDK reports that BrokenResourceError in place of this. + handshake_failure = error + raise async with self._state_lock: if self._state is _ConnectionState.CONNECTING: self._state = _ConnectionState.OPEN @@ -500,7 +507,7 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No if not isinstance(error, Exception): self._settle(None) raise - cause = _transport_cause(error) + cause = handshake_failure if handshake_failure is not None else _transport_cause(error) # A rendered traceback would print frame locals, and those hold the server's env. named = {'client': self._name} if self._host is None else {'server': self._name, 'host': self._host} logger.warning( diff --git a/packages/genkit-mcp/tests/fake_server.py b/packages/genkit-mcp/tests/fake_server.py index 9bbfc1210..24b9de335 100644 --- a/packages/genkit-mcp/tests/fake_server.py +++ b/packages/genkit-mcp/tests/fake_server.py @@ -6,12 +6,21 @@ """A small subprocess MCP server used by connection lifecycle tests.""" +# ruff: noqa: E402 + import asyncio import json import os import sys import threading +# mcp.server imports jsonschema, which loads rfc3987_syntax when it is installed +# (dotpromptz pulls it in). That module compiles a Lark grammar at import, which +# is most of this server's startup and stretches every handshake on a busy +# machine. None in sys.modules makes the import fail, and jsonschema skips the +# IRI format checks this server never runs. +sys.modules['rfc3987_syntax'] = None # type: ignore[assignment] + import anyio from mcp.server import Server from mcp.server.stdio import stdio_server @@ -67,6 +76,14 @@ stall_started = asyncio.Event() +def write_marker(path: str, text: str) -> None: + """Write a file the tests poll for in one step, so a reader never finds it created but still empty.""" + staging = f'{path}.partial' + with open(staging, 'w', encoding='utf-8') as marker: + marker.write(text) + os.replace(staging, path) + + @app.list_tools() async def list_tools(req: ListToolsRequest) -> ListToolsResult: # The SDK passes None when it refreshes its own tool cache, and that refresh @@ -88,7 +105,7 @@ async def list_tools(req: ListToolsRequest) -> ListToolsResult: stall_list_marker = os.environ.get('MCP_FAKE_STALL_LIST') if stall_list_marker: - await anyio.Path(stall_list_marker).write_text('stalled', encoding='utf-8') + write_marker(stall_list_marker, 'stalled') await asyncio.Event().wait() if os.environ.get('MCP_FAKE_STUCK_CURSOR'): @@ -109,7 +126,7 @@ async def list_tools(req: ListToolsRequest) -> ListToolsResult: async def call_tool(name: str, arguments: dict[str, object]) -> list[TextContent] | CallToolResult: call_marker = os.environ.get('MCP_FAKE_CALL_MARKER') if call_marker: - await anyio.Path(call_marker).write_text(name, encoding='utf-8') + write_marker(call_marker, name) if name == 'wait': # Must stay under the SDK's PROCESS_TERMINATION_TIMEOUT of 2.0 seconds. await asyncio.sleep(0.25) @@ -185,8 +202,7 @@ def close_stdin_after_handshake(marker: str) -> None: elif message.get('method') == 'notifications/initialized': break os.close(0) - with open(marker, 'w', encoding='utf-8') as closed: - closed.write('closed') + write_marker(marker, 'closed') threading.Event().wait() @@ -197,7 +213,7 @@ async def main() -> None: os.write(1, b'\xff\xfe not utf-8\n') pid_file = os.environ.get('MCP_FAKE_PID_FILE') if pid_file: - await anyio.Path(pid_file).write_text(str(os.getpid()), encoding='utf-8') + write_marker(pid_file, str(os.getpid())) close_stdin_marker = os.environ.get('MCP_FAKE_CLOSE_STDIN') if close_stdin_marker: close_stdin_after_handshake(close_stdin_marker) @@ -210,7 +226,7 @@ async def main() -> None: if eof_marker: # Stands in for state a server flushes once stdin closes. await anyio.sleep(0.3) - await anyio.Path(eof_marker).write_text('flushed', encoding='utf-8') + write_marker(eof_marker, 'flushed') if __name__ == '__main__': diff --git a/packages/genkit-mcp/tests/late_handshake_server.py b/packages/genkit-mcp/tests/late_handshake_server.py new file mode 100644 index 000000000..4d9b6339f --- /dev/null +++ b/packages/genkit-mcp/tests/late_handshake_server.py @@ -0,0 +1,42 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# SPDX-License-Identifier: Apache-2.0 + +"""A server that answers initialize only after the client has given up on it. + +Imports nothing heavy, so its reply lands inside the two seconds the SDK waits +for the child to exit after closing its stdin. +""" + +import json +import os +import sys +import threading + + +def main() -> None: + initialize = None + # Reads until the client closes stdin, which it does once the handshake times out. + for line in sys.stdin.buffer: + message = json.loads(line) + if message.get('method') == 'initialize': + initialize = message + if initialize is not None: + reply = { + 'jsonrpc': '2.0', + 'id': initialize['id'], + 'result': { + 'protocolVersion': initialize['params']['protocolVersion'], + 'capabilities': {'tools': {}}, + 'serverInfo': {'name': 'late-handshake-server', 'version': '0'}, + }, + } + os.write(1, (json.dumps(reply) + '\n').encode()) + # Stays up so the client's stdout reader, not process exit, sees the reply. + threading.Event().wait() + + +if __name__ == '__main__': + main() diff --git a/packages/genkit-mcp/tests/mcp_connection_test.py b/packages/genkit-mcp/tests/mcp_connection_test.py index 571f40c92..b62806fd9 100644 --- a/packages/genkit-mcp/tests/mcp_connection_test.py +++ b/packages/genkit-mcp/tests/mcp_connection_test.py @@ -1115,11 +1115,18 @@ def test_the_request_timeout_defaults_to_sixty_seconds(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_a_request_timeout_fails_that_call_alone(tmp_path: Path) -> None: """A tool which never replies gives up without taking the connection with it.""" - # The timeout also covers the handshake, which a loaded machine can take seconds to finish. - connection = McpConnection('fake', config(tmp_path), request_timeout_millis=8000) + connection = McpConnection('fake', config(tmp_path)) + + # The session-wide timeout also bounds the handshake, which takes seconds on a + # loaded machine, so the stalled call carries its own. The SDK enforces both + # with the same deadline and raises the same 408. + async def stall(session: ClientSession) -> CallToolResult: + return await session.call_tool('stall', {}, read_timeout_seconds=timedelta(milliseconds=100)) + try: + await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) with pytest.raises(_RequestTimeoutError, match="MCP request to 'fake' .* timed out") as timed_out: - await asyncio.wait_for(connection.call_tool('stall', {}), timeout=LIMIT) + await asyncio.wait_for(connection._request(stall), timeout=LIMIT) assert timed_out.value.status == 'DEADLINE_EXCEEDED' assert isinstance(timed_out.value.__cause__, McpError) assert timed_out.value.__cause__.error.code == 408 @@ -1127,8 +1134,9 @@ async def test_a_request_timeout_fails_that_call_alone(tmp_path: Path) -> None: assert str(timed_out.value.__cause__) in str(timed_out.value) assert connection._state is _ConnectionState.OPEN - alive = await asyncio.wait_for(connection.call_tool('echo', {'message': 'alive'}), timeout=LIMIT) - assert text_of(alive) == 'alive' + # Answers only once the timed-out stall is in flight on the server. + alive = await asyncio.wait_for(connection.call_tool('await_stall', {}), timeout=LIMIT) + assert text_of(alive) == 'stalled' finally: await asyncio.wait_for(connection.close(), timeout=LIMIT) @@ -1146,6 +1154,22 @@ async def test_a_handshake_which_never_answers_gives_up(tmp_path: Path) -> None: await asyncio.wait_for(connection.close(), timeout=LIMIT) +@pytest.mark.asyncio +async def test_a_handshake_answered_after_the_timeout_still_reports_the_timeout(tmp_path: Path) -> None: + """The late reply breaks the SDK's closed read stream, and that error must not replace the timeout.""" + server = Path(__file__).with_name('late_handshake_server.py') + connection = McpConnection( + 'fake', McpStdioServerConfig(command=sys.executable, args=[str(server)]), request_timeout_millis=100 + ) + + with pytest.raises(_ConnectionFailedError, match='failed') as failure: + await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) + + assert isinstance(failure.value.__cause__, McpError) + assert failure.value.__cause__.error.code == 408 + await asyncio.wait_for(connection.close(), timeout=LIMIT) + + @pytest.mark.asyncio async def test_no_request_timeout_waits_for_a_slow_server(tmp_path: Path) -> None: connection = McpConnection('fake', config(tmp_path), request_timeout_millis=None)