diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index edad9de81..f4f27f091 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -88,8 +88,12 @@ closed client cannot be restarted. To use that server again, define a new client is `FAILED_PRECONDITION`. A server that cannot start, or whose process dies, fails with status `UNAVAILABLE`, and a request the server does not answer within `request_timeout_millis` fails with `DEADLINE_EXCEEDED`. A connection that died on its own is replaced on next use, so one bad server start is -not permanent. Resolving a tool by its action key, as the Dev UI does to run one, reports neither -status: core finds no action for a closed client or a server that cannot start. +not permanent. A server that fails before it completes a request, including one that never finishes +its handshake, waits one second before it is started again, and each such failure in a row doubles +the wait, up to 30 seconds. Meanwhile its tools fail at once with `UNAVAILABLE` and an error that +says how long is left, and `restart()` skips the wait. Resolving a tool by its action key, as the +Dev UI does to run one, reports neither status: core finds no action for a closed client or a server +that cannot start. Nothing needs closing at exit. Call `close()` when you are done with a server before your process is, not as cleanup on the way out: a process running under `genkit start` outlives your `main()`, @@ -159,4 +163,6 @@ server the host holds, and like `McpClient.close()` it is final: afterwards the status `FAILED_PRECONDITION`, so define a new host to use those servers again. One provider means one listing. A tool call that fails on one server drops the listing for all of -them, so the next `generate` lists every server again. +them, so the next `generate` lists every server again. A server that cannot start is not started +again for those listings until its wait is up, as for a single client, and `reconnect()` skips the +wait. diff --git a/packages/genkit-mcp/src/genkit_mcp/_client.py b/packages/genkit-mcp/src/genkit_mcp/_client.py index f57a9dcc5..bd2a8069e 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_client.py +++ b/packages/genkit-mcp/src/genkit_mcp/_client.py @@ -20,6 +20,7 @@ import asyncio import concurrent.futures +import math import os import threading import time @@ -51,6 +52,12 @@ _LOOP_POLL_SECONDS = 0.1 +# How long a server that failed before completing a request, including one that +# never finished its handshake, waits to be started again. The wait doubles with +# each such failure in a row, up to the maximum. +_RESPAWN_DELAY_SECONDS = 1.0 +_MAX_RESPAWN_DELAY_SECONDS = 30.0 + _registered_clients: weakref.WeakKeyDictionary[Action[Any, Any], weakref.ref[McpClient]] = weakref.WeakKeyDictionary() """The client behind each provider :func:`define_mcp_client` registered.""" @@ -63,6 +70,12 @@ class McpClient: A client built directly is unregistered: no selector reaches it, and its tools come from :meth:`get_active_tools`. + + A server that fails before it completes a request, including one that never + finishes its handshake, is not started again for one second, and each such + failure in a row doubles that wait, up to 30 seconds. Until then its tools + and listings fail at once with ``UNAVAILABLE``, naming how long is left. + :meth:`restart` starts it again without waiting. """ _provider: DynamicActionProvider | None @@ -118,6 +131,9 @@ def __init__( McpConnection, tuple[asyncio.AbstractEventLoop, concurrent.futures.Future[None]] ] = weakref.WeakKeyDictionary() self._close_tasks: set[asyncio.Task[None]] = set() + self._next_respawn_delays: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, float] = ( + weakref.WeakKeyDictionary() + ) self._connections_lock = threading.Lock() @property @@ -240,6 +256,7 @@ async def _disconnect_all(self) -> None: for loop, connection in self._connections.items(): self._start_close(loop, connection) self._connections.clear() + self._next_respawn_delays.clear() closing = list(self._closing.values()) results = await asyncio.gather( *(self._wait_for_close(loop, closed) for loop, closed in closing), @@ -305,6 +322,8 @@ def _drop_closed_loops(self) -> None: """ for loop in [loop for loop in self._connections if loop.is_closed()]: del self._connections[loop] + for loop in [loop for loop in self._next_respawn_delays if loop.is_closed()]: + del self._next_respawn_delays[loop] for connection, (loop, _) in list(self._closing.items()): if loop.is_closed(): del self._closing[connection] @@ -316,7 +335,7 @@ def _refuse_when_closed(self) -> None: raise _ConnectionClosedError(f'MCP client {self._name!r} is closed') def _connection(self) -> McpConnection: - """Return the calling loop's connection, replacing one which has ended.""" + """Return the calling loop's connection, replacing one which has ended once its wait, if any, is up.""" loop = asyncio.get_running_loop() with self._connections_lock: self._refuse_when_closed() @@ -324,12 +343,29 @@ def _connection(self) -> McpConnection: existing = self._connections.get(loop) if existing is not None and not existing.is_terminal: return existing + delay = self._next_respawn_delays.get(loop, _RESPAWN_DELAY_SECONDS) + if existing is not None and existing.failed_at is not None and not existing.answered: + waited = time.monotonic() - existing.failed_at + if waited < delay: + raise self._waiting_error(existing, waited, delay) + delay = min(delay * 2, _MAX_RESPAWN_DELAY_SECONDS) + else: + delay = _RESPAWN_DELAY_SECONDS + self._next_respawn_delays[loop] = delay connection = McpConnection( self._name, self._server, request_timeout_millis=self._request_timeout_millis, host=self._host ) self._connections[loop] = connection return connection + def _waiting_error(self, failed: McpConnection, waited: float, delay: float) -> _ConnectionFailedError: + """Build the error for a request made while a failed server waits to be started again.""" + return _ConnectionFailedError( + f'MCP server {self._name!r} failed {int(waited)}s ago and is not started again for another ' + f'{math.ceil(delay - waited)}s; restart it to try now', + cause=failed.failure, + ) + async def _on_connection(self, operation: Callable[[McpConnection], Awaitable[_T]]) -> _T: """Run an operation on the calling loop's connection, reporting one a restart closed as unavailable.""" try: diff --git a/packages/genkit-mcp/src/genkit_mcp/_connection.py b/packages/genkit-mcp/src/genkit_mcp/_connection.py index 75edba3da..670d54190 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_connection.py +++ b/packages/genkit-mcp/src/genkit_mcp/_connection.py @@ -20,6 +20,7 @@ import contextvars import os import sys +import time from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import timedelta @@ -301,6 +302,8 @@ def __init__( ) self._state = _ConnectionState.NEW self._failure: Exception | None = None + self._failed_at: float | None = None + self._answered = False self._queue: asyncio.Queue[_Request[Any]] = asyncio.Queue() self._ready = asyncio.Event() self._closed = asyncio.Event() @@ -316,6 +319,21 @@ def is_terminal(self) -> bool: """Whether this connection is closed or failed and serves nothing more.""" return self._state in (_ConnectionState.FAILED, _ConnectionState.CLOSED) + @property + def failed_at(self) -> float | None: + """When this connection failed, by ``time.monotonic``, or ``None`` if it has not failed.""" + return self._failed_at + + @property + def answered(self) -> bool: + """Whether an operation after the handshake finished without timing out while the server stayed reachable.""" + return self._answered + + @property + def failure(self) -> Exception | None: + """What ended this connection, once known.""" + return self._failure + async def list_tools(self) -> list[McpTool]: """List every tool the server offers, following pagination cursors. @@ -549,9 +567,13 @@ async def _execute(self, session: ClientSession, request: _Request[Any], serving # Settle now rather than leaving callers waiting the seconds the SDK spends terminating the child. self._settle(error) serving.cancel() - elif not request.result.done(): - request.result.set_exception(self._answered_error(error)) + else: + if not _timed_out(error): + self._answered = True + if not request.result.done(): + request.result.set_exception(self._answered_error(error)) else: + self._answered = True if not request.result.done(): request.result.set_result(value) except BaseException: @@ -560,7 +582,7 @@ async def _execute(self, session: ClientSession, request: _Request[Any], serving self._settle(None) else: # The SDK cancels this child before its task group hands the owner the transport error. - self._state = _ConnectionState.FAILED + self._mark_failed() self._unwinding.append(request) deferred = True raise @@ -588,12 +610,18 @@ def _settle(self, error: Exception | None) -> None: if self._state is _ConnectionState.CLOSED: self._fail_queued(self._closed_error) return - self._state = _ConnectionState.FAILED + self._mark_failed() if self._failure is None and error is not None: _drop_tracebacks(error) self._failure = error self._fail_queued(self._failed_error) + def _mark_failed(self) -> None: + """Enter the failed state, keeping the time it was first entered.""" + self._state = _ConnectionState.FAILED + if self._failed_at is None: + self._failed_at = time.monotonic() + def _fail_queued(self, build_error: Callable[[], BaseException]) -> None: """Release callers whose work was not yet started, or who wait for a failure's cause. diff --git a/packages/genkit-mcp/src/genkit_mcp/_host.py b/packages/genkit-mcp/src/genkit_mcp/_host.py index a8ae689c0..844b02faa 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_host.py +++ b/packages/genkit-mcp/src/genkit_mcp/_host.py @@ -48,6 +48,11 @@ class McpHost: other failure to list a server, such as a protocol violation, an error the server returns, or two of its tools sharing a name, fails the listing. + A server that failed before completing a request, including one that never + finished its handshake, is started again only once the delay + :class:`McpClient` describes is up, not on every listing of the other + servers. :meth:`reconnect` starts it at once. + A host holds no Genkit instance. Registering the provider is :func:`define_mcp_host`. diff --git a/packages/genkit-mcp/tests/fake_server.py b/packages/genkit-mcp/tests/fake_server.py index 24b9de335..58e3d3fda 100644 --- a/packages/genkit-mcp/tests/fake_server.py +++ b/packages/genkit-mcp/tests/fake_server.py @@ -103,6 +103,13 @@ async def list_tools(req: ListToolsRequest) -> ListToolsResult: code = int(os.environ.get('MCP_FAKE_APP_ERROR_CODE', CONNECTION_CLOSED)) raise McpError(ErrorData(code=code, message='application-level failure')) + exit_list_marker = os.environ.get('MCP_FAKE_EXIT_ON_LIST') + if exit_list_marker: + # Answers the handshake, then dies on the first request after it. + async with await anyio.open_file(exit_list_marker, 'a', encoding='utf-8') as exits: + await exits.write('x') + os._exit(1) + stall_list_marker = os.environ.get('MCP_FAKE_STALL_LIST') if stall_list_marker: write_marker(stall_list_marker, 'stalled') diff --git a/packages/genkit-mcp/tests/mcp_client_test.py b/packages/genkit-mcp/tests/mcp_client_test.py index c75c00fad..69bfef2dd 100644 --- a/packages/genkit-mcp/tests/mcp_client_test.py +++ b/packages/genkit-mcp/tests/mcp_client_test.py @@ -23,6 +23,7 @@ from typing import Any, TypeVar import genkit_mcp._client +import genkit_mcp._connection import psutil import pytest from genkit_mcp import McpClient, define_mcp_client @@ -57,6 +58,10 @@ # assert is one the client asked for. LONG_TTL_MILLIS = 600_000 +# Long enough for a healthy test server to start and answer under parallel +# xdist load on CI runners, since the same timeout bounds its handshake. +STALL_TIMEOUT_MILLIS = 8_000 + def server(tmp_path: Path, **env: str) -> dict[str, Any]: """Keyword arguments that launch the test server with the suite's interpreter.""" @@ -71,6 +76,40 @@ def server(tmp_path: Path, **env: str) -> dict[str, Any]: } +def exiting_server(starts: Path) -> dict[str, Any]: + """Keyword arguments for a server that records each start in ``starts`` and exits before the handshake.""" + return { + 'command': sys.executable, + 'args': ['-c', 'import sys; open(sys.argv[1], "a").write("x")', str(starts)], + } + + +def start_count(starts: Path) -> int: + """How many times a server from :func:`exiting_server` has been started.""" + try: + return len(starts.read_text(encoding='utf-8')) + except FileNotFoundError: + return 0 + + +class FakeClock: + """A stand-in for ``time`` whose ``monotonic`` moves only when a test moves it.""" + + def __init__(self) -> None: + self.now = 1000.0 + + def monotonic(self) -> float: + return self.now + + +def fake_clock(monkeypatch: pytest.MonkeyPatch) -> FakeClock: + """Make the client and its connections read the time from a :class:`FakeClock`.""" + clock = FakeClock() + monkeypatch.setattr(genkit_mcp._client, 'time', clock) + monkeypatch.setattr(genkit_mcp._connection, 'time', clock) + return clock + + def server_processes(tmp_path: Path) -> list[psutil.Process]: """Every fake MCP server this test started that is still running.""" pid_file = str(tmp_path / 'server.pid') @@ -687,6 +726,187 @@ async def test_restart_reports_a_server_which_cannot_be_started(tmp_path: Path) await client.close() +@pytest.mark.asyncio +async def test_a_server_that_fails_before_answering_is_not_started_on_every_listing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Until its delay is up, a broken server's listing fails at once with the same status.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 600.0) + starts = tmp_path / 'starts' + client = McpClient('fake', **exiting_server(starts)) + try: + for _ in range(3): + with pytest.raises(GenkitError, match='failed') as raised: + await client.get_active_tools() + assert raised.value.status == 'UNAVAILABLE' + assert raised.value.__cause__ is not None + finally: + await client.close() + + assert start_count(starts) == 1 + + +@pytest.mark.asyncio +async def test_a_server_that_dies_after_the_handshake_but_before_answering_waits_too( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The handshake alone does not count as an answer, so a server that dies on its first request waits.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 600.0) + exits = tmp_path / 'exits' + client = McpClient('fake', **server(tmp_path, MCP_FAKE_EXIT_ON_LIST=str(exits))) + try: + for _ in range(3): + with pytest.raises(GenkitError) as raised: + await client.get_active_tools() + assert raised.value.status == 'UNAVAILABLE' + finally: + await client.close() + + assert start_count(exits) == 1 + + +@pytest.mark.asyncio +async def test_a_server_that_timed_out_and_then_died_waits_too(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A request that timed out got no answer, so it does not spare the server the wait.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 600.0) + client = McpClient( + 'fake', + **server(tmp_path, MCP_FAKE_STALL_LIST=str(tmp_path / 'listing.stalled')), + request_timeout_millis=STALL_TIMEOUT_MILLIS, + ) + try: + with pytest.raises(GenkitError) as timed_out: + await client.get_active_tools() + assert timed_out.value.status == 'DEADLINE_EXCEEDED' + stalled = server_processes(tmp_path) + assert len(stalled) == 1 + stalled[0].kill() + stalled[0].wait(timeout=30) + + for _ in range(2): + with pytest.raises(GenkitError) as raised: + await client.get_active_tools() + assert raised.value.status == 'UNAVAILABLE' + assert server_processes(tmp_path) == [] + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_a_request_during_the_wait_says_how_long_is_left(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The error names the server and the time left, and keeps the failure that started the wait.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 18.0) + clock = fake_clock(monkeypatch) + client = McpClient('booking', **exiting_server(tmp_path / 'starts')) + try: + with pytest.raises(GenkitError) as failed: + await client.get_active_tools() + clock.now += 4.0 + with pytest.raises( + GenkitError, + match="MCP server 'booking' failed 4s ago and is not started again for another 14s; restart it to try now", + ) as waiting: + await client.get_active_tools() + finally: + await client.close() + + assert waiting.value.status == 'UNAVAILABLE' + assert failed.value.__cause__ is not None + assert waiting.value.__cause__ is failed.value.__cause__ + + +@pytest.mark.asyncio +async def test_a_broken_server_waits_twice_as_long_after_each_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Each failure in a row doubles the wait before the next start.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 1.0) + clock = fake_clock(monkeypatch) + starts = tmp_path / 'starts' + client = McpClient('fake', **exiting_server(starts)) + + async def list_after(seconds: float) -> int: + clock.now += seconds + with pytest.raises(GenkitError): + await client.get_active_tools() + return start_count(starts) + + try: + assert await list_after(0) == 1 + assert await list_after(0.5) == 1 + assert await list_after(0.5) == 2 + assert await list_after(1.5) == 2 + assert await list_after(0.5) == 3 + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_the_wait_before_starting_a_broken_server_again_stops_growing_at_its_maximum( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Once the wait reaches its maximum, every later failure waits the same.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 1.0) + monkeypatch.setattr(genkit_mcp._client, '_MAX_RESPAWN_DELAY_SECONDS', 1.0) + clock = fake_clock(monkeypatch) + starts = tmp_path / 'starts' + client = McpClient('fake', **exiting_server(starts)) + try: + for expected in (1, 2, 3): + with pytest.raises(GenkitError): + await client.get_active_tools() + assert start_count(starts) == expected + clock.now += 1.0 + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_a_server_that_dies_after_answering_is_started_again_at_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Only a server that never answered waits: one that worked and then died is replaced on next use.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 600.0) + client = McpClient('fake', **server(tmp_path)) + try: + listed = [tool.name for tool in await client.get_active_tools()] + killed = server_processes(tmp_path) + assert len(killed) == 1 + killed[0].kill() + killed[0].wait(timeout=30) + with pytest.raises(GenkitError) as raised: + await client.get_active_tools() + assert raised.value.status == 'UNAVAILABLE' + + assert [tool.name for tool in await client.get_active_tools()] == listed + replaced = server_processes(tmp_path) + assert len(replaced) == 1 + assert replaced[0].pid != killed[0].pid + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_restart_starts_a_broken_server_without_waiting(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Restart starts the server at once, and a failed restart begins a new wait.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 600.0) + starts = tmp_path / 'starts' + client = McpClient('fake', **exiting_server(starts)) + try: + with pytest.raises(GenkitError): + await client.get_active_tools() + with pytest.raises(GenkitError) as raised: + await client.restart() + assert raised.value.status == 'UNAVAILABLE' + assert start_count(starts) == 2 + + with pytest.raises(GenkitError): + await client.get_active_tools() + assert start_count(starts) == 2 + finally: + await client.close() + + @pytest.mark.asyncio async def test_tool_names_are_known_before_anything_connects(tmp_path: Path) -> None: """Naming a tool costs nothing: the prefix is the caller's own.""" diff --git a/packages/genkit-mcp/tests/mcp_host_test.py b/packages/genkit-mcp/tests/mcp_host_test.py index a39da7036..213a7e26a 100644 --- a/packages/genkit-mcp/tests/mcp_host_test.py +++ b/packages/genkit-mcp/tests/mcp_host_test.py @@ -22,6 +22,7 @@ from typing import Any import anyio +import genkit_mcp._client import psutil import pytest import structlog @@ -215,6 +216,27 @@ async def test_a_server_which_cannot_start_leaves_the_others_listed(tmp_path: Pa assert tool_names(tools) == hosted('alpha') +@pytest.mark.asyncio +async def test_listing_the_other_servers_does_not_start_a_broken_one_each_time( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A broken server waits out its delay however often the healthy ones are listed.""" + monkeypatch.setattr(genkit_mcp._client, '_RESPAWN_DELAY_SECONDS', 600.0) + starts = tmp_path / 'starts' + broken: McpServerEntry = { + 'command': sys.executable, + 'args': ['-c', 'import sys; open(sys.argv[1], "a").write("x")', str(starts)], + } + host = McpHost('hosted', mcp_servers={'broken': broken, **servers(tmp_path, 'alpha')}) + try: + for _ in range(3): + assert tool_names(await asyncio.wait_for(host.get_active_tools(), timeout=LIMIT)) == hosted('alpha') + finally: + await host.close() + + assert starts.read_text(encoding='utf-8') == 'x' + + @pytest.mark.asyncio async def test_a_server_without_the_tools_capability_leaves_the_others_listed(tmp_path: Path) -> None: host = McpHost(