Skip to content
Closed
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
2 changes: 1 addition & 1 deletion packages/genkit-mcp/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ dependencies = [
"anyio>=4.9.0",
"exceptiongroup>=1.2.0; python_version < '3.11'",
"genkit>=0.14.0,<2",
"mcp>=1.26.0,<2",
"mcp>=1.26.0,<3",
"pydantic>=2.10.5",
]
description = "Model Context Protocol client for Genkit. Exposes an MCP server's tools as Genkit tools."
Expand Down
83 changes: 83 additions & 0 deletions packages/genkit-mcp/src/genkit_mcp/_compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

"""The parts of the MCP client API that differ between mcp 1.x and 2.x.

Each difference is detected from the installed SDK, not from its version string.
Names that only one major version defines are looked up with ``getattr`` so the
module imports, and type checks, against either.
"""

import importlib
from datetime import timedelta
from typing import Any

from mcp import ClientSession
from mcp.types import ErrorData, ServerCapabilities
from pydantic import BaseModel

_exceptions = importlib.import_module('mcp.shared.exceptions')
_types = importlib.import_module('mcp.types')

McpError: type[Exception] = getattr(_exceptions, 'MCPError', None) or getattr(_exceptions, 'McpError') # noqa: B009
"""The error the SDK raises for a JSON-RPC error reply. mcp 2 renamed ``McpError`` to ``MCPError``."""

REQUEST_TIMEOUT: int = getattr(_types, 'REQUEST_TIMEOUT', 408)
"""The code on the ``McpError`` the SDK raises when a request outlives its read timeout.

mcp 1.x used the HTTP status 408. mcp 2 uses the JSON-RPC code -32001 and exports it.
"""

_SESSION_HAS_PROPERTIES = hasattr(ClientSession, 'server_capabilities')
"""Whether this is mcp 2's ``ClientSession``, which also takes timeouts as float seconds rather than ``timedelta``."""


def error_data(error: BaseException) -> ErrorData | None:
"""Return the JSON-RPC error an ``McpError`` carries, or ``None`` for any other exception."""
if not isinstance(error, McpError):
return None
data: ErrorData = getattr(error, 'error') # noqa: B009 - McpError is typed as a plain Exception here.
return data


def read_timeout(timeout: timedelta | None) -> Any: # noqa: ANN401 - timedelta on mcp 1.x, float on mcp 2.
"""Convert a request timeout to the type this SDK's ``ClientSession`` takes."""
if timeout is None or not _SESSION_HAS_PROPERTIES:
return timeout
return timeout.total_seconds()


def server_capabilities(session: ClientSession) -> ServerCapabilities | None:
"""Return what the server advertised at initialize, or ``None`` before the handshake."""
if _SESSION_HAS_PROPERTIES:
return getattr(session, 'server_capabilities') # noqa: B009 - absent from mcp 1.x.
return getattr(session, 'get_server_capabilities')() # noqa: B009 - removed in mcp 2.


def field(model: BaseModel, name: str) -> Any: # noqa: ANN401 - the field's own type.
"""Read a protocol field by its mcp 2 snake_case name, falling back to the camelCase name mcp 1.x uses.

Args:
model: An ``mcp.types`` model.
name: The snake_case field name, such as ``next_cursor``.

Returns:
The field's value.
"""
if name in type(model).model_fields:
return getattr(model, name)
head, *rest = name.split('_')
return getattr(model, head + ''.join(part.capitalize() for part in rest))
75 changes: 45 additions & 30 deletions packages/genkit-mcp/src/genkit_mcp/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import anyio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.shared.exceptions import McpError
from mcp.types import (
CONNECTION_CLOSED,
INTERNAL_ERROR,
Expand All @@ -39,13 +38,15 @@
METHOD_NOT_FOUND,
PARSE_ERROR,
CallToolResult,
ErrorData,
Implementation,
PaginatedRequestParams,
Tool as McpTool,
)

