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
13 changes: 9 additions & 4 deletions packages/genkit-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,13 @@ is `FAILED_PRECONDITION`. A server that cannot start, or whose process dies, fai
`UNAVAILABLE`, and a request the server does not answer within `request_timeout_millis` fails with
`DEADLINE_EXCEEDED`. A request that times out, or whose caller is cancelled, is stopped and the
server is sent `notifications/cancelled`. 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.
so one bad server start is 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 on that
event loop, 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. `restart()`, or
`host.reconnect(name)` for a server in a host, 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()`,
Expand Down Expand Up @@ -165,4 +169,5 @@ 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.
41 changes: 39 additions & 2 deletions packages/genkit-mcp/src/genkit_mcp/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import asyncio
import concurrent.futures
import math
import os
import threading
import time
Expand Down Expand Up @@ -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."""

Expand All @@ -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
Expand Down Expand Up @@ -119,6 +132,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
Expand Down Expand Up @@ -182,7 +198,8 @@ async def restart(self) -> None:

The calling loop reconnects and re-lists before this returns, so a server
which still cannot be started says so here rather than on the next
generate. Any other loop reconnects when it next asks for a tool.
generate. Any other loop reconnects when it next asks for a tool. A
server waiting to be started again after a failure is started at once.

A request still running on any loop's connection fails with
``UNAVAILABLE``, and can be retried once this returns.
Expand Down Expand Up @@ -241,6 +258,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),
Expand Down Expand Up @@ -307,6 +325,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]
Expand All @@ -325,20 +345,37 @@ def _refuse_when_closed(self) -> None:
raise _ConnectionClosedError(f'{self._target} 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()
self._drop_closed_loops()
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:
Expand Down
36 changes: 32 additions & 4 deletions packages/genkit-mcp/src/genkit_mcp/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -372,6 +373,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()
Expand All @@ -387,6 +390,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.

Expand Down Expand Up @@ -628,6 +646,7 @@ def caller_gone(result: asyncio.Future[Any]) -> None:
try:
with abandon:
value = await request.operation(session)
self._answered = True
if not request.result.done():
request.result.set_result(value)
except Exception as error:
Expand All @@ -636,15 +655,18 @@ def caller_gone(result: asyncio.Future[Any]) -> None:
# 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))
except BaseException:
# Only an ending connection cancels a child, and the state must say so before any caller is released.
if self._state is _ConnectionState.CLOSED or self._failure is not None:
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
Expand Down Expand Up @@ -673,12 +695,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.

Expand Down
8 changes: 7 additions & 1 deletion packages/genkit-mcp/src/genkit_mcp/_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

A host holds no Genkit instance. Registering the provider is
:func:`define_mcp_host`.

Expand Down Expand Up @@ -221,7 +226,8 @@ async def reconnect(self, server_name: str) -> None:

The calling loop reconnects and re-lists before this returns, so a
server which still cannot be started says so here rather than on the
next generate. The server stays in this host either way.
next generate. The server stays in this host either way. A server
waiting to be started again after a failure is started at once.

Args:
server_name: Name of the server within this host.
Expand Down
7 changes: 7 additions & 0 deletions packages/genkit-mcp/tests/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,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')
Expand Down
Loading
Loading