Skip to content
Merged
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
11 changes: 9 additions & 2 deletions packages/genkit-mcp/src/genkit_mcp/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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(
Expand Down
28 changes: 22 additions & 6 deletions packages/genkit-mcp/tests/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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'):
Expand All @@ -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)
Expand Down Expand Up @@ -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()


Expand All @@ -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)
Expand All @@ -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__':
Expand Down
42 changes: 42 additions & 0 deletions packages/genkit-mcp/tests/late_handshake_server.py
Original file line number Diff line number Diff line change
@@ -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()
34 changes: 29 additions & 5 deletions packages/genkit-mcp/tests/mcp_connection_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1115,20 +1115,28 @@ 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
assert attached_cause(timed_out.value) is timed_out.value.__cause__
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)

Expand All @@ -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)
Expand Down
Loading