diff --git a/packages/genkit-mcp/pyproject.toml b/packages/genkit-mcp/pyproject.toml index 15b2dabe7..0bf39f1bc 100644 --- a/packages/genkit-mcp/pyproject.toml +++ b/packages/genkit-mcp/pyproject.toml @@ -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." diff --git a/packages/genkit-mcp/src/genkit_mcp/_compat.py b/packages/genkit-mcp/src/genkit_mcp/_compat.py new file mode 100644 index 000000000..5e1a6e408 --- /dev/null +++ b/packages/genkit-mcp/src/genkit_mcp/_compat.py @@ -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)) diff --git a/packages/genkit-mcp/src/genkit_mcp/_connection.py b/packages/genkit-mcp/src/genkit_mcp/_connection.py index 75edba3da..abc59a28d 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_connection.py +++ b/packages/genkit-mcp/src/genkit_mcp/_connection.py @@ -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, @@ -39,6 +38,7 @@ METHOD_NOT_FOUND, PARSE_ERROR, CallToolResult, + ErrorData, Implementation, PaginatedRequestParams, Tool as McpTool, @@ -46,6 +46,7 @@ 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, @@ -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', @@ -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. """ @@ -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: @@ -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: @@ -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): @@ -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] = [] @@ -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: @@ -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, @@ -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() @@ -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: @@ -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) @@ -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: diff --git a/packages/genkit-mcp/src/genkit_mcp/_tools.py b/packages/genkit-mcp/src/genkit_mcp/_tools.py index 257de3188..d951f04af 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_tools.py +++ b/packages/genkit-mcp/src/genkit_mcp/_tools.py @@ -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]] @@ -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}, @@ -146,7 +147,7 @@ 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): @@ -154,9 +155,9 @@ def call_result_to_multipart(result: CallToolResult) -> MultipartToolResponse: 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( @@ -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} @@ -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 diff --git a/packages/genkit-mcp/tests/fake_server.py b/packages/genkit-mcp/tests/fake_server.py index 24b9de335..81543bc3c 100644 --- a/packages/genkit-mcp/tests/fake_server.py +++ b/packages/genkit-mcp/tests/fake_server.py @@ -13,6 +13,7 @@ import os import sys import threading +from typing import Any, cast # mcp.server imports jsonschema, which loads rfc3987_syntax when it is installed # (dotpromptz pulls it in). That module compiles a Lark grammar at import, which @@ -22,45 +23,61 @@ sys.modules['rfc3987_syntax'] = None # type: ignore[assignment] import anyio +from genkit_mcp._compat import McpError, field from mcp.server import Server from mcp.server.stdio import stdio_server -from mcp.shared.exceptions import McpError from mcp.types import ( CONNECTION_CLOSED, CallToolRequest, CallToolResult, - EmptyResult, ErrorData, + ListResourcesResult, ListToolsRequest, ListToolsResult, - Resource, ServerResult, TextContent, Tool, ) -app = Server('fake-server') +MCP_V2 = not hasattr(Server, 'list_tools') +"""mcp 2 replaced the lowlevel server's handler decorators with ``on_*`` constructor arguments.""" + + +def mcp_error(code: int, message: str) -> Exception: + """Build the SDK's JSON-RPC error. mcp 2 takes the code and message, mcp 1.x an ``ErrorData``.""" + data = ErrorData(code=code, message=message) + from_error_data = getattr(McpError, 'from_error_data', None) + return from_error_data(data) if from_error_data is not None else McpError(data) + + +def tool(name: str, description: str, **fields: object) -> Tool: + """Build a tool from wire-shaped fields, which mcp 1.x and 2.x both parse.""" + return Tool.model_validate({'name': name, 'description': description, 'inputSchema': {'type': 'object'}, **fields}) + + +def text_result(text: str) -> CallToolResult: + return CallToolResult(content=[TextContent(type='text', text=text)]) + TOOLS = [ - Tool(name='echo', description='Echo input.', inputSchema={'type': 'object'}), - Tool(name='second', description='Another tool.', inputSchema={'type': 'object'}), - Tool(name='wait', description='Wait before replying.', inputSchema={'type': 'object'}), - Tool(name='list_requests', description='Count tools/list requests.', inputSchema={'type': 'object'}), - Tool(name='who_called', description='Report the client that connected.', inputSchema={'type': 'object'}), - Tool(name='stall', description='Never reply.', inputSchema={'type': 'object'}), - Tool(name='rendezvous', description='Reply once two calls are in flight together.', inputSchema={'type': 'object'}), - Tool(name='await_stall', description='Reply once a stall call is in flight.', inputSchema={'type': 'object'}), - Tool( - name='bad_output', - description='Violate its own output schema.', - inputSchema={'type': 'object'}, + tool('echo', 'Echo input.'), + tool('second', 'Another tool.'), + tool('wait', 'Wait before replying.'), + tool('list_requests', 'Count tools/list requests.'), + tool('who_called', 'Report the client that connected.'), + tool('stall', 'Never reply.'), + tool('rendezvous', 'Reply once two calls are in flight together.'), + tool('await_stall', 'Reply once a stall call is in flight.'), + tool( + 'bad_output', + 'Violate its own output schema.', outputSchema={'type': 'object', 'properties': {'value': {'type': 'integer'}}, 'required': ['value']}, ), ] COLLIDING_TOOLS = [ - Tool(name='look.up', description='Collides once rewritten.', inputSchema={'type': 'object'}), - Tool(name='look/up', description='Collides once rewritten.', inputSchema={'type': 'object'}), + tool('look.up', 'Collides once rewritten.'), + tool('look/up', 'Collides once rewritten.'), ] PAGE_SIZE = int(os.environ.get('MCP_FAKE_PAGE_SIZE', '2')) @@ -84,14 +101,22 @@ def write_marker(path: str, text: str) -> None: os.replace(staging, path) -@app.list_tools() -async def list_tools(req: ListToolsRequest) -> ListToolsResult: - # The SDK passes None when it refreshes its own tool cache, and that refresh - # must see every tool or call_tool skips input validation. +def page(tools: list[Tool], next_cursor: str | None) -> ListToolsResult: + return ListToolsResult.model_validate({'tools': tools, 'nextCursor': next_cursor}) + + +async def list_tools(cursor: str | None, *, cache_refresh: bool = False) -> ListToolsResult: + """Answer one tools/list page. + + Args: + cursor: The cursor the client sent, if any. + cache_refresh: Whether mcp 1.x's server is refreshing its own tool cache, + which must see every tool or call_tool skips input validation. + """ if os.environ.get('MCP_FAKE_COLLIDING_TOOLS'): return ListToolsResult(tools=COLLIDING_TOOLS) - if req is None: + if cache_refresh: return ListToolsResult(tools=TOOLS) global list_requests @@ -101,7 +126,7 @@ async def list_tools(req: ListToolsRequest) -> ListToolsResult: # -32000 is the JSON-RPC implementation-defined server error range, which # a healthy server may use and the SDK also synthesises on transport death. code = int(os.environ.get('MCP_FAKE_APP_ERROR_CODE', CONNECTION_CLOSED)) - raise McpError(ErrorData(code=code, message='application-level failure')) + raise mcp_error(code, 'application-level failure') stall_list_marker = os.environ.get('MCP_FAKE_STALL_LIST') if stall_list_marker: @@ -109,24 +134,33 @@ async def list_tools(req: ListToolsRequest) -> ListToolsResult: await asyncio.Event().wait() if os.environ.get('MCP_FAKE_STUCK_CURSOR'): - return ListToolsResult(tools=TOOLS[:1], nextCursor='stuck') + return page(TOOLS[:1], 'stuck') if os.environ.get('MCP_FAKE_EMPTY_CURSOR'): - return ListToolsResult(tools=TOOLS, nextCursor='') + return page(TOOLS, '') if os.environ.get('MCP_FAKE_ENDLESS_CURSOR'): - return ListToolsResult(tools=TOOLS[:1], nextCursor=str(list_requests)) + return page(TOOLS[:1], str(list_requests)) - start = int(req.params.cursor) if req.params is not None and req.params.cursor is not None else 0 + start = int(cursor) if cursor is not None else 0 end = start + PAGE_SIZE - return ListToolsResult(tools=TOOLS[start:end], nextCursor=str(end) if end < len(TOOLS) else None) + return page(TOOLS[start:end], str(end) if end < len(TOOLS) else None) + +async def call_tool(name: str, arguments: dict[str, object], client: object) -> CallToolResult: + """Answer one tools/call. -@app.call_tool() -async def call_tool(name: str, arguments: dict[str, object]) -> list[TextContent] | CallToolResult: + Args: + name: The tool the client called. + arguments: The tool input. + client: The ``Implementation`` the client named at initialize. + """ call_marker = os.environ.get('MCP_FAKE_CALL_MARKER') if call_marker: write_marker(call_marker, name) + if os.environ.get('MCP_FAKE_APP_ERROR_CALL'): + # A JSON-RPC error on the wire, not an isError result. + raise mcp_error(CONNECTION_CLOSED, 'application-level failure') if name == 'wait': # Must stay under the SDK's PROCESS_TERMINATION_TIMEOUT of 2.0 seconds. await asyncio.sleep(0.25) @@ -135,53 +169,121 @@ async def call_tool(name: str, arguments: dict[str, object]) -> list[TextContent await asyncio.Event().wait() if name == 'await_stall': await stall_started.wait() - return [TextContent(type='text', text='stalled')] + return text_result('stalled') if name == 'rendezvous': global rendezvous_arrivals rendezvous_arrivals += 1 if rendezvous_arrivals == 2: rendezvous_met.set() await rendezvous_met.wait() - return [TextContent(type='text', text=str(rendezvous_arrivals))] + return text_result(str(rendezvous_arrivals)) if name == 'bad_output': - # A ready-made CallToolResult bypasses the decorator's own output validation. - return CallToolResult( - content=[TextContent(type='text', text='not an integer')], - structuredContent={'value': 'not an integer'}, - ) + # Neither SDK's server validates a ready-made CallToolResult against the output schema. + return CallToolResult.model_validate({ + 'content': [TextContent(type='text', text='not an integer')], + 'structuredContent': {'value': 'not an integer'}, + }) if name == 'list_requests': - return [TextContent(type='text', text=str(list_requests))] + return text_result(str(list_requests)) if name == 'who_called': - client = app.request_context.session.client_params assert client is not None - return [TextContent(type='text', text=f'{client.clientInfo.name} {client.clientInfo.version}')] - return [TextContent(type='text', text=str(arguments.get('message', name)))] + return text_result(f'{getattr(client, "name")} {getattr(client, "version")}') # noqa: B009 + return text_result(str(arguments.get('message', name))) + + +def build_v2_server() -> Server[Any]: + """Register the handlers through mcp 2's ``on_*`` constructor arguments.""" + if os.environ.get('MCP_FAKE_NO_TOOLS'): + # Without tool handlers the server neither advertises tools nor answers tools/list. + async def list_resources(ctx: Any, params: Any) -> ListResourcesResult: # noqa: ANN401 + return ListResourcesResult(resources=[]) + + return Server('fake-server', on_list_resources=list_resources) + + async def on_list_tools(ctx: Any, params: Any) -> ListToolsResult: # noqa: ANN401 + return await list_tools(params.cursor if params is not None else None) + + async def on_call_tool(ctx: Any, params: Any) -> CallToolResult: # noqa: ANN401 + client_params = ctx.session.client_params + client = field(client_params, 'client_info') if client_params is not None else None + return await call_tool(params.name, params.arguments or {}, client) + return Server('fake-server', on_list_tools=on_list_tools, on_call_tool=on_call_tool) -if os.environ.get('MCP_FAKE_APP_ERROR_CALL'): - # The call_tool decorator turns handler exceptions into isError results, so - # putting a JSON-RPC error code on the wire needs the raw handler. - async def failing_call(req: CallToolRequest) -> ServerResult: - raise McpError(ErrorData(code=CONNECTION_CLOSED, message='application-level failure')) - app.request_handlers[CallToolRequest] = failing_call +def build_v1_server() -> Any: # noqa: ANN401 - mcp 1.x's Server, whose decorators mcp 2 removed. + """Register the handlers through mcp 1.x's decorators and request handler table.""" + app = cast(Any, Server('fake-server')) -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.list_tools() + # The annotation must be exactly ListToolsRequest: mcp 1.x reads it to decide whether to pass the request. + async def on_list_tools(req: ListToolsRequest) -> ListToolsResult: + # mcp 1.x passes None when its server refreshes its own tool cache. + if req is None: # pyright: ignore[reportUnnecessaryComparison] + return await list_tools(None, cache_refresh=True) + return await list_tools(req.params.cursor if req.params is not None else None) - app.request_handlers[ListToolsRequest] = empty_reply - app.request_handlers[CallToolRequest] = empty_reply + @app.call_tool() + async def on_call_tool(name: str, arguments: dict[str, object]) -> CallToolResult: + client_params = app.request_context.session.client_params + return await call_tool(name, arguments, client_params.clientInfo if client_params is not None else None) -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] - del app.request_handlers[CallToolRequest] + if os.environ.get('MCP_FAKE_APP_ERROR_CALL'): + # The call_tool decorator turns handler exceptions into isError results, so + # putting a JSON-RPC error code on the wire needs the raw handler. + async def failing_call(req: CallToolRequest) -> ServerResult: + raise mcp_error(CONNECTION_CLOSED, 'application-level failure') - @app.list_resources() - async def list_resources() -> list[Resource]: - return [] + app.request_handlers[CallToolRequest] = failing_call + + 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] + del app.request_handlers[CallToolRequest] + + @app.list_resources() + async def list_resources() -> list[object]: + return [] + + return app + + +app: Any = build_v2_server() if MCP_V2 else build_v1_server() + + +def initialize_reply(message: dict[str, Any]) -> dict[str, Any]: + return { + 'jsonrpc': '2.0', + 'id': message['id'], + 'result': { + 'protocolVersion': message['params']['protocolVersion'], + 'capabilities': {'tools': {}}, + 'serverInfo': {'name': 'fake-server', 'version': '0'}, + }, + } + + +def reply_with_empty_results() -> None: + """Answer every request after initialize with an empty result. + + An empty result is valid JSON-RPC but lacks the fields tools/list and + tools/call require. Written by hand because mcp 2's server validates what a + handler returns before it reaches the wire. + """ + for line in sys.stdin.buffer: + message = json.loads(line) + if 'id' not in message or 'method' not in message: + continue + reply = ( + initialize_reply(message) + if message['method'] == 'initialize' + else { + 'jsonrpc': '2.0', + 'id': message['id'], + 'result': {}, + } + ) + os.write(1, (json.dumps(reply) + '\n').encode()) def close_stdin_after_handshake(marker: str) -> None: @@ -189,16 +291,7 @@ def close_stdin_after_handshake(marker: str) -> None: while True: message = json.loads(sys.stdin.buffer.readline()) if message.get('method') == 'initialize': - reply = { - 'jsonrpc': '2.0', - 'id': message['id'], - 'result': { - 'protocolVersion': message['params']['protocolVersion'], - 'capabilities': {'tools': {}}, - 'serverInfo': {'name': 'fake-server', 'version': '0'}, - }, - } - os.write(1, (json.dumps(reply) + '\n').encode()) + os.write(1, (json.dumps(initialize_reply(message)) + '\n').encode()) elif message.get('method') == 'notifications/initialized': break os.close(0) @@ -214,6 +307,9 @@ async def main() -> None: pid_file = os.environ.get('MCP_FAKE_PID_FILE') if pid_file: write_marker(pid_file, str(os.getpid())) + if os.environ.get('MCP_FAKE_MALFORMED_REPLY'): + reply_with_empty_results() + return close_stdin_marker = os.environ.get('MCP_FAKE_CLOSE_STDIN') if close_stdin_marker: close_stdin_after_handshake(close_stdin_marker) diff --git a/packages/genkit-mcp/tests/mcp_connection_test.py b/packages/genkit-mcp/tests/mcp_connection_test.py index ced317ef5..622bb79bf 100644 --- a/packages/genkit-mcp/tests/mcp_connection_test.py +++ b/packages/genkit-mcp/tests/mcp_connection_test.py @@ -26,6 +26,7 @@ import pytest import structlog from genkit_mcp import _connection +from genkit_mcp._compat import REQUEST_TIMEOUT, McpError, error_data, read_timeout from genkit_mcp._config import McpStdioServerConfig from genkit_mcp._connection import McpConnection, _call_tool, _ConnectionState, _Request from genkit_mcp._errors import ( @@ -38,7 +39,6 @@ _ToolResultError, ) from mcp import ClientSession -from mcp.shared.exceptions import McpError from mcp.types import ( CONNECTION_CLOSED, INTERNAL_ERROR, @@ -79,6 +79,32 @@ SECRET = 'genkit-mcp-redaction-canary-7f3a' +MCP_V2 = int(metadata.version('mcp').split('.')[0]) >= 2 + +REQUESTS_ARE_CANCELLED_ON_A_BROKEN_STDIN = pytest.mark.skipif( + MCP_V2, reason='mcp 2 fails the request with CONNECTION_CLOSED instead of cancelling it before the transport error' +) + + +def is_broken_stdin(error: BaseException | None) -> bool: + """Report whether ``error`` is how the SDK reports a write to a closed stdin. + + mcp 1.x raises the write's ``BrokenResourceError``. mcp 2 closes the read side + instead, so the request fails with ``CONNECTION_CLOSED``. + """ + if not MCP_V2: + return isinstance(error, anyio.BrokenResourceError) + reply = error_data(error) if error is not None else None + return reply is not None and reply.code == CONNECTION_CLOSED + + +def mcp_error(code: int, message: str) -> Exception: + """Build the SDK's JSON-RPC error. mcp 2 takes the code and message, mcp 1.x an ``ErrorData``.""" + data = ErrorData(code=code, message=message) + from_error_data = getattr(McpError, 'from_error_data', None) + return from_error_data(data) if from_error_data is not None else McpError(data) + + def config(tmp_path: Path, pid_file: Path | None = None, **env: str) -> McpStdioServerConfig: """Launch the test server with the same interpreter as the test suite.""" return McpStdioServerConfig( @@ -370,7 +396,8 @@ async def test_close_kills_a_server_whose_shutdown_overruns_the_grace( started = time.monotonic() await asyncio.wait_for(connection.close(), timeout=LIMIT) # The SDK alone waits two seconds for a server that never reads its stdin. - assert time.monotonic() - started < 1.5 + # mcp 2 shields that wait, so there close takes the SDK's own two seconds. + assert time.monotonic() - started < (3.5 if MCP_V2 else 1.5) assert not is_running(pid) with pytest.raises(_ConnectionClosedError, match='closed'): await asyncio.wait_for(waiter, timeout=LIMIT) @@ -529,7 +556,7 @@ async def test_a_caller_cut_off_by_a_broken_stdin_carries_the_transport_error(tm with pytest.raises(_ConnectionFailedError, match='failed') as failure: await asyncio.wait_for(connection.call_tool('echo', {}), timeout=LIMIT) - assert isinstance(failure.value.__cause__, anyio.BrokenResourceError) + assert is_broken_stdin(failure.value.__cause__) await settle(owner) with pytest.raises(_ConnectionFailedError, match='failed') as later: @@ -539,6 +566,7 @@ async def test_a_caller_cut_off_by_a_broken_stdin_carries_the_transport_error(tm await asyncio.wait_for(connection.close(), timeout=LIMIT) +@REQUESTS_ARE_CANCELLED_ON_A_BROKEN_STDIN @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' @@ -572,6 +600,7 @@ async def cut_off(session: ClientSession) -> list[McpTool]: await asyncio.wait_for(connection.close(), timeout=LIMIT) +@REQUESTS_ARE_CANCELLED_ON_A_BROKEN_STDIN @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' @@ -622,9 +651,9 @@ 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 type(failure.value.__cause__).__name__ in logged assert SECRET not in logged - assert isinstance(failure.value.__cause__, anyio.BrokenResourceError) + assert is_broken_stdin(failure.value.__cause__) assert SECRET not in rendered_for_logs(failure.value) @@ -729,7 +758,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')) + reply = mcp_error(code, 'refused') error = McpConnection('fake', config(tmp_path))._answered_error(reply) @@ -862,8 +891,8 @@ def leaf_causes(error: BaseException | None) -> list[BaseException]: return [leaf for child in nested for leaf in leaf_causes(child)] -def closed_mcp_error(message: str = 'connection closed') -> McpError: - return McpError(ErrorData(code=CONNECTION_CLOSED, message=message)) +def closed_mcp_error(message: str = 'connection closed') -> Exception: + return mcp_error(CONNECTION_CLOSED, message) @pytest.mark.asyncio @@ -874,8 +903,8 @@ def closed_mcp_error(message: str = 'connection closed') -> McpError: (anyio.ClosedResourceError(), True), (anyio.EndOfStream(), True), (RuntimeError('unrelated'), False), - (McpError(ErrorData(code=-32601, message='method not found')), False), - (McpError(ErrorData(code=408, message='Timed out while waiting for response')), False), + (mcp_error(-32601, 'method not found'), False), + (mcp_error(REQUEST_TIMEOUT, 'Timed out while waiting for response'), False), ], ) async def test_transport_death_is_decided_without_a_probe(error: Exception, dead: bool) -> None: @@ -889,7 +918,7 @@ async def test_transport_death_is_decided_without_a_probe(error: Exception, dead ('outcome', 'dead'), [ (None, False), - (McpError(ErrorData(code=-32601, message='method not found')), False), + (mcp_error(-32601, 'method not found'), False), (closed_mcp_error(), True), (anyio.ClosedResourceError(), True), ], @@ -1119,17 +1148,18 @@ async def test_a_request_timeout_fails_that_call_alone(tmp_path: Path) -> None: # The session-wide timeout also bounds the handshake, which takes seconds on a # loaded machine, so the stalled call carries its own. The SDK enforces both - # with the same deadline and raises the same 408. + # with the same deadline and raises the same REQUEST_TIMEOUT. async def stall(session: ClientSession) -> CallToolResult: - return await session.call_tool('stall', {}, read_timeout_seconds=timedelta(milliseconds=100)) + return await session.call_tool('stall', {}, read_timeout_seconds=read_timeout(timedelta(milliseconds=100))) try: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) with pytest.raises(_RequestTimeoutError, match="MCP request to 'fake' .* timed out") as timed_out: await asyncio.wait_for(connection._request(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 + reply = error_data(timed_out.value.__cause__) + assert reply is not None + assert reply.code == REQUEST_TIMEOUT assert attached_cause(timed_out.value) is timed_out.value.__cause__ assert str(timed_out.value.__cause__) in str(timed_out.value) @@ -1150,7 +1180,7 @@ async def test_a_handshake_which_never_answers_gives_up(tmp_path: Path) -> None: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) causes = leaf_causes(failure.value.__cause__) - assert [error.error.code for error in causes if isinstance(error, McpError)] == [408] + assert [reply.code for reply in map(error_data, causes) if reply is not None] == [REQUEST_TIMEOUT] await asyncio.wait_for(connection.close(), timeout=LIMIT) @@ -1165,8 +1195,9 @@ async def test_a_handshake_answered_after_the_timeout_still_reports_the_timeout( with pytest.raises(_ConnectionFailedError, match='failed') as failure: await asyncio.wait_for(connection.list_tools(), timeout=LIMIT) - assert isinstance(failure.value.__cause__, McpError) - assert failure.value.__cause__.error.code == 408 + reply = error_data(failure.value.__cause__) + assert reply is not None + assert reply.code == REQUEST_TIMEOUT await asyncio.wait_for(connection.close(), timeout=LIMIT) diff --git a/packages/genkit-mcp/tests/mcp_tools_test.py b/packages/genkit-mcp/tests/mcp_tools_test.py index 2b6c08726..d9b2c768a 100644 --- a/packages/genkit-mcp/tests/mcp_tools_test.py +++ b/packages/genkit-mcp/tests/mcp_tools_test.py @@ -16,7 +16,7 @@ """Unit tests for MCP tool result translation.""" -from typing import Any +from typing import Any, TypeVar import pytest from genkit_mcp._errors import _ConnectionFailedError, _ToolResultError @@ -40,12 +40,19 @@ TextResourceContents, Tool, ) -from pydantic import AnyUrl +from pydantic import BaseModel from structlog.testing import capture_logs from genkit import MultipartToolResponse, Part from genkit.plugin_api import Action +ModelT = TypeVar('ModelT', bound=BaseModel) + + +def wire(model: type[ModelT], **fields: object) -> ModelT: + """Build an MCP type from its wire field names, which mcp 1.x and 2.x both parse.""" + return model.model_validate(fields) + def text(value: str) -> TextContent: return TextContent(type='text', text=value) @@ -69,26 +76,28 @@ def server_tool_of(action: Action) -> object: (CallToolResult(content=[text('true')]), 'true', None, None), (CallToolResult(content=[text('null')]), 'null', None, None), ( - CallToolResult(content=[text('ignored')], structuredContent={'answer': 'structured'}), + wire(CallToolResult, content=[text('ignored')], structuredContent={'answer': 'structured'}), {'answer': 'structured'}, None, None, ), ( - CallToolResult( - content=[text('bad'), ImageContent(type='image', mimeType='image/png', data='abc')], + wire( + CallToolResult, + content=[text('bad'), wire(ImageContent, type='image', mimeType='image/png', data='abc')], isError=True, - _meta={'requestId': 'r1'}, # ty: ignore[unknown-argument] + _meta={'requestId': 'r1'}, ), {'error': 'bad'}, None, {'requestId': 'r1', 'isError': True}, ), ( - CallToolResult( + wire( + CallToolResult, content=[text('bad')], isError=True, - _meta={'isError': False}, # ty: ignore[unknown-argument] + _meta={'isError': False}, ), {'error': 'bad'}, None, @@ -111,10 +120,11 @@ def test_call_result_to_multipart_text_and_errors( def test_call_result_to_multipart_error_flag_is_top_level_and_keeps_server_mcp_meta() -> None: """The error flag sits beside the server's _meta keys, so a server's own mcp key survives.""" - result = CallToolResult( + result = wire( + CallToolResult, content=[text('bad')], isError=True, - _meta={'mcp': {'trace': 't1'}}, # ty: ignore[unknown-argument] + _meta={'mcp': {'trace': 't1'}}, ) response = call_result_to_multipart(result) @@ -139,16 +149,17 @@ def test_call_result_to_multipart_maps_multipart_content_and_meta() -> None: result = CallToolResult( content=[ text('before'), - ImageContent(type='image', mimeType='image/png', data='image-data'), - AudioContent(type='audio', mimeType='audio/mpeg', data='audio-data'), + wire(ImageContent, type='image', mimeType='image/png', data='image-data'), + wire(AudioContent, type='audio', mimeType='audio/mpeg', data='audio-data'), EmbeddedResource( type='resource', - resource=TextResourceContents(uri=AnyUrl('file:///note.txt'), mimeType='text/plain', text='note'), + resource=wire(TextResourceContents, uri='file:///note.txt', mimeType='text/plain', text='note'), ), EmbeddedResource( type='resource', - resource=BlobResourceContents( - uri=AnyUrl('file:///data.pdf'), + resource=wire( + BlobResourceContents, + uri='file:///data.pdf', mimeType='application/pdf', blob='blob-data', ), @@ -156,7 +167,7 @@ def test_call_result_to_multipart_maps_multipart_content_and_meta() -> None: ResourceLink( type='resource_link', name='documentation', - uri=AnyUrl('https://example.test/docs'), + uri='https://example.test/docs', ), ], _meta={'trace': 'mcp-1'}, # ty: ignore[unknown-argument] @@ -179,7 +190,7 @@ def test_call_result_to_multipart_skips_resource_link() -> None: link = ResourceLink( type='resource_link', name='docs', - uri=AnyUrl('https://example.test/docs'), + uri='https://example.test/docs', ) standalone = call_result_to_multipart(CallToolResult(content=[link])) @@ -191,7 +202,7 @@ def test_call_result_to_multipart_skips_resource_link() -> None: def test_call_result_to_multipart_labels_a_blob_without_a_mime_type_as_octet_stream() -> None: result = CallToolResult( - content=[EmbeddedResource(type='resource', resource=BlobResourceContents(uri=AnyUrl('file:///x'), blob='YQ=='))] + content=[EmbeddedResource(type='resource', resource=BlobResourceContents(uri='file:///x', blob='YQ=='))] ) response = call_result_to_multipart(result) @@ -208,11 +219,12 @@ async def test_mcp_tool_to_action_preserves_schema_metadata_and_context_meta() - '$ref': '#/$defs/Lookup', '$defs': {'Lookup': {'properties': {'q': {'type': 'string'}}}}, } - tool = Tool( + tool = wire( + Tool, name='lookup', description='Find a record.', inputSchema=awkward_schema, - _meta={'audience': 'internal'}, # ty: ignore[unknown-argument] + _meta={'audience': 'internal'}, ) calls: list[tuple[str, dict[str, Any], dict[str, Any] | None]] = [] @@ -235,7 +247,7 @@ async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None @pytest.mark.asyncio async def test_mcp_tool_to_action_folds_a_tool_result_error_into_an_error_envelope() -> None: """A result which violates the tool's output schema is a tool error the model can retry.""" - tool = Tool(name='lookup', inputSchema={'type': 'object'}) + tool = wire(Tool, name='lookup', inputSchema={'type': 'object'}) async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None) -> CallToolResult: # noqa: ARG001 raise _ToolResultError('MCP output did not match the declared schema') @@ -251,7 +263,7 @@ async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None @pytest.mark.asyncio async def test_mcp_tool_to_action_lets_a_runtime_error_through() -> None: """A bare RuntimeError is infrastructure failing, not a result the model should retry.""" - tool = Tool(name='lookup', inputSchema={'type': 'object'}) + tool = wire(Tool, name='lookup', inputSchema={'type': 'object'}) async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None) -> CallToolResult: # noqa: ARG001 raise RuntimeError('Event loop is closed') @@ -267,7 +279,7 @@ async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None @pytest.mark.asyncio async def test_mcp_tool_to_action_lets_a_connection_failure_through() -> None: """A dead connection is not a tool error: the model must not retry against it.""" - tool = Tool(name='lookup', inputSchema={'type': 'object'}) + tool = wire(Tool, name='lookup', inputSchema={'type': 'object'}) async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None) -> CallToolResult: # noqa: ARG001 raise _ConnectionFailedError("MCP connection to 'npx' failed") @@ -348,7 +360,7 @@ async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None return CallToolResult(content=[text('ok')]) with capture_logs() as logs: - action = mcp_tool_to_action(Tool(name=tool_name, inputSchema={'type': 'object'}), 'catalog', call) + action = mcp_tool_to_action(wire(Tool, name=tool_name, inputSchema={'type': 'object'}), 'catalog', call) await action.run({}) assert action.name == 'catalog_' + tool_name.replace('.', '_').replace('/', '_') @@ -365,7 +377,7 @@ def test_mcp_tool_to_action_warns_about_a_name_longer_than_a_model_accepts() -> tool_name = 'a' * 64 with capture_logs() as logs: - action = mcp_tool_to_action(Tool(name=tool_name, inputSchema={'type': 'object'}), 'catalog', no_content) + action = mcp_tool_to_action(wire(Tool, name=tool_name, inputSchema={'type': 'object'}), 'catalog', no_content) assert action.name == f'catalog_{tool_name}' assert [entry['log_level'] for entry in logs] == ['warning'] @@ -373,7 +385,10 @@ def test_mcp_tool_to_action_warns_about_a_name_longer_than_a_model_accepts() -> def test_mcp_tools_to_actions_maps_a_listing_in_order() -> None: - tools = [Tool(name='lookup', inputSchema={'type': 'object'}), Tool(name='look.up', inputSchema={'type': 'object'})] + tools = [ + wire(Tool, name='lookup', inputSchema={'type': 'object'}), + wire(Tool, name='look.up', inputSchema={'type': 'object'}), + ] actions = mcp_tools_to_actions(tools, 'catalog', no_content) @@ -386,8 +401,8 @@ async def test_mcp_tools_to_handles_wraps_each_action_with_the_server_output_sch """A handle carries the Genkit name, the server's output schema, and runs the tool.""" output_schema: dict[str, Any] = {'type': 'object', 'properties': {'hits': {'type': 'integer'}}} tools = [ - Tool(name='lookup', inputSchema={'type': 'object'}, outputSchema=output_schema), - Tool(name='look.up', inputSchema={'type': 'object'}), + wire(Tool, name='lookup', inputSchema={'type': 'object'}, outputSchema=output_schema), + wire(Tool, name='look.up', inputSchema={'type': 'object'}), ] async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None) -> CallToolResult: @@ -409,8 +424,8 @@ def test_mcp_tool_handle_exposes_output_schema_on_definition() -> None: 'required': ['temperature_c'], } tools = [ - Tool(name='sensor_reading', inputSchema={'type': 'object'}, outputSchema=output_schema), - Tool(name='ping', inputSchema={'type': 'object'}), + wire(Tool, name='sensor_reading', inputSchema={'type': 'object'}, outputSchema=output_schema), + wire(Tool, name='ping', inputSchema={'type': 'object'}), ] handles = mcp_tools_to_handles(tools, 'lab', no_content) @@ -425,7 +440,7 @@ def test_mcp_tool_handle_exposes_output_schema_on_definition() -> None: ) def test_mcp_tools_to_actions_skips_tools_which_share_a_genkit_name(colliding: list[str], genkit_name: str) -> None: """Server tools which would answer to one Genkit name are left out; the rest of the listing survives.""" - tools = [Tool(name=name, inputSchema={'type': 'object'}) for name in [colliding[0], 'other', colliding[1]]] + tools = [wire(Tool, name=name, inputSchema={'type': 'object'}) for name in [colliding[0], 'other', colliding[1]]] with capture_logs() as logs: actions = mcp_tools_to_actions(tools, 'catalog', no_content) diff --git a/samples/mcp-hello/pyproject.toml b/samples/mcp-hello/pyproject.toml index f51adae1f..bba9c72e7 100644 --- a/samples/mcp-hello/pyproject.toml +++ b/samples/mcp-hello/pyproject.toml @@ -6,7 +6,7 @@ dependencies = [ "genkit", "genkit-google-genai", "genkit-mcp", - "mcp>=1.26.0,<2", + "mcp>=2,<3", ] [build-system] diff --git a/samples/mcp-hello/src/bookshop_server.py b/samples/mcp-hello/src/bookshop_server.py index ed5f67de8..440f0f2b0 100644 --- a/samples/mcp-hello/src/bookshop_server.py +++ b/samples/mcp-hello/src/bookshop_server.py @@ -21,13 +21,13 @@ as a child process. """ -from mcp.server.fastmcp import FastMCP +from mcp.server.mcpserver import MCPServer # The name a client sees during initialization. It is not what Genkit names the # tools after, which is why it reads nothing like the prefix on them. # A server logs to stderr, which is the sample's own terminal; INFO would print # a line per request over the sample's output. -mcp = FastMCP('Corner Bookshop', log_level='WARNING') +mcp = MCPServer('Corner Bookshop', log_level='WARNING') CATALOGUE = [ {'title': 'The Left Hand of Darkness', 'author': 'Ursula K. Le Guin', 'topic': 'science fiction'}, diff --git a/uv.lock b/uv.lock index b9c6bde41..03d69b1e8 100644 --- a/uv.lock +++ b/uv.lock @@ -1879,7 +1879,7 @@ requires-dist = [ { name = "anyio", specifier = ">=4.9.0" }, { name = "exceptiongroup", marker = "python_full_version < '3.11'", specifier = ">=1.2.0" }, { name = "genkit", editable = "packages/genkit" }, - { name = "mcp", specifier = ">=1.26.0,<2" }, + { name = "mcp", specifier = ">=1.26.0,<3" }, { name = "pydantic", specifier = ">=2.10.5" }, ] @@ -2650,6 +2650,42 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, ] +[[package]] +name = "httpcore2" +version = "2.14.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "h11", marker = "python_full_version < '3.11'" }, + { name = "truststore", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/30/ff/b53af1b49bb2cb5fa97c92215614b173ca5c1a99ded80e2d52f15a94fa6d/httpcore2-2.14.0.tar.gz", hash = "sha256:4f57a1a8249fe6af589d935cfd456f1d13bbdcb0f0fc72af9142368fc94811d7", size = 69096, upload-time = "2026-10-18T16:29:21.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/06/a8d6a8f90d11b76d9086242b6bb0ee4b503473bfc8be34c2d5b067275c22/httpcore2-2.14.0-py3-none-any.whl", hash = "sha256:4c4f64f4b544afeb778c42c0ffb5941b29e671157e90ed3f6dc787c4bca90cd1", size = 84291, upload-time = "2026-10-18T16:29:19.743Z" }, +] + +[[package]] +name = "httpcore2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14'", + "python_full_version == '3.13.*'", + "python_full_version == '3.12.*'", + "python_full_version >= '3.11.5' and python_full_version < '3.12'", + "python_full_version >= '3.11' and python_full_version < '3.11.5'", +] +dependencies = [ + { name = "h11", marker = "python_full_version >= '3.11'" }, + { name = "truststore", marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" }, +] + [[package]] name = "httptools" version = "0.7.1" @@ -2709,12 +2745,55 @@ wheels = [ ] [[package]] -name = "httpx-sse" -version = "0.4.3" +name = "httpx2" +version = "2.14.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "anyio", marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" }, + { name = "httpcore2", version = "2.14.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" }, + { name = "idna", marker = "python_full_version < '3.11'" }, + { name = "truststore", marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e8/67/58353f1848b4ba568e1ec22ea1e0d8e039f0bca5fde7e2d1f07739fd83e7/httpx2-2.14.0.tar.gz", hash = "sha256:47ad61a3c40282cd8d0dc96311531f00f5bfc71a066c6fe3b36d8f63fb9e4f6e", size = 102036, upload-time = "2026-10-18T16:29:22.627Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/5a/469616aa8c2cbb0bb9dd67a3c18d07c01ab604cc0b236ee1c47d260c7f6e/httpx2-2.14.0-py3-none-any.whl", hash = "sha256:9d20c13a10bae1773a0be3b0f1e5beeb4bdd549bc3a2ba18efa32897c65403e4", size = 96901, upload-time = "2026-10-18T16:29:20.819Z" }, +] + +[[package]] +name = "httpx2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14'", + "python_full_version == '3.13.*'", + "python_full_version == '3.12.*'", + "python_full_version >= '3.11.5' and python_full_version < '3.12'", + "python_full_version >= '3.11' and python_full_version < '3.11.5'", +] +dependencies = [ + { name = "anyio", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, + { name = "httpcore2", version = "2.16.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" }, + { name = "idna", marker = "python_full_version >= '3.11'" }, + { name = "truststore", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "python_full_version >= '3.11' and python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0f/4c/751061ffa58615a32c31b2d82e8482be8dd4a89154f003147acee90f2be9/httpx_sse-0.4.3.tar.gz", hash = "sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d", size = 15943, upload-time = "2025-10-10T21:48:22.271Z" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" }, + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, ] [[package]] @@ -2768,11 +2847,11 @@ wheels = [ [[package]] name = "idna" -version = "3.11" +version = "3.20" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/0703ccc57f3a7233505399edb88de3cbd678da106337b9fcde432b65ed60/idna-3.11.tar.gz", hash = "sha256:795dafcc9c04ed0c1fb032c2aa73654d8e8c5023a7df64a53f39190ada629902", size = 194582, upload-time = "2025-10-12T14:55:20.501Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" }, + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, ] [[package]] @@ -3714,15 +3793,16 @@ wheels = [ [[package]] name = "mcp" -version = "1.26.0" +version = "2.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "httpx" }, - { name = "httpx-sse" }, + { name = "httpx2", version = "2.14.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "httpx2", version = "2.16.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "jsonschema" }, + { name = "mcp-types" }, + { name = "opentelemetry-api" }, { name = "pydantic" }, - { name = "pydantic-settings" }, { name = "pyjwt", extra = ["crypto"] }, { name = "python-multipart" }, { name = "pywin32", marker = "sys_platform == 'win32'" }, @@ -3732,9 +3812,9 @@ dependencies = [ { name = "typing-inspection" }, { name = "uvicorn", marker = "sys_platform != 'emscripten'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fc/6d/62e76bbb8144d6ed86e202b5edd8a4cb631e7c8130f3f4893c3f90262b10/mcp-1.26.0.tar.gz", hash = "sha256:db6e2ef491eecc1a0d93711a76f28dec2e05999f93afd48795da1c1137142c66", size = 608005, upload-time = "2026-01-24T19:40:32.468Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/8d/e0d339616f4810e9051d4aba6887afab289ab1f81875fe908b606cdfd0e3/mcp-2.3.0.tar.gz", hash = "sha256:8b147a50441cf059dc88c684e0aeed3687f0aa0f39c6cde7b90330effd2b34d8", size = 4171955, upload-time = "2026-10-02T22:06:56.091Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fd/d9/eaa1f80170d2b7c5ba23f3b59f766f3a0bb41155fbc32a69adfa1adaaef9/mcp-1.26.0-py3-none-any.whl", hash = "sha256:904a21c33c25aa98ddbeb47273033c435e595bbacfdb177f4bd87f6dceebe1ca", size = 233615, upload-time = "2026-01-24T19:40:30.652Z" }, + { url = "https://files.pythonhosted.org/packages/20/d7/4a2878f128df729db3ca04e71bfce26405cc2e0c9ebe19c592feeb4c61b9/mcp-2.3.0-py3-none-any.whl", hash = "sha256:dd0c44c089d16453e8ae31a3877a0054d7a2314caaa81f5e0541b9b1734b2377", size = 368664, upload-time = "2026-10-02T22:06:52.119Z" }, ] [[package]] @@ -3753,7 +3833,20 @@ requires-dist = [ { name = "genkit", editable = "packages/genkit" }, { name = "genkit-google-genai", editable = "packages/genkit-google-genai" }, { name = "genkit-mcp", editable = "packages/genkit-mcp" }, - { name = "mcp", specifier = ">=1.26.0,<2" }, + { name = "mcp", specifier = ">=2,<3" }, +] + +[[package]] +name = "mcp-types" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/2d/7c251e34207f6c51000312fc8839111ac45cfe02023f90b44e7f1051dd8e/mcp_types-2.3.0.tar.gz", hash = "sha256:d1e46549edb35ee19a94940fcee6d1addd7e589ab7ea92dda83f5d84781fc362", size = 65898, upload-time = "2026-10-02T22:06:57.863Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ce/48/32583066b155bb5d4507e7887dc88ee23118cc4de8e2a12870c49719e2a8/mcp_types-2.3.0-py3-none-any.whl", hash = "sha256:968efdbdaedfab06adae40d378a34395f1090c5921d4be3c9cde283aaf76d91d", size = 69108, upload-time = "2026-10-02T22:06:54.099Z" }, ] [[package]] @@ -5730,20 +5823,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/c7/cfc8e811f061c841d7990b0201912c3556bfeb99cdcb7ed24adc8d6f8704/pydantic_core-2.41.5-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:56121965f7a4dc965bff783d70b907ddf3d57f6eba29b6d2e5dabfaf07799c51", size = 2145302, upload-time = "2025-11-04T13:43:46.64Z" }, ] -[[package]] -name = "pydantic-settings" -version = "2.12.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pydantic" }, - { name = "python-dotenv" }, - { name = "typing-inspection" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/43/4b/ac7e0aae12027748076d72a8764ff1c9d82ca75a7a52622e67ed3f765c54/pydantic_settings-2.12.0.tar.gz", hash = "sha256:005538ef951e3c2a68e1c08b292b5f2e71490def8589d4221b95dab00dafcfd0", size = 194184, upload-time = "2025-11-10T14:25:47.013Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl", hash = "sha256:fddb9fd99a5b18da837b29710391e945b1e30c135477f484084ee513adb93809", size = 51880, upload-time = "2025-11-10T14:25:45.546Z" }, -] - [[package]] name = "pydeck" version = "0.9.1" @@ -7056,6 +7135,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/00/c0/8f5d070730d7836adc9c9b6408dec68c6ced86b304a9b26a14df072a6e8c/traitlets-5.14.3-py3-none-any.whl", hash = "sha256:b74e89e397b1ed28cc831db7aea759ba6640cb3de13090ca145426688ff1ac4f", size = 85359, upload-time = "2024-04-19T11:11:46.763Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "twine" version = "7.0.0"