diff --git a/packages/genkit-mcp/src/genkit_mcp/_client.py b/packages/genkit-mcp/src/genkit_mcp/_client.py index 1808fd84..187edf9e 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_client.py +++ b/packages/genkit-mcp/src/genkit_mcp/_client.py @@ -289,9 +289,10 @@ async def _wait_for_close(self, loop: asyncio.AbstractEventLoop, closed: concurr if not loop.is_running(): return if time.monotonic() >= deadline: + named = {'client': self._name} if self._host is None else {'server': self._name, 'host': self._host} logger.warning( 'MCP connection did not close on its event loop in time', - client=self._name, + **named, timeout_seconds=_CROSS_LOOP_CLOSE_TIMEOUT_SECONDS, ) return @@ -311,10 +312,17 @@ def _drop_closed_loops(self) -> None: del self._closing[connection] self._close_tasks -= {task for task in self._close_tasks if task.get_loop().is_closed()} + @property + def _target(self) -> str: + """Name this standalone client or this hosted server in a message.""" + if self._host is None: + return f'MCP client {self._name!r}' + return f'MCP server {self._name!r} on host {self._host!r}' + def _refuse_when_closed(self) -> None: """Raise if this client has been closed. Call under the connections lock.""" if self._closed: - raise _ConnectionClosedError(f'MCP client {self._name!r} is closed') + raise _ConnectionClosedError(f'{self._target} is closed') def _connection(self) -> McpConnection: """Return the calling loop's connection, replacing one which has ended.""" @@ -338,7 +346,7 @@ async def _on_connection(self, operation: Callable[[McpConnection], Awaitable[_T except _ConnectionClosedError: if self._closed: raise - raise _ConnectionFailedError(f'MCP client {self._name!r} restarted during the request; retry it') from None + raise _ConnectionFailedError(f'{self._target} restarted during the request; retry it') from None async def _call_tool( self, diff --git a/packages/genkit-mcp/tests/mcp_client_test.py b/packages/genkit-mcp/tests/mcp_client_test.py index c75c00fa..1b0e2ae5 100644 --- a/packages/genkit-mcp/tests/mcp_client_test.py +++ b/packages/genkit-mcp/tests/mcp_client_test.py @@ -12,6 +12,7 @@ """ import asyncio +import concurrent.futures import gc import os import sys @@ -28,6 +29,7 @@ from genkit_mcp import McpClient, define_mcp_client from genkit_mcp._config import McpStdioServerConfig from genkit_mcp._connection import McpConnection, _serving +from structlog.testing import capture_logs from genkit import FinishReason, Genkit, GenkitError, Message, ModelResponse, Part, Role @@ -528,6 +530,29 @@ async def test_close_stops_waiting_on_a_loop_too_busy_to_close_its_connection( background.stop() +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('host', 'named'), + [(None, {'client': 'catalog'}), ('hosted', {'server': 'catalog', 'host': 'hosted'})], +) +async def test_a_close_timeout_is_logged_under_its_client_or_its_host_and_server( + monkeypatch: pytest.MonkeyPatch, + host: str | None, + named: dict[str, str], +) -> None: + """The keys match the client's and the host's other connection logs.""" + monkeypatch.setattr(genkit_mcp._client, '_CROSS_LOOP_CLOSE_TIMEOUT_SECONDS', 0) + client = McpClient('catalog', command='unused') + client._host = host + closed: concurrent.futures.Future[None] = concurrent.futures.Future() + + with capture_logs() as logs: + await client._wait_for_close(asyncio.get_running_loop(), closed) + + [timed_out] = [log for log in logs if log['event'] == 'MCP connection did not close on its event loop in time'] + assert {key: timed_out[key] for key in ('client', 'server', 'host') if key in timed_out} == named + + @pytest.mark.asyncio async def test_a_closed_client_starts_no_server_on_a_new_loop(tmp_path: Path) -> None: """Close is final: a loop which never had a connection does not get one.""" diff --git a/packages/genkit-mcp/tests/mcp_host_test.py b/packages/genkit-mcp/tests/mcp_host_test.py index a39da703..7aef0ded 100644 --- a/packages/genkit-mcp/tests/mcp_host_test.py +++ b/packages/genkit-mcp/tests/mcp_host_test.py @@ -614,6 +614,24 @@ async def test_reconnect_replaces_one_server_process(tmp_path: Path) -> None: await host.close() +@pytest.mark.asyncio +async def test_a_hosted_call_cut_off_by_reconnect_names_its_server_and_host(tmp_path: Path) -> None: + """A hosted server's interrupted call is distinguishable from the same server on another host.""" + host = McpHost('hosted', mcp_servers=servers(tmp_path, 'repo')) + try: + tools = {tool.name: tool for tool in await host.get_active_tools()} + waiting = asyncio.create_task(tools['repo_stall']({})) + await tools['repo_await_stall']({}) + + await host.reconnect('repo') + + with pytest.raises(GenkitError, match="MCP server 'repo' on host 'hosted' restarted") as raised: + await asyncio.wait_for(waiting, timeout=LIMIT) + assert raised.value.status == 'UNAVAILABLE' + finally: + await host.close() + + @pytest.mark.asyncio async def test_reconnect_reports_a_server_which_cannot_be_started(tmp_path: Path) -> None: """The caller of reconnect hears about a broken server, and keeps holding it.""" @@ -777,7 +795,7 @@ async def test_a_disconnected_server_cannot_drop_the_listing(tmp_path: Path) -> await expand_wildcard_tools(ai._registry, ['hosted:tool/*']) assert (await counter.run({})).response.output == '2' - with pytest.raises(GenkitError) as raised: + with pytest.raises(GenkitError, match="MCP server 'beta' on host 'hosted' is closed") as raised: await beta_echo.run({'message': 'late'}) assert raised.value.status == 'FAILED_PRECONDITION'