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

Expand Down
71 changes: 52 additions & 19 deletions packages/genkit-mcp/src/genkit_mcp/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -93,15 +93,15 @@
}
"""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
dead one: the opposite reading tears down a healthy connection over one slow
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
Expand All @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
"""
Expand All @@ -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
)
Expand All @@ -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)

Expand 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.
"""
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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,
)
Expand All @@ -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
6 changes: 5 additions & 1 deletion packages/genkit-mcp/src/genkit_mcp/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 3 additions & 1 deletion packages/genkit-mcp/src/genkit_mcp/_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,14 +341,16 @@ 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,
env=config.env,
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."""
Expand Down
14 changes: 7 additions & 7 deletions packages/genkit-mcp/src/genkit_mcp/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""


Expand All @@ -63,7 +63,7 @@ def validate_provider_name(name: str) -> None:
Raises:
ValueError: If ``<name>:tool/<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 '
Expand All @@ -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 '
Expand All @@ -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

Expand Down Expand Up @@ -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,
Expand Down
9 changes: 9 additions & 0 deletions packages/genkit-mcp/tests/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
CONNECTION_CLOSED,
CallToolRequest,
CallToolResult,
EmptyResult,
ErrorData,
ListToolsRequest,
ListToolsResult,
Expand Down Expand Up @@ -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]
Expand Down
6 changes: 3 additions & 3 deletions packages/genkit-mcp/tests/mcp_client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Loading
Loading