From aa9a9e300016f598298f9c2a9840ef543cdda0c6 Mon Sep 17 00:00:00 2001 From: Hilary Date: Wed, 11 Nov 2026 15:43:13 +0100 Subject: [PATCH] fix(mcp): send notifications/cancelled when a call is cancelled or times out Upstream-PR: https://github.com/genkit-ai/genkit/pull/6958 --- packages/genkit-mcp/README.md | 8 +- packages/genkit-mcp/src/genkit_mcp/_client.py | 6 +- .../genkit-mcp/src/genkit_mcp/_connection.py | 99 +++++++++++++- packages/genkit-mcp/src/genkit_mcp/_host.py | 8 +- packages/genkit-mcp/tests/fake_server.py | 41 +++++- .../genkit-mcp/tests/mcp_connection_test.py | 127 ++++++++++++++++-- 6 files changed, 262 insertions(+), 27 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index edad9de81..38bef9858 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -87,9 +87,11 @@ closed client cannot be restarted. To use that server again, define a new client `generate` with one of its tools, and `get_active_tools()`, fail with a `GenkitError` whose status 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. +`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. 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()`, diff --git a/packages/genkit-mcp/src/genkit_mcp/_client.py b/packages/genkit-mcp/src/genkit_mcp/_client.py index f57a9dcc5..1808fd84e 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_client.py +++ b/packages/genkit-mcp/src/genkit_mcp/_client.py @@ -95,7 +95,8 @@ def __init__( cwd: Working directory for the server process. request_timeout_millis: How long one MCP request may take before it fails. Must be positive. ``None`` is the only way to disable the - timeout. + timeout. A request that times out, or whose caller is cancelled, + is stopped and the server is sent ``notifications/cancelled``. Raises: ValueError: If ``name`` cannot appear in a tool selector or a @@ -401,7 +402,8 @@ def define_mcp_client( cache, so every lookup lists the tools again. request_timeout_millis: How long one MCP request may take before it fails. Must be positive. ``None`` is the only way to disable the - timeout. + timeout. A request that times out, or whose caller is cancelled, + is stopped and the server is sent ``notifications/cancelled``. Returns: A handle for listing tools, restarting and disconnecting. diff --git a/packages/genkit-mcp/src/genkit_mcp/_connection.py b/packages/genkit-mcp/src/genkit_mcp/_connection.py index 75edba3da..91208474e 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_connection.py +++ b/packages/genkit-mcp/src/genkit_mcp/_connection.py @@ -31,6 +31,8 @@ from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp.shared.exceptions import McpError +from mcp.shared.message import MessageMetadata +from mcp.shared.session import ProgressFnT from mcp.types import ( CONNECTION_CLOSED, INTERNAL_ERROR, @@ -39,10 +41,16 @@ METHOD_NOT_FOUND, PARSE_ERROR, CallToolResult, + CancelledNotification, + CancelledNotificationParams, + ClientNotification, + ClientRequest, Implementation, PaginatedRequestParams, + RequestId, Tool as McpTool, ) +from pydantic import BaseModel from genkit import get_logger from genkit.plugin_api import StatusName @@ -61,6 +69,7 @@ from exceptiongroup import BaseExceptionGroup # type: ignore[import-not-found] _T = TypeVar('_T') +_Result = TypeVar('_Result', bound=BaseModel) logger = get_logger(__name__) @@ -101,6 +110,9 @@ reply. """ +_CANCEL_NOTICE_SECONDS = 1.0 +"""Bound on sending ``notifications/cancelled`` to a server that is not reading its stdin.""" + _CLOSE_GRACE_SECONDS = 6.0 """How long ``close`` lets the SDK's stdio shutdown run before it kills the server outright. @@ -123,6 +135,9 @@ def _client_info() -> Implementation: _serving: contextvars.ContextVar['McpConnection | None'] = contextvars.ContextVar('genkit_mcp_serving', default=None) """The connection whose operation the current task, or a task it spawned, is running.""" +_abandon: contextvars.ContextVar[anyio.CancelScope | None] = contextvars.ContextVar('genkit_mcp_abandon', default=None) +"""Cancelled once the caller of the operation the current task is running stops waiting for it.""" + class _ConnectionState(Enum): NEW = 'new' @@ -245,6 +260,60 @@ async def _call_tool( raise +class _Session(ClientSession): + """A session that sends ``notifications/cancelled`` for an operation's request that times out or is abandoned. + + Only for the ``mcp<2`` pin: SDK 2 sends this notice itself and has no + ``_request_id`` counter, so this class goes when the pin is lifted. + """ + + async def send_request( + self, + request: ClientRequest, + result_type: type[_Result], + request_read_timeout_seconds: timedelta | None = None, + metadata: MessageMetadata = None, + progress_callback: ProgressFnT | None = None, + ) -> _Result: + """Send a request and wait for its reply, cancelling it on the server if the wait is given up.""" + abandon = _abandon.get() + sent = super().send_request( + request, + result_type, + request_read_timeout_seconds=request_read_timeout_seconds, + metadata=metadata, + progress_callback=progress_callback, + ) + # Outside an operation (the handshake, the liveness probe), a request is never cancelled. + if abandon is None: + return await sent + # The SDK takes the request's id from this counter before it first suspends. + request_id = self._request_id + try: + return await sent + except McpError as error: + if _timed_out(error): + await self._cancel(request_id, 'Request timed out') + raise + except asyncio.CancelledError: + if abandon.cancel_called: + await self._cancel(request_id, 'Request cancelled') + raise + + async def _cancel(self, request_id: RequestId, reason: str) -> None: + """Ask the server to stop one request, giving up quietly if the notice cannot be written.""" + connection = _serving.get() + # When the connection is ending, the reply to the cancelled request could arrive after the reader has gone. + if connection is None or connection.is_terminal: + return + notice = CancelledNotification(params=CancelledNotificationParams(requestId=request_id, reason=reason)) + with anyio.move_on_after(_CANCEL_NOTICE_SECONDS, shield=True): + try: + await self.send_notification(ClientNotification(notice)) + except _TRANSPORT_ERRORS: + pass + + def validate_request_timeout(request_timeout_millis: int | None) -> None: """Reject a request timeout that is not positive. @@ -285,7 +354,9 @@ def __init__( 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. + the timeout. A request that times out, or whose caller is + cancelled, is stopped and the server is sent + ``notifications/cancelled``. host: Name of the host serving this server, if any, which errors and logs report alongside ``name``. @@ -483,7 +554,7 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No ) with shutdown: async with stdio_client(parameters) as (read_stream, write_stream): - async with ClientSession( + async with _Session( read_stream, write_stream, read_timeout_seconds=self._request_timeout, @@ -538,22 +609,35 @@ async def _serve(self, session: ClientSession) -> None: operations.start_soon(self._execute, session, request, operations.cancel_scope) async def _execute(self, session: ClientSession, request: _Request[Any], serving: anyio.CancelScope) -> None: - """Run one operation and release its caller, however the body is left.""" + """Run one operation and release its caller, however the body is left. + + A caller that is cancelled cancels the operation with it, and the + connection stays open. + """ _serving.set(self) + abandon = anyio.CancelScope() + _abandon.set(abandon) + + def caller_gone(result: asyncio.Future[Any]) -> None: + if result.cancelled(): + abandon.cancel() + + request.result.add_done_callback(caller_gone) deferred = False try: try: - value = await request.operation(session) + with abandon: + value = await request.operation(session) + if not request.result.done(): + request.result.set_result(value) except Exception as error: + _abandon.set(None) if await _transport_is_dead(session, error): # 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 request.result.done(): - request.result.set_result(value) 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: @@ -565,6 +649,7 @@ async def _execute(self, session: ClientSession, request: _Request[Any], serving deferred = True raise finally: + request.result.remove_done_callback(caller_gone) # A caller must never see the child's own CancelledError. if not deferred and not request.result.done(): request.result.set_exception(self._terminal_error()) diff --git a/packages/genkit-mcp/src/genkit_mcp/_host.py b/packages/genkit-mcp/src/genkit_mcp/_host.py index a8ae689c0..6186d947a 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_host.py +++ b/packages/genkit-mcp/src/genkit_mcp/_host.py @@ -72,7 +72,9 @@ def __init__( entry whose ``disabled`` is true is validated but left out. request_timeout_millis: How long one MCP request may take before it fails, for every server. Must be positive. ``None`` is the only - way to disable the timeout. + way to disable the timeout. A request that times out, or whose + caller is cancelled, is stopped and the server is sent + ``notifications/cancelled``. Raises: ValueError: If ``name`` cannot appear in a tool selector, if a @@ -421,7 +423,9 @@ def define_mcp_host( cache, so every lookup lists the tools again. request_timeout_millis: How long one MCP request may take before it fails, for every server. Must be positive. ``None`` is the only way - to disable the timeout. + to disable the timeout. A request that times out, or whose caller + is cancelled, is stopped and the server is sent + ``notifications/cancelled``. Returns: A handle for listing tools, connecting, reconnecting and disconnecting. diff --git a/packages/genkit-mcp/tests/fake_server.py b/packages/genkit-mcp/tests/fake_server.py index 24b9de335..0c27ef3c1 100644 --- a/packages/genkit-mcp/tests/fake_server.py +++ b/packages/genkit-mcp/tests/fake_server.py @@ -22,15 +22,18 @@ sys.modules['rfc3987_syntax'] = None # type: ignore[assignment] import anyio +from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream from mcp.server import Server from mcp.server.stdio import stdio_server from mcp.shared.exceptions import McpError +from mcp.shared.message import SessionMessage from mcp.types import ( CONNECTION_CLOSED, CallToolRequest, CallToolResult, EmptyResult, ErrorData, + JSONRPCNotification, ListToolsRequest, ListToolsResult, Resource, @@ -132,7 +135,18 @@ async def call_tool(name: str, arguments: dict[str, object]) -> list[TextContent await asyncio.sleep(0.25) if name == 'stall': stall_started.set() - await asyncio.Event().wait() + stall_dir = os.environ.get('MCP_FAKE_STALL_DIR') + if stall_dir is None: + await asyncio.Event().wait() + else: + marker = anyio.Path(stall_dir) / str(arguments.get('message', name)) + await marker.with_suffix('.started').write_text('started', encoding='utf-8') + try: + await asyncio.Event().wait() + finally: + # Written when a notifications/cancelled stops this call. + with anyio.CancelScope(shield=True): + await marker.with_suffix('.cancelled').write_text('cancelled', encoding='utf-8') if name == 'await_stall': await stall_started.wait() return [TextContent(type='text', text='stalled')] @@ -206,6 +220,22 @@ def close_stdin_after_handshake(marker: str) -> None: threading.Event().wait() +async def log_cancellations( + source: MemoryObjectReceiveStream[SessionMessage | Exception], + sink: MemoryObjectSendStream[SessionMessage | Exception], + log_path: str, +) -> None: + """Record the params of each notifications/cancelled the client sends, and pass every message on.""" + async with sink: + async for message in source: + if isinstance(message, SessionMessage): + notice = message.message.root + if isinstance(notice, JSONRPCNotification) and notice.method == 'notifications/cancelled': + async with await anyio.open_file(log_path, 'a', encoding='utf-8') as log: + await log.write(json.dumps(notice.params) + '\n') + await sink.send(message) + + async def main() -> None: if os.environ.get('MCP_FAKE_BAD_UTF8'): # Bypasses the SDK's text stream deliberately: this is a byte a strict @@ -221,7 +251,14 @@ async def main() -> None: # Never answers initialize, so the client stays in its connecting state. await asyncio.Event().wait() async with stdio_server() as (read_stream, write_stream): - await app.run(read_stream, write_stream, app.create_initialization_options()) + cancel_log = os.environ.get('MCP_FAKE_CANCEL_LOG') + if cancel_log is None: + await app.run(read_stream, write_stream, app.create_initialization_options()) + else: + sink, source = anyio.create_memory_object_stream[SessionMessage | Exception](0) + async with anyio.create_task_group() as tasks: + tasks.start_soon(log_cancellations, read_stream, sink, cancel_log) + await app.run(source, write_stream, app.create_initialization_options()) eof_marker = os.environ.get('MCP_FAKE_EOF_MARKER') if eof_marker: # Stands in for state a server flushes once stdin closes. diff --git a/packages/genkit-mcp/tests/mcp_connection_test.py b/packages/genkit-mcp/tests/mcp_connection_test.py index b62806fd9..fbcd85658 100644 --- a/packages/genkit-mcp/tests/mcp_connection_test.py +++ b/packages/genkit-mcp/tests/mcp_connection_test.py @@ -9,6 +9,7 @@ import asyncio import gc import io +import json import os import shlex import signal @@ -133,6 +134,13 @@ async def read() -> str: return await asyncio.wait_for(read(), timeout=LIMIT) +def cancellations(log: Path) -> list[dict[str, object]]: + """Read the notifications/cancelled params the server has received, in order.""" + if not log.exists(): + return [] + return [json.loads(line) for line in log.read_text(encoding='utf-8').splitlines()] + + async def stdin_closed(marker: Path) -> None: """Wait for the server to report that it closed its stdin.""" await server_marker(marker) @@ -647,29 +655,32 @@ 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: +@pytest.mark.parametrize('ending', ['cancelled', 'raises', 'returns']) +async def test_a_caller_cancelled_after_dispatch_cancels_its_operation_alone(tmp_path: Path, ending: str) -> None: 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() + running, stopped = asyncio.Event(), asyncio.Event() async def abandoned(session: ClientSession) -> list[McpTool]: running.set() - await release.wait() - # Nothing awaits between here and the outcome reaching the caller's future. - returned.set() - if raises: - raise ValueError('abandoned') + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + # Nothing suspends between here and the operation ending. + stopped.set() + if ending == 'cancelled': + raise + if ending == 'raises': + raise ValueError('abandoned') from None return [] caller = asyncio.create_task(connection._request(abandoned)) await asyncio.wait_for(running.wait(), timeout=LIMIT) caller.cancel() with pytest.raises(asyncio.CancelledError): - await caller - release.set() - await asyncio.wait_for(returned.wait(), timeout=LIMIT) + await asyncio.wait_for(caller, timeout=LIMIT) + await asyncio.wait_for(stopped.wait(), timeout=LIMIT) assert connection._state is _ConnectionState.OPEN assert connection._failure is None @@ -679,6 +690,43 @@ async def abandoned(session: ClientSession) -> list[McpTool]: await asyncio.wait_for(connection.close(), timeout=LIMIT) +@pytest.mark.asyncio +async def test_a_cancelled_call_is_cancelled_on_the_server(tmp_path: Path) -> None: + """With no request timeout, only the notice stops a call on the server before close.""" + stalls = tmp_path / 'stalls' + stalls.mkdir() + log = tmp_path / 'cancellations.jsonl' + connection = McpConnection( + 'fake', + config(tmp_path, MCP_FAKE_STALL_DIR=str(stalls), MCP_FAKE_CANCEL_LOG=str(log)), + request_timeout_millis=None, + ) + try: + cancelled = asyncio.create_task(connection.call_tool('stall', {'message': 'cancelled'})) + await server_marker(stalls / 'cancelled.started') + kept = asyncio.create_task(connection.call_tool('stall', {'message': 'kept'})) + await server_marker(stalls / 'kept.started') + + cancelled.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(cancelled, timeout=LIMIT) + await server_marker(stalls / 'cancelled.cancelled') + + assert cancellations(log) == [{'requestId': 1, 'reason': 'Request cancelled'}] + assert not (stalls / 'kept.cancelled').exists() + assert not kept.done() + assert connection._state is _ConnectionState.OPEN + alive = await asyncio.wait_for(connection.call_tool('echo', {'message': 'alive'}), timeout=LIMIT) + assert text_of(alive) == 'alive' + kept.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(kept, timeout=LIMIT) + await server_marker(stalls / 'kept.cancelled') + assert cancellations(log)[1:] == [{'requestId': 2, 'reason': 'Request cancelled'}] + finally: + await asyncio.wait_for(connection.close(), timeout=LIMIT) + + @pytest.mark.asyncio async def test_a_server_error_reply_outside_the_server_error_range_reports_its_status(tmp_path: Path) -> None: connection = McpConnection( @@ -1141,6 +1189,63 @@ async def stall(session: ClientSession) -> CallToolResult: await asyncio.wait_for(connection.close(), timeout=LIMIT) +@pytest.mark.asyncio +async def test_a_timed_out_call_is_cancelled_on_the_server(tmp_path: Path) -> None: + stalls = tmp_path / 'stalls' + stalls.mkdir() + log = tmp_path / 'cancellations.jsonl' + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_STALL_DIR=str(stalls), MCP_FAKE_CANCEL_LOG=str(log))) + + stall_ids: list[int] = [] + + # Long enough for the server to start the handler, so the notice has a call to stop. + async def stall(session: ClientSession) -> CallToolResult: + stall_ids.append(session._request_id) + return await session.call_tool('stall', {'message': 'late'}, read_timeout_seconds=timedelta(seconds=1)) + + try: + await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) + with pytest.raises(_RequestTimeoutError, match='timed out'): + await asyncio.wait_for(connection._request(stall), timeout=LIMIT) + + await server_marker(stalls / 'late.cancelled') + assert cancellations(log) == [{'requestId': stall_ids[0], 'reason': 'Request timed out'}] + assert connection._state is _ConnectionState.OPEN + finally: + await asyncio.wait_for(connection.close(), timeout=LIMIT) + + +@pytest.mark.asyncio +async def test_close_is_not_taken_for_an_abandoned_call(tmp_path: Path) -> None: + log = tmp_path / 'cancellations.jsonl' + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_CANCEL_LOG=str(log)), request_timeout_millis=None) + stalled = asyncio.create_task(connection.call_tool('stall', {})) + await asyncio.wait_for(connection.call_tool('await_stall', {}), timeout=LIMIT) + + await asyncio.wait_for(connection.close(), timeout=LIMIT) + + with pytest.raises(_ConnectionClosedError): + await asyncio.wait_for(stalled, timeout=LIMIT) + assert cancellations(log) == [] + + +@pytest.mark.asyncio +async def test_a_caller_cancelled_in_the_same_step_as_close_sends_no_cancellation(tmp_path: Path) -> None: + log = tmp_path / 'cancellations.jsonl' + connection = McpConnection('fake', config(tmp_path, MCP_FAKE_CANCEL_LOG=str(log)), request_timeout_millis=None) + caller = asyncio.create_task(connection.call_tool('stall', {})) + await asyncio.wait_for(connection.call_tool('await_stall', {}), timeout=LIMIT) + + # Close is scheduled first, so the operation is already ending when the caller's cancellation reaches it. + closing = asyncio.ensure_future(connection.close()) + caller.cancel() + await asyncio.wait_for(closing, timeout=LIMIT) + + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(caller, timeout=LIMIT) + assert cancellations(log) == [] + + @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."""