from genkit import get_logger
from genkit.plugin_api import StatusName
from genkit_mcp._compat import REQUEST_TIMEOUT, McpError, error_data, field, read_timeout, server_capabilities
from genkit_mcp._config import McpStdioServerConfig
from genkit_mcp._errors import (
_ClientError,
Expand Down Expand Up @@ -81,9 +82,6 @@
DEFAULT_REQUEST_TIMEOUT_MILLIS = 60_000
"""How long one MCP request may take before the SDK fails it."""

_REQUEST_TIMEOUT = 408
"""The code on the ``McpError`` the SDK raises when a request outlives its read timeout."""

_SERVER_ERROR_STATUS: dict[int, StatusName] = {
INVALID_PARAMS: 'INVALID_ARGUMENT',
METHOD_NOT_FOUND: 'UNIMPLEMENTED',
Expand All @@ -105,7 +103,8 @@
"""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
after SIGTERM to the process group before it sends SIGKILL.
after SIGTERM to the process group before it sends SIGKILL. mcp 2 shields that
shutdown and bounds every wait in it, so there this deadline cannot cut it short.
"""


Expand Down Expand Up @@ -157,12 +156,14 @@ async def _transport_is_dead(session: ClientSession, error: Exception) -> bool:
"""
if isinstance(error, _TRANSPORT_ERRORS):
return True
if not isinstance(error, McpError) or error.error.code != CONNECTION_CLOSED:
reply = error_data(error)
if reply is None or reply.code != CONNECTION_CLOSED:
return False
try:
await asyncio.wait_for(session.send_ping(), timeout=_LIVENESS_PROBE_SECONDS)
except McpError as probe:
return probe.error.code == CONNECTION_CLOSED
probe_reply = error_data(probe)
return probe_reply is not None and probe_reply.code == CONNECTION_CLOSED
except asyncio.TimeoutError:
return False
except Exception:
Expand All @@ -172,7 +173,8 @@ async def _transport_is_dead(session: ClientSession, error: Exception) -> bool:

def _timed_out(error: Exception) -> bool:
"""Report whether the SDK gave up waiting for the server to answer a request."""
return isinstance(error, McpError) and error.error.code == _REQUEST_TIMEOUT
reply = error_data(error)
return reply is not None and reply.code == REQUEST_TIMEOUT


def _transport_cause(error: Exception) -> Exception:
Expand Down Expand Up @@ -237,7 +239,7 @@ async def _call_tool(
_ToolResultError: If the result violates the tool's declared output schema.
"""
try:
return await session.call_tool(name, arguments, meta=meta)
return await session.call_tool(name, arguments, meta=cast(Any, meta))
except RuntimeError as error:
message = str(error)
if any(marker in message for marker in _OUTPUT_SCHEMA_VIOLATIONS):
Expand Down Expand Up @@ -334,7 +336,7 @@ async def list_tools(self) -> list[McpTool]:
"""

async def list_all(session: ClientSession) -> list[McpTool]:
capabilities = session.get_server_capabilities()
capabilities = server_capabilities(session)
if capabilities is None or capabilities.tools is None:
return []
tools: list[McpTool] = []
Expand All @@ -345,7 +347,7 @@ async def list_all(session: ClientSession) -> list[McpTool]:
params=PaginatedRequestParams(cursor=cursor) if cursor is not None else None
)
tools.extend(result.tools)
cursor = result.nextCursor
cursor = field(result, 'next_cursor')
if not cursor:
return tools
if cursor in seen:
Expand Down Expand Up @@ -470,7 +472,7 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No
``_CLOSE_GRACE_SECONDS``.
stop: Cancelled by ``close`` to end the session's work.
"""
handshake_failure: McpError | None = None
handshake_failure: Exception | None = None
try:
parameters = StdioServerParameters(
command=self._config.command,
Expand All @@ -486,10 +488,10 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No
async with ClientSession(
read_stream,
write_stream,
read_timeout_seconds=self._request_timeout,
read_timeout_seconds=read_timeout(self._request_timeout),
client_info=_CLIENT_INFO,
) as session:
# The SDK's stdio shutdown is not shielded, so no scope around it may be cancelled.
# mcp 1.x does not shield its stdio shutdown, so no scope around it may be cancelled.
with stop:
try:
await session.initialize()
Expand All @@ -508,22 +510,34 @@ async def _run(self, shutdown: anyio.CancelScope, stop: anyio.CancelScope) -> No
self._settle(None)
raise
cause = handshake_failure if handshake_failure is not None else _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',
**named,
command=self._config.command,
error=type(error).__name__,
cause=repr(cause),
)
self._log_ended(error, cause)
self._settle(cause)
else:
# mcp 2 reports a dead transport to the request that hit it rather than
# raising it out of the transport, so ``_execute`` settles and stops the
# serve loop, and the owner unwinds without an exception of its own.
if self._failure is not None:
self._log_ended(self._failure, self._failure)
finally:
# anyio cancel scopes inside the SDK can absorb whatever ended the
# serve loop, so this is the only settlement guaranteed to run.
self._settle(None)
self._ready.set()

def _log_ended(self, error: Exception, cause: Exception) -> None:
"""Log why the session ended, by type and repr only.

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',
**named,
command=self._config.command,
error=type(error).__name__,
cause=repr(cause),
)

async def _serve(self, session: ClientSession) -> None:
"""Start each queued operation as a child task until the transport dies."""
async with anyio.create_task_group() as operations:
Expand Down Expand Up @@ -627,8 +641,9 @@ 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)
reply = error_data(error)
if reply is not None:
return self._server_error(error, reply)
if isinstance(error, _ClientError):
return error
return self._protocol_error(error)
Expand All @@ -639,15 +654,15 @@ def _protocol_error(self, failure: Exception) -> _ProtocolError:
error.__cause__ = failure
return error

def _server_error(self, reply: McpError) -> _ServerError:
def _server_error(self, failure: Exception, reply: ErrorData) -> _ServerError:
"""Build the error reported when the server answered one request with a JSON-RPC error."""
code = reply.error.code
code = reply.code
error = _ServerError(
f'MCP request to {self._target} failed with error {code}: {reply.error.message}',
f'MCP request to {self._target} failed with error {code}: {reply.message}',
status=_SERVER_ERROR_STATUS.get(code, 'UNKNOWN'),
cause=reply,
cause=failure,
)
error.__cause__ = reply
error.__cause__ = failure
return error

def _timed_out_error(self, timeout: Exception) -> _RequestTimeoutError:
Expand Down
22 changes: 12 additions & 10 deletions packages/genkit-mcp/src/genkit_mcp/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
)

from genkit import MultipartToolResponse, Part, Tool, ToolContext, get_logger
from genkit_mcp._compat import field
from genkit_mcp._errors import _ToolResultError

McpToolCall = Callable[[str, dict[str, Any], dict[str, Any] | None], Awaitable[CallToolResult]]
Expand Down Expand Up @@ -133,7 +134,7 @@ def call_result_to_multipart(result: CallToolResult) -> MultipartToolResponse:
The envelope ``generate`` expects from a ``tool`` action.
"""
metadata = dict(result.meta) if result.meta is not None else None
if result.isError:
if field(result, 'is_error'):
error_text = ''.join(block.text for block in result.content if isinstance(block, TextContent))
return MultipartToolResponse(
output={'error': error_text},
Expand All @@ -146,17 +147,17 @@ def call_result_to_multipart(result: CallToolResult) -> MultipartToolResponse:
if isinstance(block, TextContent):
text_output += block.text
elif isinstance(block, (ImageContent, AudioContent)):
content.append(_media_part(block.mimeType, block.data))
content.append(_media_part(field(block, 'mime_type'), block.data))
elif isinstance(block, EmbeddedResource):
resource = block.resource
if isinstance(resource, TextResourceContents):
if text_output:
text_output += '\n\n'
text_output += f'Resource ({resource.uri}):\n{resource.text}'
elif isinstance(resource, BlobResourceContents):
content.append(_media_part(resource.mimeType or 'application/octet-stream', resource.blob))
content.append(_media_part(field(resource, 'mime_type') or 'application/octet-stream', resource.blob))

output: object | None = result.structuredContent
output: object | None = field(result, 'structured_content')
if output is None and text_output:
output = _text_output(text_output)
return MultipartToolResponse(
Expand Down Expand Up @@ -228,17 +229,18 @@ async def handler(input: dict[str, Any], ctx: ToolContext) -> MultipartToolRespo
try:
result = await call(tool.name, input, meta)
except _ToolResultError as error:
result = CallToolResult(
content=[TextContent(type='text', text=error.message)],
isError=True,
)
# Validated from wire-shaped data: mcp 1.x would keep an ``is_error`` keyword as an unknown extra.
result = CallToolResult.model_validate({
'content': [TextContent(type='text', text=error.message)],
'isError': True,
})
return call_result_to_multipart(result)

action: Tool = Tool(
handler,
name=tool_name,
description=tool.description or '',
input_schema=tool.inputSchema,
input_schema=field(tool, 'input_schema'),
)
action.metadata['name'] = action.name
action.metadata['mcp'] = {'prefix': prefix, 'tool': tool.name, '_meta': mcp_meta}
Expand Down Expand Up @@ -301,6 +303,6 @@ def mcp_tools_to_handles(
by_name = {mcp_tool_name(prefix, tool.name): tool for tool in tools}
handles = mcp_tools_to_actions(tools, prefix, call)
for handle in handles:
output_schema = by_name[handle.name].outputSchema
output_schema = field(by_name[handle.name], 'output_schema')
handle.model_output_schema = dict(output_schema) if output_schema is not None else None
return handles
Loading
Loading