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
8 changes: 5 additions & 3 deletions packages/genkit-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`,
Expand Down
6 changes: 4 additions & 2 deletions packages/genkit-mcp/src/genkit_mcp/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
99 changes: 92 additions & 7 deletions packages/genkit-mcp/src/genkit_mcp/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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__)

Expand Down Expand Up @@ -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.

Expand All @@ -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'
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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``.

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -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())
Expand Down
8 changes: 6 additions & 2 deletions packages/genkit-mcp/src/genkit_mcp/_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
41 changes: 39 additions & 2 deletions packages/genkit-mcp/tests/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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')]
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
Loading
Loading