From 05086fbc827ad7598ecfd5787d0e644efb6fe87b Mon Sep 17 00:00:00 2001 From: Hilary Chukwuma Date: Tue, 10 Nov 2026 12:51:07 +0100 Subject: [PATCH 1/2] fix(py/plugins/mcp): say which server failed and why (#6930) Upstream-Commit: genkit-ai/genkit@d0d2e7af892f873ddc0d7a89093e06d640b95c9f Upstream-PR: https://github.com/genkit-ai/genkit/pull/6930 --- packages/genkit-mcp/src/genkit_mcp/_client.py | 5 +- .../genkit-mcp/src/genkit_mcp/_connection.py | 71 ++++-- packages/genkit-mcp/src/genkit_mcp/_errors.py | 6 +- packages/genkit-mcp/src/genkit_mcp/_host.py | 4 +- packages/genkit-mcp/src/genkit_mcp/_tools.py | 14 +- packages/genkit-mcp/tests/fake_server.py | 9 + packages/genkit-mcp/tests/mcp_client_test.py | 6 +- .../genkit-mcp/tests/mcp_connection_test.py | 210 +++++++++++++----- packages/genkit-mcp/tests/mcp_host_test.py | 25 +++ 9 files changed, 258 insertions(+), 92 deletions(-) diff --git a/packages/genkit-mcp/src/genkit_mcp/_client.py b/packages/genkit-mcp/src/genkit_mcp/_client.py index 3907a5e3a..f57a9dcc5 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_client.py +++ b/packages/genkit-mcp/src/genkit_mcp/_client.py @@ -107,6 +107,7 @@ def __init__( validate_request_timeout(request_timeout_millis) self._provider = None self._name = name + self._host: str | None = None self._server = McpStdioServerConfig(command=command, args=args, env=env, cwd=cwd) self._request_timeout_millis = request_timeout_millis self._closed = False @@ -323,7 +324,9 @@ def _connection(self) -> McpConnection: existing = self._connections.get(loop) if existing is not None and not existing.is_terminal: return existing - connection = McpConnection(self._server, request_timeout_millis=self._request_timeout_millis) + connection = McpConnection( + self._name, self._server, request_timeout_millis=self._request_timeout_millis, host=self._host + ) self._connections[loop] = connection return connection diff --git a/packages/genkit-mcp/src/genkit_mcp/_connection.py b/packages/genkit-mcp/src/genkit_mcp/_connection.py index d32e98fb4..092af01e9 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_connection.py +++ b/packages/genkit-mcp/src/genkit_mcp/_connection.py @@ -75,7 +75,7 @@ _PACKAGE = 'genkit-mcp' -MAX_TOOL_PAGES = 1000 +_MAX_TOOL_PAGES = 1000 """Ceiling on ``tools/list`` pages followed before a server is called broken.""" DEFAULT_REQUEST_TIMEOUT_MILLIS = 60_000 @@ -93,7 +93,7 @@ } """Status for each JSON-RPC error code a server may answer with. Any other code is ``UNKNOWN``.""" -LIVENESS_PROBE_SECONDS = 5.0 +_LIVENESS_PROBE_SECONDS = 5.0 """Bound on the ping that tells a dead transport from a server error reply. A ping which does not return inside this window is read as a slow server, not a @@ -101,7 +101,7 @@ reply. """ -CLOSE_GRACE_SECONDS = 6.0 +_CLOSE_GRACE_SECONDS = 6.0 """How long ``close`` lets the SDK's stdio shutdown run before it kills the server outright. The SDK waits two seconds for the server to exit on stdin EOF, then two more @@ -117,7 +117,7 @@ def _client_info() -> Implementation: return Implementation(name=_PACKAGE, version='0.0.0') -CLIENT_INFO = _client_info() +_CLIENT_INFO = _client_info() """What servers see in the ``clientInfo`` of every initialize request.""" _serving: contextvars.ContextVar['McpConnection | None'] = contextvars.ContextVar('genkit_mcp_serving', default=None) @@ -160,7 +160,7 @@ async def _transport_is_dead(session: ClientSession, error: Exception) -> bool: if not isinstance(error, McpError) or error.error.code != CONNECTION_CLOSED: return False try: - await asyncio.wait_for(session.send_ping(), timeout=LIVENESS_PROBE_SECONDS) + await asyncio.wait_for(session.send_ping(), timeout=_LIVENESS_PROBE_SECONDS) except McpError as probe: return probe.error.code == CONNECTION_CLOSED except asyncio.TimeoutError: @@ -271,21 +271,30 @@ class McpConnection: def __init__( self, + name: str, config: McpStdioServerConfig, request_timeout_millis: int | None = DEFAULT_REQUEST_TIMEOUT_MILLIS, + *, + host: str | None = None, ) -> None: """Prepare a connection. No process starts until the first call. Args: + name: Name of the client, or of the server within a host, that + errors and logs report this connection by. config: How to launch the server. request_timeout_millis: How long one request may take before it fails. Must be positive. ``None`` is the only way to disable the timeout. + host: Name of the host serving this server, if any, which errors + and logs report alongside ``name``. Raises: ValueError: If ``request_timeout_millis`` is zero or negative. """ validate_request_timeout(request_timeout_millis) + self._name = name + self._host = host self._config = config self._request_timeout = ( timedelta(milliseconds=request_timeout_millis) if request_timeout_millis is not None else None @@ -317,7 +326,9 @@ async def list_tools(self) -> list[McpTool]: capability. Raises: - _ProtocolError: If the server's cursors never terminate. + _ProtocolError: If the server's cursors never terminate, or a page + request fails without a JSON-RPC error, such as on a malformed + reply. _RequestTimeoutError: If the server does not answer a page in time. _ServerError: If the server answers a page with a JSON-RPC error. """ @@ -329,7 +340,7 @@ async def list_all(session: ClientSession) -> list[McpTool]: tools: list[McpTool] = [] cursor: str | None = None seen: set[str] = set() - for _ in range(MAX_TOOL_PAGES): + for _ in range(_MAX_TOOL_PAGES): result = await session.list_tools( params=PaginatedRequestParams(cursor=cursor) if cursor is not None else None ) @@ -338,9 +349,9 @@ async def list_all(session: ClientSession) -> list[McpTool]: if not cursor: return tools if cursor in seen: - raise _ProtocolError(f'{self._config.command!r} repeated the tools/list cursor {cursor!r}') + raise _ProtocolError(f'MCP server {self._target} repeated the tools/list cursor {cursor!r}') seen.add(cursor) - raise _ProtocolError(f'{self._config.command!r} served over {MAX_TOOL_PAGES} tools/list pages') + raise _ProtocolError(f'MCP server {self._target} served over {_MAX_TOOL_PAGES} tools/list pages') return await self._request(list_all) @@ -362,6 +373,8 @@ async def call_tool( Raises: _ToolResultError: If the result violates the tool's declared output schema. + _ProtocolError: If the request fails without a JSON-RPC error, such + as on a malformed reply. _RequestTimeoutError: If the server does not answer in time. _ServerError: If the server answers with a JSON-RPC error. """ @@ -377,7 +390,7 @@ async def close(self) -> None: Safe to call when never connected, and safe to call twice. A closed connection serves nothing more. In-flight and queued callers are released at once; the return waits until the server has exited, which - takes up to ``CLOSE_GRACE_SECONDS`` for a server that ignores stdin EOF. + takes up to ``_CLOSE_GRACE_SECONDS`` for a server that ignores stdin EOF. Raises: GenkitError: ``FAILED_PRECONDITION`` if called from inside one of @@ -411,7 +424,7 @@ def _begin_close(self) -> None: self._stop.cancel() if self._shutdown is not None: # Not ``task.cancel()``: that ignores anyio shields, so it can abort the SDK reaping the child. - self._deadline = asyncio.get_running_loop().call_later(CLOSE_GRACE_SECONDS, self._shutdown.cancel) + self._deadline = asyncio.get_running_loop().call_later(_CLOSE_GRACE_SECONDS, self._shutdown.cancel) task.add_done_callback(self._owner_done) def _owner_done(self, _task: asyncio.Task[None]) -> None: @@ -454,7 +467,7 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No Args: shutdown: Cancelled only when the SDK's stdio shutdown overruns - ``CLOSE_GRACE_SECONDS``. + ``_CLOSE_GRACE_SECONDS``. stop: Cancelled by ``close`` to end the session's work. """ try: @@ -473,7 +486,7 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No read_stream, write_stream, read_timeout_seconds=self._request_timeout, - client_info=CLIENT_INFO, + client_info=_CLIENT_INFO, ) as session: # The SDK's stdio shutdown is not shielded, so no scope around it may be cancelled. with stop: @@ -489,8 +502,13 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No raise cause = _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( - 'MCP connection ended', command=self._config.command, error=type(error).__name__, cause=repr(cause) + 'MCP connection ended', + **named, + command=self._config.command, + error=type(error).__name__, + cause=repr(cause), ) self._settle(cause) finally: @@ -587,23 +605,38 @@ def _fail_queued(self, build_error: Callable[[], BaseException]) -> None: if not request.result.done(): request.result.set_exception(build_error()) + @property + def _target(self) -> str: + """Name the server in a message by its name, its host if any, and the command that runs it.""" + if self._host is None: + return f'{self._name!r} ({self._config.command!r})' + return f'{self._name!r} on host {self._host!r} ({self._config.command!r})' + def _closed_error(self) -> _ConnectionClosedError: """Build the error reported once this connection is shut down.""" - return _ConnectionClosedError(f'MCP connection to {self._config.command!r} is closed') + return _ConnectionClosedError(f'MCP connection to {self._target} is closed') - def _answered_error(self, error: Exception) -> Exception: + def _answered_error(self, error: Exception) -> _ClientError: """Build the error reported for one operation that failed while the server stayed reachable.""" if _timed_out(error): return self._timed_out_error(error) if isinstance(error, McpError): return self._server_error(error) + if isinstance(error, _ClientError): + return error + return self._protocol_error(error) + + def _protocol_error(self, failure: Exception) -> _ProtocolError: + """Build the error reported when one request failed without a JSON-RPC error, such as on a malformed reply.""" + error = _ProtocolError(f'MCP request to {self._target} failed with {type(failure).__name__}', cause=failure) + error.__cause__ = failure return error def _server_error(self, reply: McpError) -> _ServerError: """Build the error reported when the server answered one request with a JSON-RPC error.""" code = reply.error.code error = _ServerError( - f'MCP request to {self._config.command!r} failed with error {code}: {reply.error.message}', + f'MCP request to {self._target} failed with error {code}: {reply.error.message}', status=_SERVER_ERROR_STATUS.get(code, 'UNKNOWN'), cause=reply, ) @@ -612,12 +645,12 @@ def _server_error(self, reply: McpError) -> _ServerError: def _timed_out_error(self, timeout: Exception) -> _RequestTimeoutError: """Build the error reported when the server did not answer one request in time.""" - error = _RequestTimeoutError(f'MCP request to {self._config.command!r} timed out') + error = _RequestTimeoutError(f'MCP request to {self._target} timed out', cause=timeout) error.__cause__ = timeout return error def _failed_error(self) -> _ConnectionFailedError: """Build the error reported when startup or the session died.""" - error = _ConnectionFailedError(f'MCP connection to {self._config.command!r} failed') + error = _ConnectionFailedError(f'MCP connection to {self._target} failed', cause=self._failure) error.__cause__ = self._failure return error diff --git a/packages/genkit-mcp/src/genkit_mcp/_errors.py b/packages/genkit-mcp/src/genkit_mcp/_errors.py index 838ce48bf..77f2a4d67 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_errors.py +++ b/packages/genkit-mcp/src/genkit_mcp/_errors.py @@ -83,7 +83,11 @@ class _ServerError(_ClientError): class _ProtocolError(_ClientError): - """The server answered in a way the protocol does not allow. Status ``INTERNAL``.""" + """One request failed without a JSON-RPC error, such as on a malformed reply. Status ``INTERNAL``. + + This includes a server whose ``tools/list`` cursors never terminate. + ``__cause__`` carries what the MCP SDK raised, when there is one. + """ class _ToolResultError(_ClientError): diff --git a/packages/genkit-mcp/src/genkit_mcp/_host.py b/packages/genkit-mcp/src/genkit_mcp/_host.py index c29bc0a08..a8ae689c0 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_host.py +++ b/packages/genkit-mcp/src/genkit_mcp/_host.py @@ -341,7 +341,7 @@ async def _release(self, client: McpClient) -> None: def _build_client(self, server_name: str, config: McpStdioServerConfig) -> McpClient: """Build a client for one server, which serves no provider until it is installed.""" - return McpClient( + client = McpClient( server_name, command=config.command, args=config.args, @@ -349,6 +349,8 @@ def _build_client(self, server_name: str, config: McpStdioServerConfig) -> McpCl cwd=config.cwd, request_timeout_millis=self._request_timeout_millis, ) + client._host = self._name + return client def _stdio_config(self, server_name: str, entry: McpServerEntry) -> McpStdioServerConfig: """Validate one server's name and entry, naming the server when it is not a stdio entry.""" diff --git a/packages/genkit-mcp/src/genkit_mcp/_tools.py b/packages/genkit-mcp/src/genkit_mcp/_tools.py index e0d1c2b56..257de3188 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_tools.py +++ b/packages/genkit-mcp/src/genkit_mcp/_tools.py @@ -39,15 +39,15 @@ logger = get_logger(__name__) -MAX_TOOL_NAME_LENGTH = 64 +_MAX_TOOL_NAME_LENGTH = 64 """Longest function declaration name both Gemini and OpenAI accept.""" -TOOL_NAME_PATTERN = re.compile(r'[A-Za-z_][A-Za-z0-9_-]*') +_TOOL_NAME_PATTERN = re.compile(r'[A-Za-z_][A-Za-z0-9_-]*') """What both Gemini and OpenAI accept in a function declaration name.""" _TOOL_NAME_REJECTED_CHARS = re.compile(r'[^A-Za-z0-9_-]') -SELECTOR_SEPARATORS = (':', '/') +_SELECTOR_SEPARATORS = (':', '/') """Characters a tool selector puts around a provider name, so a name cannot hold them.""" @@ -63,7 +63,7 @@ def validate_provider_name(name: str) -> None: Raises: ValueError: If ``:tool/`` would not parse as a selector. """ - if name and not any(separator in name for separator in SELECTOR_SEPARATORS): + if name and not any(separator in name for separator in _SELECTOR_SEPARATORS): return raise ValueError( f'{name!r} cannot name an MCP provider: its tools are selected as ' @@ -84,7 +84,7 @@ def validate_tool_prefix(prefix: str) -> None: ValueError: If a name built from this prefix would be rejected by the model providers. """ - if TOOL_NAME_PATTERN.fullmatch(prefix): + if _TOOL_NAME_PATTERN.fullmatch(prefix): return raise ValueError( f'{prefix!r} cannot prefix an MCP tool name: a function declaration name must start with a ' @@ -110,7 +110,7 @@ def mcp_tool_name(prefix: str, tool_name: str) -> str: The namespaced name sent to the model. """ name = _TOOL_NAME_REJECTED_CHARS.sub('_', f'{prefix}_{tool_name}') - if not TOOL_NAME_PATTERN.fullmatch(name): + if not _TOOL_NAME_PATTERN.fullmatch(name): name = f'_{name}' return name @@ -214,7 +214,7 @@ def mcp_tool_to_action( tool=tool_name, server_tool=tool.name, ) - if len(tool_name) > MAX_TOOL_NAME_LENGTH: + if len(tool_name) > _MAX_TOOL_NAME_LENGTH: logger.warning( 'MCP tool name is longer than most model providers accept', tool=tool_name, diff --git a/packages/genkit-mcp/tests/fake_server.py b/packages/genkit-mcp/tests/fake_server.py index 83f369b2c..9bbfc1210 100644 --- a/packages/genkit-mcp/tests/fake_server.py +++ b/packages/genkit-mcp/tests/fake_server.py @@ -20,6 +20,7 @@ CONNECTION_CLOSED, CallToolRequest, CallToolResult, + EmptyResult, ErrorData, ListToolsRequest, ListToolsResult, @@ -148,6 +149,14 @@ async def failing_call(req: CallToolRequest) -> ServerResult: app.request_handlers[CallToolRequest] = failing_call +if os.environ.get('MCP_FAKE_MALFORMED_REPLY'): + # An empty result is valid JSON-RPC but lacks the fields tools/list and tools/call require. + async def empty_reply(req: ListToolsRequest | CallToolRequest) -> ServerResult: + return ServerResult(EmptyResult()) + + app.request_handlers[ListToolsRequest] = empty_reply + app.request_handlers[CallToolRequest] = empty_reply + if os.environ.get('MCP_FAKE_NO_TOOLS'): # Without these handlers the server neither advertises tools nor answers tools/list. del app.request_handlers[ListToolsRequest] diff --git a/packages/genkit-mcp/tests/mcp_client_test.py b/packages/genkit-mcp/tests/mcp_client_test.py index dc5127eec..c75c00fad 100644 --- a/packages/genkit-mcp/tests/mcp_client_test.py +++ b/packages/genkit-mcp/tests/mcp_client_test.py @@ -678,9 +678,9 @@ async def test_a_call_cut_off_by_close_fails_as_closed(tmp_path: Path) -> None: async def test_restart_reports_a_server_which_cannot_be_started(tmp_path: Path) -> None: """The caller of restart hears about a broken server, not the next generate.""" ai = Genkit() - client = define_mcp_client(ai, 'fake', command=str(tmp_path / 'no-such-server')) + client = define_mcp_client(ai, 'bookshop', command=str(tmp_path / 'no-such-server')) try: - with pytest.raises(GenkitError, match='failed') as raised: + with pytest.raises(GenkitError, match="MCP connection to 'bookshop' .* failed") as raised: await client.restart() assert raised.value.status == 'UNAVAILABLE' finally: @@ -907,4 +907,4 @@ def test_define_mcp_client_rejects_a_timeout_that_is_not_positive(timeout: int) def test_connection_rejects_a_timeout_that_is_not_positive(timeout: int) -> None: """The connection guards the timeout too, for callers that build one directly.""" with pytest.raises(ValueError, match='request_timeout_millis'): - McpConnection(McpStdioServerConfig(command='npx'), request_timeout_millis=timeout) + McpConnection('fake', McpStdioServerConfig(command='npx'), request_timeout_millis=timeout) diff --git a/packages/genkit-mcp/tests/mcp_connection_test.py b/packages/genkit-mcp/tests/mcp_connection_test.py index d48fc6888..05e2a2cba 100644 --- a/packages/genkit-mcp/tests/mcp_connection_test.py +++ b/packages/genkit-mcp/tests/mcp_connection_test.py @@ -16,6 +16,7 @@ import threading import time import traceback +from collections.abc import Awaitable, Callable from datetime import timedelta from importlib import metadata from pathlib import Path @@ -51,6 +52,8 @@ TextContent, Tool as McpTool, ) +from pydantic import ValidationError +from structlog.testing import capture_logs from genkit import get_logger @@ -206,7 +209,7 @@ async def close_with_queued(connection: McpConnection, *requests: _Request[list[ @pytest.mark.asyncio async def test_connect_list_call_and_close_reaps_server(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) assert [tool.name for tool in await asyncio.wait_for(connection.list_tools(), timeout=LIMIT)] == ALL_TOOLS assert text_of(await asyncio.wait_for(connection.call_tool('echo', {'message': 'hello'}), timeout=LIMIT)) == 'hello' @@ -215,13 +218,13 @@ async def test_connect_list_call_and_close_reaps_server(tmp_path: Path) -> None: await asyncio.wait_for(connection.close(), timeout=LIMIT) await asyncio.wait_for(connection.close(), timeout=LIMIT) assert not is_running(pid) - with pytest.raises(_ConnectionClosedError, match='closed'): + with pytest.raises(_ConnectionClosedError, match="MCP connection to 'fake' .* is closed"): await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) @pytest.mark.asyncio async def test_list_tools_follows_pagination_cursors(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path, MCP_FAKE_PAGE_SIZE='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_PAGE_SIZE='1')) try: assert [tool.name for tool in await asyncio.wait_for(connection.list_tools(), timeout=LIMIT)] == ALL_TOOLS served = await asyncio.wait_for(connection.call_tool('list_requests', {}), timeout=LIMIT) @@ -232,7 +235,7 @@ async def test_list_tools_follows_pagination_cursors(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_list_tools_treats_an_empty_cursor_as_the_last_page(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path, MCP_FAKE_EMPTY_CURSOR='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_EMPTY_CURSOR='1')) try: assert [tool.name for tool in await asyncio.wait_for(connection.list_tools(), timeout=LIMIT)] == ALL_TOOLS served = await asyncio.wait_for(connection.call_tool('list_requests', {}), timeout=LIMIT) @@ -244,7 +247,7 @@ async def test_list_tools_treats_an_empty_cursor_as_the_last_page(tmp_path: Path @pytest.mark.asyncio async def test_a_server_without_the_tools_capability_lists_no_tools(tmp_path: Path) -> None: """Such a server answers tools/list with method not found, so it must not be asked.""" - connection = McpConnection(config(tmp_path, MCP_FAKE_NO_TOOLS='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_NO_TOOLS='1')) try: assert await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) == [] finally: @@ -253,9 +256,9 @@ async def test_a_server_without_the_tools_capability_lists_no_tools(tmp_path: Pa @pytest.mark.asyncio async def test_list_tools_rejects_a_non_advancing_cursor(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path, MCP_FAKE_STUCK_CURSOR='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_STUCK_CURSOR='1')) try: - with pytest.raises(_ProtocolError, match='repeated the tools/list cursor'): + with pytest.raises(_ProtocolError, match="MCP server 'fake' .* repeated the tools/list cursor"): await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) alive = await asyncio.wait_for(connection.call_tool('echo', {'message': 'alive'}), timeout=LIMIT) assert text_of(alive) == 'alive' @@ -265,7 +268,7 @@ async def test_list_tools_rejects_a_non_advancing_cursor(tmp_path: Path) -> None @pytest.mark.asyncio async def test_concurrent_requests_each_receive_their_own_result(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) try: first, tools, second, third = await asyncio.gather( connection.call_tool('echo', {'message': 'one'}), @@ -284,7 +287,7 @@ async def test_concurrent_requests_each_receive_their_own_result(tmp_path: Path) @pytest.mark.asyncio async def test_a_cancelled_caller_is_never_sent_to_the_server(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) try: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) started: list[str] = [] @@ -306,7 +309,7 @@ async def abandoned(session: ClientSession) -> list[McpTool]: @pytest.mark.asyncio async def test_close_interrupts_an_in_flight_call(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path, MCP_FAKE_CALL_MARKER=str(tmp_path / 'call.started'))) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_CALL_MARKER=str(tmp_path / 'call.started'))) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) call = asyncio.create_task(connection.call_tool('wait', {})) assert await server_marker(tmp_path / 'call.started') == 'wait' @@ -319,7 +322,7 @@ async def test_close_interrupts_an_in_flight_call(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_close_lets_the_server_finish_its_shutdown_after_eof(tmp_path: Path) -> None: marker = tmp_path / 'eof.flushed' - connection = McpConnection(config(tmp_path, MCP_FAKE_EOF_MARKER=str(marker))) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_EOF_MARKER=str(marker))) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) await asyncio.wait_for(connection.close(), timeout=LIMIT) @@ -336,11 +339,12 @@ async def test_close_reaps_what_a_wrapped_server_spawned(tmp_path: Path) -> None f'{shlex.quote(sys.executable)} {shlex.quote(str(server))}; wait' ) connection = McpConnection( + 'fake', McpStdioServerConfig( command='/bin/sh', args=['-c', script], env={**os.environ, 'MCP_FAKE_PID_FILE': str(tmp_path / 'server.pid')}, - ) + ), ) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) grandchild = await server_pid(grandchild_file) @@ -356,9 +360,9 @@ async def test_close_reaps_what_a_wrapped_server_spawned(tmp_path: Path) -> None async def test_close_kills_a_server_whose_shutdown_overruns_the_grace( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setattr(_connection, 'CLOSE_GRACE_SECONDS', 0.1) + monkeypatch.setattr(_connection, '_CLOSE_GRACE_SECONDS', 0.1) pid_file = tmp_path / 'stalled.pid' - connection = McpConnection(config(tmp_path, pid_file=pid_file, MCP_FAKE_STALL='1')) + connection = McpConnection('fake', config(tmp_path, pid_file=pid_file, MCP_FAKE_STALL='1')) waiter = asyncio.create_task(connection.list_tools()) pid = await server_pid(pid_file) @@ -373,7 +377,7 @@ async def test_close_kills_a_server_whose_shutdown_overruns_the_grace( @pytest.mark.asyncio async def test_a_close_after_a_cancelled_close_waits_for_the_server_to_exit(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) pid = int((tmp_path / 'server.pid').read_text(encoding='utf-8')) @@ -390,7 +394,7 @@ async def test_a_close_after_a_cancelled_close_waits_for_the_server_to_exit(tmp_ @pytest.mark.asyncio async def test_close_releases_a_request_that_never_reached_the_server(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) blocker = await hold_in_flight(connection) started: list[str] = [] @@ -411,7 +415,7 @@ async def unstarted(session: ClientSession) -> list[McpTool]: @pytest.mark.asyncio async def test_close_propagates_the_callers_own_cancellation(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) pid = int((tmp_path / 'server.pid').read_text(encoding='utf-8')) owner = connection._owner_task @@ -434,7 +438,7 @@ async def test_close_propagates_the_callers_own_cancellation(tmp_path: Path) -> @pytest.mark.asyncio async def test_close_before_the_owner_task_starts_releases_the_waiter(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) waiter = asyncio.create_task(connection.list_tools()) await asyncio.sleep(0) assert connection._state is _ConnectionState.CONNECTING @@ -446,7 +450,7 @@ async def test_close_before_the_owner_task_starts_releases_the_waiter(tmp_path: @pytest.mark.asyncio async def test_close_never_started_twice(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.close(), timeout=LIMIT) await asyncio.wait_for(connection.close(), timeout=LIMIT) @@ -459,7 +463,7 @@ async def test_close_never_started_twice(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_close_during_startup_releases_the_waiter(tmp_path: Path) -> None: pid_file = tmp_path / 'stalled.pid' - connection = McpConnection(config(tmp_path, pid_file=pid_file, MCP_FAKE_STALL='1')) + connection = McpConnection('fake', config(tmp_path, pid_file=pid_file, MCP_FAKE_STALL='1')) waiter = asyncio.create_task(connection.list_tools()) pid = await server_pid(pid_file) @@ -474,7 +478,7 @@ async def test_close_during_startup_releases_the_waiter(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_close_from_inside_a_request_is_rejected(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) try: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) @@ -494,7 +498,7 @@ async def close_from_operation(session: ClientSession) -> None: @pytest.mark.asyncio async def test_server_death_makes_the_connection_terminal(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) owner = connection._owner_task assert owner is not None @@ -518,7 +522,7 @@ async def test_server_death_makes_the_connection_terminal(tmp_path: Path) -> Non async def test_a_caller_cut_off_by_a_broken_stdin_carries_the_transport_error(tmp_path: Path) -> None: """The SDK cancels the in-flight call before its task group reports why.""" marker = tmp_path / 'stdin.closed' - connection = McpConnection(config(tmp_path, MCP_FAKE_CLOSE_STDIN=str(marker))) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_CLOSE_STDIN=str(marker))) try: owner = await start_with_closed_stdin(connection, marker) @@ -537,7 +541,7 @@ async def test_a_caller_cut_off_by_a_broken_stdin_carries_the_transport_error(tm @pytest.mark.asyncio async def test_a_caller_arriving_while_the_owner_unwinds_waits_for_the_transport_error(tmp_path: Path) -> None: marker = tmp_path / 'stdin.closed' - connection = McpConnection(config(tmp_path, MCP_FAKE_CLOSE_STDIN=str(marker))) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_CLOSE_STDIN=str(marker))) try: await start_with_closed_stdin(connection, marker) seen: list[tuple[_ConnectionState, Exception | None]] = [] @@ -570,7 +574,7 @@ async def cut_off(session: ClientSession) -> list[McpTool]: @pytest.mark.asyncio async def test_close_while_the_owner_unwinds_releases_a_cut_off_caller_as_closed(tmp_path: Path) -> None: marker = tmp_path / 'stdin.closed' - connection = McpConnection(config(tmp_path, MCP_FAKE_CLOSE_STDIN=str(marker))) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_CLOSE_STDIN=str(marker))) await start_with_closed_stdin(connection, marker) cut = asyncio.Event() @@ -601,7 +605,7 @@ async def test_a_transport_failure_is_logged_without_the_server_env(tmp_path: Pa assert launch.env is not None # First, so the renderer's cap on how many dict entries it prints cannot hide it. launch.env = {'GENKIT_MCP_TEST_API_KEY': SECRET, **launch.env} - connection = McpConnection(launch) + connection = McpConnection('fake', launch) output = io.StringIO() saved = structlog.get_config() structlog.configure(logger_factory=structlog.PrintLoggerFactory(output)) @@ -616,6 +620,7 @@ async def test_a_transport_failure_is_logged_without_the_server_env(tmp_path: Pa logged = output.getvalue() assert 'MCP connection ended' in logged + assert 'client=fake' in logged assert 'BrokenResourceError' in logged assert SECRET not in logged assert isinstance(failure.value.__cause__, anyio.BrokenResourceError) @@ -626,7 +631,9 @@ async def test_a_transport_failure_is_logged_without_the_server_env(tmp_path: Pa async def test_a_startup_failure_keeps_the_server_env_out_of_its_traceback(tmp_path: Path) -> None: """Core renders a failed listing with logger.exception, which prints the locals of every frame in the chain.""" missing = tmp_path / 'no-such-mcp-server' - connection = McpConnection(McpStdioServerConfig(command=str(missing), env={'GENKIT_MCP_TEST_API_KEY': SECRET})) + connection = McpConnection( + 'fake', McpStdioServerConfig(command=str(missing), env={'GENKIT_MCP_TEST_API_KEY': SECRET}) + ) try: with pytest.raises(_ConnectionFailedError, match='failed') as failure: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) @@ -641,7 +648,7 @@ async def test_a_startup_failure_keeps_the_server_env_out_of_its_traceback(tmp_p @pytest.mark.asyncio @pytest.mark.parametrize('raises', [False, True]) async def test_a_caller_cancelled_after_dispatch_leaves_the_connection_open(tmp_path: Path, raises: bool) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) try: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) running, release, returned = asyncio.Event(), asyncio.Event(), asyncio.Event() @@ -673,7 +680,9 @@ async def abandoned(session: ClientSession) -> list[McpTool]: @pytest.mark.asyncio async def test_a_server_error_reply_outside_the_server_error_range_reports_its_status(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path, MCP_FAKE_APP_ERROR='1', MCP_FAKE_APP_ERROR_CODE=str(INVALID_PARAMS))) + connection = McpConnection( + 'fake', config(tmp_path, MCP_FAKE_APP_ERROR='1', MCP_FAKE_APP_ERROR_CODE=str(INVALID_PARAMS)) + ) try: with pytest.raises(_ServerError, match=f'failed with error {INVALID_PARAMS}') as answered: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) @@ -685,10 +694,12 @@ async def test_a_server_error_reply_outside_the_server_error_range_reports_its_s @pytest.mark.asyncio async def test_a_server_error_code_does_not_poison_a_live_connection(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path, MCP_FAKE_APP_ERROR='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_APP_ERROR='1')) try: pid_file = tmp_path / 'server.pid' - with pytest.raises(_ServerError, match='failed with error -32000: application-level failure') as answered: + with pytest.raises( + _ServerError, match="MCP request to 'fake' .* failed with error -32000: application-level failure" + ) as answered: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) assert answered.value.status == 'UNKNOWN' assert isinstance(answered.value.__cause__, McpError) @@ -719,7 +730,7 @@ async def test_a_server_error_code_does_not_poison_a_live_connection(tmp_path: P async def test_a_server_error_reply_reports_the_status_for_its_code(tmp_path: Path, code: int, status: str) -> None: reply = McpError(ErrorData(code=code, message='refused')) - error = McpConnection(config(tmp_path))._answered_error(reply) + error = McpConnection('fake', config(tmp_path))._answered_error(reply) assert isinstance(error, _ServerError) assert error.status == status @@ -727,12 +738,63 @@ async def test_a_server_error_reply_reports_the_status_for_its_code(tmp_path: Pa assert f'failed with error {code}: refused' in str(error) +@pytest.mark.asyncio +async def test_an_error_this_package_raised_is_reported_unchanged(tmp_path: Path) -> None: + raised = _ToolResultError('bad output') + + assert McpConnection('fake', config(tmp_path))._answered_error(raised) is raised + + +@pytest.mark.asyncio +async def test_any_other_failure_is_reported_as_a_protocol_error(tmp_path: Path) -> None: + failure = RuntimeError('unexpected') + + error = McpConnection('fake', config(tmp_path))._answered_error(failure) + + assert isinstance(error, _ProtocolError) + assert error.status == 'INTERNAL' + assert error.cause is failure + assert error.__cause__ is failure + assert "MCP request to 'fake' (" in str(error) + assert 'failed with RuntimeError' in str(error) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'send', + [ + pytest.param(lambda connection: connection.list_tools(), id='list_tools'), + pytest.param(lambda connection: connection.call_tool('echo', {}), id='call_tool'), + ], +) +async def test_a_malformed_reply_is_a_protocol_error_without_the_server_env( + tmp_path: Path, send: Callable[[McpConnection], Awaitable[object]] +) -> None: + launch = config(tmp_path, MCP_FAKE_MALFORMED_REPLY='1') + assert launch.env is not None + # First, so the renderer's cap on how many dict entries it prints cannot hide it. + launch.env = {'GENKIT_MCP_TEST_API_KEY': SECRET, **launch.env} + connection = McpConnection('fake', launch) + try: + with pytest.raises(_ProtocolError, match="MCP request to 'fake' .* failed with ValidationError") as answered: + await asyncio.wait_for(send(connection), timeout=LIMIT) + assert answered.value.status == 'INTERNAL' + assert isinstance(answered.value.__cause__, ValidationError) + assert answered.value.cause is answered.value.__cause__ + assert connection._state is _ConnectionState.OPEN + assert is_running(await server_pid(tmp_path / 'server.pid')) + finally: + await asyncio.wait_for(connection.close(), timeout=LIMIT) + + assert SECRET not in rendered_for_logs(answered.value) + + @pytest.mark.asyncio async def test_list_tools_rejects_endlessly_advancing_cursors(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(_connection, 'MAX_TOOL_PAGES', 3) - connection = McpConnection(config(tmp_path, MCP_FAKE_ENDLESS_CURSOR='1')) + monkeypatch.setattr(_connection, '_MAX_TOOL_PAGES', 3) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_ENDLESS_CURSOR='1')) try: - with pytest.raises(_ProtocolError, match='served over 3 tools/list pages'): + with pytest.raises(_ProtocolError, match="MCP server 'fake' .* served over 3 tools/list pages"): await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) # The server counts what it served, so an off-by-N cap cannot hide # behind a message built from the same constant. @@ -746,7 +808,7 @@ async def test_list_tools_rejects_endlessly_advancing_cursors(tmp_path: Path, mo @pytest.mark.asyncio async def test_a_concurrent_close_waits_for_the_child_to_be_reaped(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) pid = int((tmp_path / 'server.pid').read_text(encoding='utf-8')) call = asyncio.create_task(connection.call_tool('wait', {})) @@ -839,7 +901,7 @@ async def test_an_ambiguous_code_is_decided_by_the_probe(outcome: Exception | No @pytest.mark.asyncio async def test_a_probe_that_times_out_reads_the_server_as_alive(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(_connection, 'LIVENESS_PROBE_SECONDS', 0.01) + monkeypatch.setattr(_connection, '_LIVENESS_PROBE_SECONDS', 0.01) session = _ProbeSession(delay=LIMIT) assert await _connection._transport_is_dead(cast(ClientSession, session), closed_mcp_error()) is False @@ -855,7 +917,7 @@ async def hang(_self: ClientSession) -> None: await asyncio.sleep(LIMIT * 2) monkeypatch.setattr(ClientSession, 'send_ping', hang) - connection = McpConnection(config(tmp_path, MCP_FAKE_APP_ERROR='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_APP_ERROR='1')) waiter = asyncio.create_task(connection.list_tools()) await asyncio.wait_for(probing.wait(), timeout=LIMIT) @@ -866,7 +928,7 @@ async def hang(_self: ClientSession) -> None: @pytest.mark.asyncio async def test_each_released_caller_gets_its_own_error(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) blocker = await hold_in_flight(connection) @@ -892,9 +954,11 @@ async def unreachable(session: ClientSession) -> list[McpTool]: @pytest.mark.asyncio async def test_a_tool_call_error_code_does_not_poison_a_live_connection(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path, MCP_FAKE_APP_ERROR_CALL='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_APP_ERROR_CALL='1')) try: - with pytest.raises(_ServerError, match='failed with error -32000: application-level failure') as answered: + with pytest.raises( + _ServerError, match="MCP request to 'fake' .* failed with error -32000: application-level failure" + ) as answered: await asyncio.wait_for(connection.call_tool('echo', {}), timeout=LIMIT) assert answered.value.status == 'UNKNOWN' assert isinstance(answered.value.__cause__, McpError) @@ -906,7 +970,7 @@ async def test_a_tool_call_error_code_does_not_poison_a_live_connection(tmp_path @pytest.mark.asyncio async def test_settle_makes_a_silent_owner_exit_terminal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) async def serve_nothing(session: ClientSession) -> None: return None @@ -951,7 +1015,7 @@ async def test_request_rejects_a_state_change_after_start( error: type[Exception], message: str, ) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) started = connection._start @@ -970,23 +1034,47 @@ async def start_then_terminate() -> None: @pytest.mark.asyncio -async def test_startup_failure_is_terminal_and_names_the_command(tmp_path: Path) -> None: +@pytest.mark.parametrize( + ('host', 'named'), + [(None, {'client': 'catalog'}), ('hosted', {'server': 'catalog', 'host': 'hosted'})], +) +async def test_an_ended_connection_is_logged_under_its_client_or_its_host_and_server( + tmp_path: Path, host: str | None, named: dict[str, str] +) -> None: + """The keys match the client's and the host's own logs.""" + connection = McpConnection('catalog', McpStdioServerConfig(command=str(tmp_path / 'no-such-mcp-server')), host=host) + try: + with capture_logs() as logs, pytest.raises(_ConnectionFailedError): + await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) + finally: + await asyncio.wait_for(connection.close(), timeout=LIMIT) + + [ended] = [log for log in logs if log['event'] == 'MCP connection ended'] + assert {key: ended[key] for key in ('client', 'server', 'host') if key in ended} == named + + +@pytest.mark.asyncio +async def test_startup_failure_is_terminal_and_names_the_server_and_why(tmp_path: Path) -> None: missing = tmp_path / 'no-such-mcp-server' - connection = McpConnection(McpStdioServerConfig(command=str(missing))) + connection = McpConnection('catalog', McpStdioServerConfig(command=str(missing))) unhandled: list[dict[str, object]] = [] asyncio.get_running_loop().set_exception_handler(lambda _loop, context: unhandled.append(context)) with pytest.raises(_ConnectionFailedError, match='failed') as failure: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) - assert str(missing) in str(failure.value) - assert isinstance(failure.value.__cause__, OSError) + assert f"MCP connection to 'catalog' ({str(missing)!r}) failed" in str(failure.value) + cause = failure.value.__cause__ + assert isinstance(cause, OSError) + assert failure.value.cause is cause + assert str(cause) in str(failure.value) + assert repr(cause) in failure.value.to_serializable().message assert connection._state is _ConnectionState.FAILED with pytest.raises(_ConnectionFailedError, match='failed'): await asyncio.wait_for(connection.call_tool('echo', {}), timeout=LIMIT) await asyncio.wait_for(connection.close(), timeout=LIMIT) - del connection, failure + del connection, failure, cause gc.collect() assert unhandled == [] @@ -997,7 +1085,7 @@ def test_a_connection_belongs_to_the_loop_that_opened_it(tmp_path: Path) -> None async def use_connection(index: int) -> None: pid_file = tmp_path / f'server-{index}.pid' - connection = McpConnection(config(tmp_path, pid_file=pid_file)) + connection = McpConnection('fake', config(tmp_path, pid_file=pid_file)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) pids.append(await server_pid(pid_file)) await asyncio.wait_for(connection.close(), timeout=LIMIT) @@ -1020,20 +1108,22 @@ def threaded() -> None: def test_the_request_timeout_defaults_to_sixty_seconds(tmp_path: Path) -> None: - assert McpConnection(config(tmp_path))._request_timeout == timedelta(seconds=60) + assert McpConnection('fake', config(tmp_path))._request_timeout == timedelta(seconds=60) @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(config(tmp_path), request_timeout_millis=8000) + connection = McpConnection('fake', config(tmp_path), request_timeout_millis=8000) try: - with pytest.raises(_RequestTimeoutError, match='timed out') as timed_out: + with pytest.raises(_RequestTimeoutError, match="MCP request to 'fake' .* timed out") as timed_out: await asyncio.wait_for(connection.call_tool('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 timed_out.value.cause 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) @@ -1045,7 +1135,7 @@ async def test_a_request_timeout_fails_that_call_alone(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_a_handshake_which_never_answers_gives_up(tmp_path: Path) -> None: """Without the timeout a server that never initializes parks every caller forever.""" - connection = McpConnection(config(tmp_path, MCP_FAKE_STALL='1'), request_timeout_millis=100) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_STALL='1'), request_timeout_millis=100) with pytest.raises(_ConnectionFailedError, match='failed') as failure: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) @@ -1057,7 +1147,7 @@ async def test_a_handshake_which_never_answers_gives_up(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_no_request_timeout_waits_for_a_slow_server(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path), request_timeout_millis=None) + connection = McpConnection('fake', config(tmp_path), request_timeout_millis=None) try: assert text_of(await asyncio.wait_for(connection.call_tool('wait', {}), timeout=LIMIT)) == 'wait' finally: @@ -1067,7 +1157,7 @@ async def test_no_request_timeout_waits_for_a_slow_server(tmp_path: Path) -> Non @pytest.mark.asyncio async def test_an_owner_cancelled_from_outside_never_hands_on_its_cancellation(tmp_path: Path) -> None: """A caller that was not cancelled must not be told that it was.""" - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) owner = connection._owner_task assert owner is not None @@ -1087,7 +1177,7 @@ async def test_an_owner_cancelled_from_outside_never_hands_on_its_cancellation(t @pytest.mark.asyncio async def test_undecodable_output_does_not_kill_the_transport(tmp_path: Path) -> None: """One bad byte on stdout costs that message, not the connection.""" - connection = McpConnection(config(tmp_path, MCP_FAKE_BAD_UTF8='1')) + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_BAD_UTF8='1')) try: assert [tool.name for tool in await asyncio.wait_for(connection.list_tools(), timeout=LIMIT)] == ALL_TOOLS finally: @@ -1096,7 +1186,7 @@ async def test_undecodable_output_does_not_kill_the_transport(tmp_path: Path) -> @pytest.mark.asyncio async def test_the_server_is_told_which_client_connected(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) try: seen = text_of(await asyncio.wait_for(connection.call_tool('who_called', {}), timeout=LIMIT)) finally: @@ -1108,7 +1198,7 @@ async def test_the_server_is_told_which_client_connected(tmp_path: Path) -> None @pytest.mark.asyncio async def test_two_calls_on_one_connection_overlap_in_time(tmp_path: Path) -> None: """The server answers rendezvous only once both calls have reached it.""" - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) try: first, second = await asyncio.wait_for( asyncio.gather(connection.call_tool('rendezvous', {}), connection.call_tool('rendezvous', {})), @@ -1123,7 +1213,7 @@ async def test_two_calls_on_one_connection_overlap_in_time(tmp_path: Path) -> No @pytest.mark.asyncio async def test_list_tools_completes_while_a_call_is_stalled(tmp_path: Path) -> None: """The server answers await_stall only once the stall call has reached it.""" - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) stalled = asyncio.create_task(connection.call_tool('stall', {})) try: assert text_of(await asyncio.wait_for(connection.call_tool('await_stall', {}), timeout=LIMIT)) == 'stalled' @@ -1137,7 +1227,7 @@ async def test_list_tools_completes_while_a_call_is_stalled(tmp_path: Path) -> N @pytest.mark.asyncio async def test_an_output_schema_violation_is_a_tool_result_error(tmp_path: Path) -> None: - connection = McpConnection(config(tmp_path)) + connection = McpConnection('fake', config(tmp_path)) try: # The SDK validates against the schemas it has listed, and its own refresh reads one tools/list page. await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) diff --git a/packages/genkit-mcp/tests/mcp_host_test.py b/packages/genkit-mcp/tests/mcp_host_test.py index 517b4703e..a39da7036 100644 --- a/packages/genkit-mcp/tests/mcp_host_test.py +++ b/packages/genkit-mcp/tests/mcp_host_test.py @@ -627,6 +627,31 @@ async def test_reconnect_reports_a_server_which_cannot_be_started(tmp_path: Path await host.close() +@pytest.mark.asyncio +async def test_servers_sharing_a_command_are_told_apart_by_name(tmp_path: Path) -> None: + """Each server's error names that server, not just the command both run.""" + host = McpHost('hosted', mcp_servers={'first': missing_server(tmp_path), 'second': missing_server(tmp_path)}) + try: + for name in ('first', 'second'): + with pytest.raises(GenkitError, match=f"MCP connection to '{name}' .* failed"): + await host.reconnect(name) + finally: + await host.close() + + +@pytest.mark.asyncio +async def test_servers_sharing_a_name_and_command_are_told_apart_by_host(tmp_path: Path) -> None: + """Each host's error names that host, when two hosts run a server of the same name the same way.""" + hosts = [McpHost(name, mcp_servers={'repo': missing_server(tmp_path)}) for name in ('alpha', 'beta')] + try: + for host in hosts: + with pytest.raises(GenkitError, match=f"MCP connection to 'repo' on host '{host.name}' .* failed"): + await host.reconnect('repo') + finally: + for host in hosts: + await host.close() + + @pytest.mark.asyncio async def test_close_is_final(tmp_path: Path) -> None: """A closed host stops every server and refuses every operation, as a client does.""" From f15201854e7636106d36773227f8223eb8733ae6 Mon Sep 17 00:00:00 2001 From: Hilary Chukwuma Date: Tue, 10 Nov 2026 13:55:03 +0100 Subject: [PATCH 2/2] fix(py/plugins/mcp): stop tests using the removed GenkitError.cause (#7153) Upstream-Commit: genkit-ai/genkit@494584f137998de377b26aad83d58c3df0d0c6e7 Upstream-PR: https://github.com/genkit-ai/genkit/pull/7153 --- packages/genkit-mcp/tests/mcp_connection_test.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/genkit-mcp/tests/mcp_connection_test.py b/packages/genkit-mcp/tests/mcp_connection_test.py index 05e2a2cba..571f40c92 100644 --- a/packages/genkit-mcp/tests/mcp_connection_test.py +++ b/packages/genkit-mcp/tests/mcp_connection_test.py @@ -56,6 +56,7 @@ from structlog.testing import capture_logs from genkit import get_logger +from genkit._core._error import attached_cause, get_reflection_json # noqa: TID251 ALL_TOOLS = [ 'echo', @@ -753,7 +754,7 @@ async def test_any_other_failure_is_reported_as_a_protocol_error(tmp_path: Path) assert isinstance(error, _ProtocolError) assert error.status == 'INTERNAL' - assert error.cause is failure + assert attached_cause(error) is failure assert error.__cause__ is failure assert "MCP request to 'fake' (" in str(error) assert 'failed with RuntimeError' in str(error) @@ -780,7 +781,7 @@ async def test_a_malformed_reply_is_a_protocol_error_without_the_server_env( await asyncio.wait_for(send(connection), timeout=LIMIT) assert answered.value.status == 'INTERNAL' assert isinstance(answered.value.__cause__, ValidationError) - assert answered.value.cause is answered.value.__cause__ + assert attached_cause(answered.value) is answered.value.__cause__ assert connection._state is _ConnectionState.OPEN assert is_running(await server_pid(tmp_path / 'server.pid')) finally: @@ -1065,9 +1066,9 @@ async def test_startup_failure_is_terminal_and_names_the_server_and_why(tmp_path assert f"MCP connection to 'catalog' ({str(missing)!r}) failed" in str(failure.value) cause = failure.value.__cause__ assert isinstance(cause, OSError) - assert failure.value.cause is cause + assert attached_cause(failure.value) is cause assert str(cause) in str(failure.value) - assert repr(cause) in failure.value.to_serializable().message + assert repr(cause) in get_reflection_json(failure.value).message assert connection._state is _ConnectionState.FAILED with pytest.raises(_ConnectionFailedError, match='failed'): @@ -1122,7 +1123,7 @@ async def test_a_request_timeout_fails_that_call_alone(tmp_path: Path) -> None: assert timed_out.value.status == 'DEADLINE_EXCEEDED' assert isinstance(timed_out.value.__cause__, McpError) assert timed_out.value.__cause__.error.code == 408 - assert timed_out.value.cause is timed_out.value.__cause__ + 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