From 8ab549780e9bacb7804a24eae78721e0246f5182 Mon Sep 17 00:00:00 2001 From: Jacob Cable Date: Mon, 21 Sep 2026 10:04:54 +0100 Subject: [PATCH 1/8] feat(py/plugins/mcp): serve Genkit tools over MCP stdio Python can call an MCP server but cannot be one. JS and Go both ship a server, and #6397 tracks the Python one. create_mcp_server builds over a Genkit app and registers nothing, so it is a create_ and not a define_, as JS has createMcpServer. The package exports McpServer, its return type, and create_mcp_server, its first public names. The lowlevel SDK Server is the base rather than FastMCP, whose tool list is filled at decoration time: a tool defined after the server was built would be missing from it. The lowlevel list handler runs per request and reads ai.list_tools(), so a late definition is served. Like JS and Go, the server serves every tool defined on the app; tools a dynamic action provider serves are not defined on the app and are not served. Listing and calling read the same pairs. A tool whose input schema is not an object cannot be described in MCP, whose arguments are always an object, so it is skipped from the listing and is not reachable by name either. An empty input schema, which core infers for a no-arg tool, becomes an object with no properties. pydantic describes a model that refers to itself as a top-level $ref, which is followed before the check, so such a tool is served. Each action's description is kept per action, so a skipped tool is warned about once, not on every request. outputSchema is advertised only for an object schema. The SDK rejects any unstructured result from a tool that declares one, so advertising a scalar schema would break every call to that tool. The schema comes from the originalOutputSchema metadata, since a tool.v2 action's own output schema is the envelope. The call handler never raises, including while it maps a result. A failure is logged in full and becomes an isError result. A GenkitError sends its status and message but not its cause's text; any other exception sends only "Tool '' failed". The result reaches a model and whoever reads its transcript, and an exception's text can carry a request URL with an API key or a database DSN. This is stricter than JS, which sends the full message. An unknown tool is an isError result too. Result mapping is built against the client's reader, so a tool re-exported through both keeps its output, media and metadata, and a client error envelope goes back out as an MCP error. MCP has one text channel and clients, ours and JS's, join every text block into the output, so a text part is sent only beside no output or an object output carried as structuredContent. Beside any other output it would change what the client reads back, so it is dropped with a warning. A media part whose URL is not absolute cannot be a resource link and is dropped with a warning rather than failing a call that succeeded. Only an object can be structuredContent, so everything else travels as JSON text, which the client parses back only when it starts with a brace or a bracket. Scalars therefore return as strings, lossy in the same way the JS plugin is. Binary content MCP has no block for becomes an embedded resource under a minted genkit:// URI, because the blob type requires one. start() captures the real stdout for the transport, then points sys.stdout at stderr, since stdout is the wire and structlog's default writes there. structlog's PrintLogger reads sys.stdout at call time, so this also moves a logger built earlier. redirect_stdout=False opts out. stdin and stdout are read and written as UTF-8 whatever the locale, as the SDK's own default does. stdin and stdout are wrapped with anyio, so anyio becomes a direct dependency. Upstream-Commit: genkit-ai/genkit@504c426f0 Upstream-PR: https://github.com/genkit-ai/genkit/pull/6882 --- packages/genkit-mcp/README.md | 78 ++++- packages/genkit-mcp/pyproject.toml | 2 +- .../genkit-mcp/src/genkit_mcp/__init__.py | 8 +- packages/genkit-mcp/src/genkit_mcp/_export.py | 244 ++++++++++++++ packages/genkit-mcp/src/genkit_mcp/_server.py | 236 ++++++++++++++ packages/genkit-mcp/tests/mcp_export_test.py | 289 +++++++++++++++++ packages/genkit-mcp/tests/mcp_exports_test.py | 9 +- packages/genkit-mcp/tests/mcp_server_test.py | 307 ++++++++++++++++++ 8 files changed, 1165 insertions(+), 8 deletions(-) create mode 100644 packages/genkit-mcp/src/genkit_mcp/_export.py create mode 100644 packages/genkit-mcp/src/genkit_mcp/_server.py create mode 100644 packages/genkit-mcp/tests/mcp_export_test.py create mode 100644 packages/genkit-mcp/tests/mcp_server_test.py diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index edad9de81..d23bdc40e 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -1,9 +1,11 @@ -# Genkit MCP Client +# Genkit MCP Connects Genkit to a [Model Context Protocol](https://modelcontextprotocol.io) server over stdio and -exposes that server's tools as Genkit `tool` actions through a dynamic action provider. +exposes that server's tools as Genkit `tool` actions through a dynamic action provider. It also +serves a Genkit app's own tools to MCP clients. -Tracking issue: +Tracking issues: (client), + (server) ## Usage @@ -160,3 +162,73 @@ status `FAILED_PRECONDITION`, so define a new host to use those servers again. One provider means one listing. A tool call that fails on one server drops the listing for all of them, so the next `generate` lists every server again. + +## Serving your app as an MCP server + +`create_mcp_server` wraps a `Genkit` instance and registers nothing, so the tools it serves are the +ones the app already has: + +```python +import asyncio + +from genkit import Genkit +from genkit_mcp import create_mcp_server +from pydantic import BaseModel + +HOURS = {'saturday': '9am to 6pm', 'sunday': 'closed'} + +ai = Genkit() + + +class Day(BaseModel): + name: str + + +@ai.tool() +async def opening_hours(day: Day) -> str: + """Report the shop's opening hours for a day of the week.""" + return HOURS.get(day.name.lower(), '10am to 7pm') + + +server = create_mcp_server(ai, 'bookshop', instructions='Ask about the shop.') + +if __name__ == '__main__': + asyncio.run(server.start()) +``` + +The app's tools are read with `ai.list_tools()` on every `tools/list`, so a tool defined after the +server was built is still served. A tool whose input is not an object, such as a single scalar or an +optional model, is skipped: MCP arguments are always an object, and such a tool is not callable by +name either, rather than being listed and then failing. A model that refers to itself is served. An output schema is advertised only when it describes an object, since anything else +cannot be structured content. Tools a dynamic action provider supplies, from `define_mcp_client` +for instance, are not defined on the app and are not served. + +A tool that raises answers with an error result. A `GenkitError` (including `PublicError`) sends its +status and message, without the text of its cause. Any other exception sends only `Tool '' +failed`, since its text can carry a URL or a credential. The full error is logged on the server +either way, so raise a `GenkitError` for a failure the model should read and retry. + +### stdio + +`await server.start()` serves on this process's stdin and stdout until stdin closes. stdout is the +wire, so `start()` captures the real one for the transport and then points `sys.stdout` at stderr +for the rest of the process's life, because structlog's builtin default writes to stdout and one +stray line corrupts a JSON-RPC frame. A logging configuration your app chose for itself is left +alone, and a logger built before `start()` keeps the descriptor it captured. Pass +`redirect_stdout=False` to opt out. + +`await server.serve(read_stream, write_stream)` serves on any SDK stream pair instead, and touches +nothing. + +## Known gaps + +Scalar outputs and strings that look like JSON do not round-trip exactly. Clients join every text +block into the output, so a text content part is sent only beside no output or an object output, and +is dropped with a warning otherwise. A media part whose URL is not absolute is dropped with a +warning. A tool whose input is not an object is not served at all, +and an output schema that is not an object is not advertised, so a client is told less about such a +tool than Genkit knows. Nothing sends `notifications/tools/list_changed`; the list is re-read per +request instead. Progress, cancellation, sampling and elicitation are not supported. A +plugin-namespaced tool name carries a `/`, which the MCP SDK warns about. Whatever the app logs +before `start()` runs is on stdout, which that call is too late to have redirected. stdio reads and +writes UTF-8 whatever the locale, but is untested on Windows. diff --git a/packages/genkit-mcp/pyproject.toml b/packages/genkit-mcp/pyproject.toml index eae910327..17437e89d 100644 --- a/packages/genkit-mcp/pyproject.toml +++ b/packages/genkit-mcp/pyproject.toml @@ -45,7 +45,7 @@ dependencies = [ "mcp>=1.26.0,<2", "pydantic>=2.10.5", ] -description = "Model Context Protocol client for Genkit. Exposes an MCP server's tools as Genkit tools." +description = "Model Context Protocol for Genkit. Exposes MCP servers' tools as Genkit tools and serves Genkit tools over MCP." keywords = [ "genkit", "mcp", diff --git a/packages/genkit-mcp/src/genkit_mcp/__init__.py b/packages/genkit-mcp/src/genkit_mcp/__init__.py index 23ff50d55..539bdc778 100644 --- a/packages/genkit-mcp/src/genkit_mcp/__init__.py +++ b/packages/genkit-mcp/src/genkit_mcp/__init__.py @@ -14,12 +14,14 @@ # # SPDX-License-Identifier: Apache-2.0 -"""Model Context Protocol client for Genkit. +"""Model Context Protocol for Genkit. -Exposes the tools of one or more stdio MCP servers as Genkit ``tool`` actions. +Exposes the tools of one or more stdio MCP servers as Genkit ``tool`` actions, +and serves a Genkit app's own tools to MCP clients. """ from genkit_mcp._client import McpClient, define_mcp_client from genkit_mcp._host import McpHost, define_mcp_host +from genkit_mcp._server import McpServer, create_mcp_server -__all__ = ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] +__all__ = ['McpClient', 'McpHost', 'McpServer', 'create_mcp_server', 'define_mcp_client', 'define_mcp_host'] diff --git a/packages/genkit-mcp/src/genkit_mcp/_export.py b/packages/genkit-mcp/src/genkit_mcp/_export.py new file mode 100644 index 000000000..c4b04d274 --- /dev/null +++ b/packages/genkit-mcp/src/genkit_mcp/_export.py @@ -0,0 +1,244 @@ +# 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 +# +# SPDX-License-Identifier: Apache-2.0 + +"""Translation of Genkit tools and their results into MCP shapes.""" + +import json +import re +from typing import Any + +from mcp.types import ( + AudioContent, + BlobResourceContents, + CallToolResult, + ContentBlock, + EmbeddedResource, + ImageContent, + ResourceLink, + TextContent, + Tool as McpTool, +) +from pydantic import AnyUrl + +from genkit import MultipartToolResponse, Part, Tool, get_logger + +logger = get_logger(__name__) + +_DATA_URL = re.compile(r'^data:(?P[^;,]+);base64,(?P.*)$', re.DOTALL) + +EMPTY_OBJECT_SCHEMA: dict[str, Any] = {'type': 'object', 'properties': {}} +"""What a no-arg tool advertises, since MCP arguments are always an object.""" + + +def tool_to_mcp(tool: Tool) -> McpTool | None: + """Describe one Genkit tool as an MCP tool. + + Args: + tool: A tool registered on the app. + + Returns: + The MCP tool description, or ``None`` when the action's input is not an + object, which MCP cannot express. + """ + input_schema = _object_schema(dict(tool.input_schema or {})) + if input_schema is None: + logger.warning( + 'skipping a tool whose input is not an object, which MCP arguments cannot express', + tool=tool.name, + input_type=(tool.input_schema or {}).get('type'), + ) + return None + + return McpTool( + name=tool.name, + description=tool.description, + inputSchema=input_schema, + outputSchema=_output_schema(tool), + _meta=_tool_meta(tool), # ty: ignore[unknown-argument] + ) + + +def multipart_to_call_result(response: MultipartToolResponse, tool_name: str) -> CallToolResult: + """Convert what a Genkit tool returned into an MCP call result. + + MCP has one text channel, and clients join every text block into the + output. A text part is therefore sent only when that cannot change the + output a client reads back: when there is no output, or when the output is + an object carried as ``structuredContent``. Otherwise it is dropped with a + warning. + + Args: + response: The envelope a ``tool.v2`` action returned. + tool_name: Name of the tool, used to mint a URI for binary content that + has no URI of its own. + + Returns: + The result to send back over MCP. + """ + metadata = dict(response.metadata) if response.metadata else {} + if metadata.get('isError') is True: + return error_result(_error_text(response.output), meta=_without_error_flag(metadata)) + + output = response.output + structured = _as_object(output) if isinstance(output, dict) else None + content: list[ContentBlock] = [] + if output is not None: + content.append(TextContent(type='text', text=_output_text(output))) + for index, part in enumerate(response.content or []): + if part.text is not None and output is not None and structured is None: + logger.warning('dropping a text part that would change the text output', tool=tool_name, index=index) + continue + block = _part_to_block(part, tool_name, index) + if block is not None: + content.append(block) + + return CallToolResult( + content=content, + structuredContent=structured, + _meta=metadata or None, # ty: ignore[unknown-argument] + ) + + +def error_result(message: str, meta: dict[str, Any] | None = None) -> CallToolResult: + """Build an MCP error result carrying one message. + + Args: + message: What the model reads. Never a trace id or a stack trace. + meta: Optional ``_meta`` to carry alongside. + + Returns: + A result the client folds into an ``error`` output. + """ + return CallToolResult( + content=[TextContent(type='text', text=message)], + isError=True, + _meta=meta or None, # ty: ignore[unknown-argument] + ) + + +def _as_object(value: object) -> dict[str, Any]: + """Read a metadata value that should be a nested object, or nothing.""" + if not isinstance(value, dict): + return {} + return {str(key): item for key, item in value.items()} + + +def _object_schema(schema: dict[str, Any]) -> dict[str, Any] | None: + """Return the schema as an object schema MCP arguments can use, or ``None``. + + pydantic describes a model that refers to itself as a top-level ``$ref`` + into ``$defs``, so that reference is followed first. + """ + if not schema: + return dict(EMPTY_OBJECT_SCHEMA) + ref = schema.get('$ref') + if isinstance(ref, str) and ref.startswith('#/$defs/'): + defs = _as_object(schema.get('$defs')) + target = _as_object(defs.get(ref.removeprefix('#/$defs/'))) + rest = {key: value for key, value in schema.items() if key != '$ref'} + schema = {**rest, **target} + if schema.get('type') == 'object': + return schema + if 'type' not in schema and isinstance(schema.get('properties'), dict): + return {**schema, 'type': 'object'} + return None + + +def _output_schema(tool: Tool) -> dict[str, Any] | None: + """Read the model-facing output schema, kept only when MCP can carry it. + + The SDK rejects any unstructured result for a tool that declares an output + schema, and ``structuredContent`` is an object, so a non-object schema is + dropped rather than advertised. + """ + original = _as_object(tool.model_output_schema) + return original if original.get('type') == 'object' else None + + +def _tool_meta(tool: Tool) -> dict[str, Any] | None: + """Read the MCP ``_meta`` a re-exported client tool carries from its origin.""" + meta = _as_object(_as_object(tool.metadata.get('mcp')).get('_meta')) + return meta or None + + +def _without_error_flag(metadata: dict[str, Any]) -> dict[str, Any] | None: + """Drop the flag the client adds on the way in, since ``isError`` already carries it.""" + rest = {key: value for key, value in metadata.items() if key != 'isError'} + return rest or None + + +def _error_text(output: object) -> str: + """Read the message out of the ``{'error': text}`` shape the client produces.""" + error = _as_object(output).get('error') + return error if isinstance(error, str) else _output_text(output) + + +def _output_text(output: object) -> str: + """Render tool output as the text half of a result. + + A string travels as itself. Everything else is JSON, which the client parses + back only when it begins with ``{`` or ``[``, so scalars return as strings. + """ + if isinstance(output, str): + return output + return json.dumps(output) + + +def _part_to_block(part: Part, tool_name: str, index: int) -> ContentBlock | None: + """Convert one Genkit content part into an MCP content block.""" + if part.text is not None: + return TextContent(type='text', text=part.text) + + if part.media is not None: + url = part.media.url + match = _DATA_URL.match(url) + if match is None: + uri = _absolute_url(url, tool_name, index) + if uri is None: + return None + return ResourceLink(type='resource_link', uri=uri, name=url, mimeType=part.media.content_type) + mime_type = match.group('mime') + data = match.group('data') + if mime_type.startswith('image/'): + return ImageContent(type='image', mimeType=mime_type, data=data) + if mime_type.startswith('audio/'): + return AudioContent(type='audio', mimeType=mime_type, data=data) + return _blob_block(tool_name, index, mime_type, data) + + if part.resource is not None: + url = str(part.resource.uri) + uri = _absolute_url(url, tool_name, index) + if uri is None: + return None + return ResourceLink(type='resource_link', uri=uri, name=url) + + logger.warning('dropping a tool content part MCP has no block for', tool=tool_name, index=index) + return None + + +def _absolute_url(url: str, tool_name: str, index: int) -> AnyUrl | None: + """Parse a URL a resource link can carry, or warn and return ``None``.""" + try: + return AnyUrl(url) + except ValueError: + logger.warning('dropping a tool content part whose URL is not absolute', tool=tool_name, index=index) + return None + + +def _blob_block(tool_name: str, index: int, mime_type: str, data: str) -> ContentBlock: + """Wrap binary content MCP has no dedicated block for, minting the URI the type requires.""" + return EmbeddedResource( + type='resource', + resource=BlobResourceContents( + uri=AnyUrl(f'genkit://tool/{tool_name}/content/{index}'), + mimeType=mime_type, + blob=data, + ), + ) diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py new file mode 100644 index 000000000..c32aee449 --- /dev/null +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -0,0 +1,236 @@ +# 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 +# +# SPDX-License-Identifier: Apache-2.0 + +"""A Genkit app served to MCP clients as an MCP server.""" + +import sys +from io import TextIOWrapper +from typing import Any +from weakref import WeakKeyDictionary + +import anyio +from mcp.server.lowlevel import Server +from mcp.server.stdio import stdio_server +from mcp.types import CallToolResult, Tool as McpTool +from pydantic import TypeAdapter + +from genkit import Genkit, GenkitError, MultipartToolResponse, Tool, get_logger +from genkit_mcp._export import error_result, multipart_to_call_result, tool_to_mcp + +logger = get_logger(__name__) + +_JSON = TypeAdapter(object) + +DEFAULT_VERSION = '1.0.0' +"""What JS and Go both advertise when the app names no version.""" + + +class McpServer: + """Serves a Genkit app's tools to MCP clients. + + Tools are read from the app on every ``tools/list``, so a tool defined + after the server was built is still served. Tools a dynamic action + provider serves are not. + + Attributes: + name: Name the server advertises to clients. + version: Version the server advertises to clients. + """ + + def __init__( + self, + ai: Genkit, + name: str, + *, + version: str = DEFAULT_VERSION, + instructions: str | None = None, + redirect_stdout: bool = True, + ) -> None: + """Build a server over a Genkit app. + + Args: + ai: The app whose tools are served. + name: Name the server advertises. + version: Version the server advertises. + instructions: How a client should use this server. + redirect_stdout: Whether ``start`` moves this process's stdout to + stderr. Leave it on unless the app already keeps stdout clear. + """ + self._ai = ai + self._name = name + self._version = version + self._redirect_stdout = redirect_stdout + self._described: WeakKeyDictionary[Tool, McpTool | None] = WeakKeyDictionary() + self._server: Server[Any, Any] = Server(name, version=version, instructions=instructions) + self._server.list_tools()(self._list_tools) + self._server.call_tool()(self._call_tool) + + @property + def name(self) -> str: + """Name the server advertises to clients.""" + return self._name + + @property + def version(self) -> str: + """Version the server advertises to clients.""" + return self._version + + async def serve(self, read_stream: Any, write_stream: Any, *, raise_exceptions: bool = False) -> None: # noqa: ANN401 + """Serve on a stream pair until the client disconnects. + + Args: + read_stream: Where requests arrive, as the MCP SDK shapes it. + write_stream: Where responses go, as the MCP SDK shapes it. + raise_exceptions: Whether a handler error propagates instead of + becoming an error response. For tests. + """ + await self._server.run( + read_stream, + write_stream, + self._server.create_initialization_options(), + raise_exceptions=raise_exceptions, + ) + + async def start(self) -> None: + """Serve on this process's stdin and stdout until stdin closes. + + stdout is the wire, so it is captured before anything can write to it + and the process's own stdout is then pointed at stderr for the rest of + its life. A logger built before this call keeps the descriptor it + captured. + """ + streams = stdio_server( + stdin=anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding='utf-8')), + stdout=anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding='utf-8')), + ) + if self._redirect_stdout: + _redirect_stdout_to_stderr() + async with streams as (read_stream, write_stream): + await self.serve(read_stream, write_stream) + + async def _list_tools(self) -> list[McpTool]: + """Describe every tool this server offers, read fresh from the app.""" + return [described for _, described in await self._served_tools()] + + async def _served_tools(self) -> list[tuple[Tool, McpTool]]: + """Pair each tool this server serves with how it is described. + + Listing and calling read the same pairs, so a tool MCP cannot describe + is not reachable by name either. + """ + served: list[tuple[Tool, McpTool]] = [] + for tool in await self._ai.list_tools(): + if tool not in self._described: + self._described[tool] = tool_to_mcp(tool) + described = self._described[tool] + if described is not None: + served.append((tool, described)) + return served + + async def _call_tool(self, name: str, arguments: dict[str, Any]) -> CallToolResult: + """Run one tool and map what it returned, reporting every failure as a result. + + A raised error becomes an ``isError`` result and is logged here, where + its traceback is still useful. + """ + tool = await self._find_tool(name) + if tool is None: + return error_result(f'Tool {name!r} is not registered') + + context = self._request_context() + try: + return multipart_to_call_result(await _run(tool, arguments, context), name) + except Exception as error: + logger.exception('an MCP tool call failed', tool=name) + return error_result(_client_message(name, error)) + + def _request_context(self) -> dict[str, Any] | None: + """Pass the request's MCP ``_meta`` in the shape the client's handler reads.""" + try: + meta = self._server.request_context.meta + except LookupError: + return None + if meta is None: + return None + return {'mcp': {'_meta': meta.model_dump(by_alias=True, exclude_none=True)}} + + async def _find_tool(self, name: str) -> Tool | None: + """Find a tool by the name it was listed under.""" + for tool, described in await self._served_tools(): + if described.name == name: + return tool + return None + + +def create_mcp_server( + ai: Genkit, + name: str, + *, + version: str = DEFAULT_VERSION, + instructions: str | None = None, + redirect_stdout: bool = True, +) -> McpServer: + """Build a server over a Genkit app, registering nothing. + + Args: + ai: The app whose tools are served. + name: Name the server advertises. + version: Version the server advertises. + instructions: How a client should use this server. + redirect_stdout: Whether ``start`` moves this process's stdout to stderr. + + Returns: + A server ready for ``start`` or ``serve``. + """ + return McpServer( + ai, + name, + version=version, + instructions=instructions, + redirect_stdout=redirect_stdout, + ) + + +async def _run(tool: Tool, arguments: dict[str, Any], context: dict[str, Any] | None) -> MultipartToolResponse: + """Run a tool and return what it produced as a tool response envelope. + + A tool built as a ``Tool`` has a ``tool.v2`` action that returns the + envelope already. A plain tool action returns its function's value, which + becomes the envelope's output. + """ + wire = tool.wire_action + if wire is not None: + return (await wire.run(arguments, context=context)).response + output = (await tool.run(arguments, context=context)).response + if isinstance(output, MultipartToolResponse): + return output + return MultipartToolResponse(output=_JSON.dump_python(output, mode='json')) + + +def _client_message(tool_name: str, error: Exception) -> str: + """Say why a tool failed without passing on text the app never chose to show. + + A ``GenkitError`` keeps its status and message but not its cause's text, + which can carry a request URL or a credential. + """ + if isinstance(error, GenkitError): + return f'{error.status}: {error.message}' + return f'Tool {tool_name!r} failed' + + +def _redirect_stdout_to_stderr() -> None: + """Point this process's stdout at stderr, so nothing can corrupt the wire. + + Rebinding ``sys.stdout`` is enough to move a logger that was built before + this call: structlog's default ``PrintLogger`` passes ``file=None`` to + ``print``, which reads ``sys.stdout`` at call time. A logger bound to an + explicit stream is the app's own choice and is left where it points. + """ + sys.stdout = sys.stderr diff --git a/packages/genkit-mcp/tests/mcp_export_test.py b/packages/genkit-mcp/tests/mcp_export_test.py new file mode 100644 index 000000000..cb6d56dfa --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_export_test.py @@ -0,0 +1,289 @@ +# 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 +# +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for translating Genkit tools and results into MCP shapes.""" + +from typing import Any + +import pytest +from genkit_mcp._export import error_result, multipart_to_call_result, tool_to_mcp +from mcp.types import ( + AudioContent, + EmbeddedResource, + ImageContent, + ResourceLink, + TextContent, +) +from pydantic import AnyUrl, BaseModel +from structlog.testing import capture_logs + +from genkit import Genkit, MultipartToolResponse, Part + + +def media(url: str, content_type: str | None = None) -> Part: + return Part.from_media(url=url, content_type=content_type) + + +@pytest.mark.parametrize( + ('output', 'text', 'structured'), + [ + ('plain text', 'plain text', None), + ({'a': 1}, '{"a": 1}', {'a': 1}), + ([1, 'x'], '[1, "x"]', None), + (42, '42', None), + (True, 'true', None), + (None, None, None), + ], +) +def test_output_travels_as_text_and_only_a_dict_is_structured( + output: object, text: str | None, structured: dict[str, Any] | None +) -> None: + """Only an object can be structuredContent, so everything else is JSON text.""" + result = multipart_to_call_result(MultipartToolResponse(output=output), 'tool') + + assert [block.text for block in result.content if isinstance(block, TextContent)] == ([text] if text else []) + assert result.structuredContent == structured + assert result.isError in (False, None) + + +def test_an_image_data_url_becomes_image_content() -> None: + result = multipart_to_call_result( + MultipartToolResponse(output=None, content=[media('data:image/png;base64,aW1n', 'image/png')]), + 'tool', + ) + + assert result.content == [ImageContent(type='image', mimeType='image/png', data='aW1n')] + + +def test_an_audio_data_url_becomes_audio_content() -> None: + result = multipart_to_call_result( + MultipartToolResponse(output=None, content=[media('data:audio/mpeg;base64,c25k', 'audio/mpeg')]), + 'tool', + ) + + assert result.content == [AudioContent(type='audio', mimeType='audio/mpeg', data='c25k')] + + +def test_other_binary_content_becomes_an_embedded_resource_with_a_minted_uri() -> None: + """BlobResourceContents requires a uri, and Genkit media carries none.""" + result = multipart_to_call_result( + MultipartToolResponse(output=None, content=[media('data:application/pdf;base64,cGRm', 'application/pdf')]), + 'bookshop', + ) + + block = result.content[0] + assert isinstance(block, EmbeddedResource) + assert str(block.resource.uri) == 'genkit://tool/bookshop/content/0' + assert block.resource.mimeType == 'application/pdf' + + +def test_a_non_data_media_url_becomes_a_resource_link() -> None: + result = multipart_to_call_result( + MultipartToolResponse(output=None, content=[media('https://example.test/a.png', 'image/png')]), + 'tool', + ) + + assert result.content == [ + ResourceLink( + type='resource_link', + uri=AnyUrl('https://example.test/a.png'), + name='https://example.test/a.png', + mimeType='image/png', + ) + ] + + +def test_a_resource_part_becomes_a_resource_link() -> None: + result = multipart_to_call_result( + MultipartToolResponse(output=None, content=[Part.model_validate({'resource': {'uri': 'https://example.test/docs'}})]), + 'tool', + ) + + assert result.content == [ + ResourceLink(type='resource_link', uri=AnyUrl('https://example.test/docs'), name='https://example.test/docs') + ] + + +def test_a_text_part_follows_an_object_output() -> None: + """Clients read an object back from structuredContent, so the text part cannot change it.""" + result = multipart_to_call_result( + MultipartToolResponse(output={'a': 1}, content=[Part(text='note')]), + 'tool', + ) + + assert [block.text for block in result.content if isinstance(block, TextContent)] == ['{"a": 1}', 'note'] + + +@pytest.mark.parametrize('output', ['first', [1, 2], 42]) +def test_a_text_part_beside_a_non_object_output_is_dropped_with_a_warning(output: object) -> None: + """Clients join text blocks into the output, so sending the part would change it.""" + with capture_logs() as logs: + result = multipart_to_call_result(MultipartToolResponse(output=output, content=[Part(text='note')]), 'tool') + + assert len(result.content) == 1 + assert [entry['log_level'] for entry in logs] == ['warning'] + + +def test_text_parts_without_output_are_sent_in_order() -> None: + result = multipart_to_call_result( + MultipartToolResponse(output=None, content=[Part(text='first'), Part(text='second')]), + 'tool', + ) + + assert [block.text for block in result.content if isinstance(block, TextContent)] == ['first', 'second'] + + +@pytest.mark.parametrize('url', ['/covers/a.png', 'covers/a.png']) +def test_a_media_part_with_a_relative_url_is_dropped_with_a_warning(url: str) -> None: + """A resource link needs an absolute URI, and one bad part must not fail a call that succeeded.""" + with capture_logs() as logs: + result = multipart_to_call_result( + MultipartToolResponse(output='ok', content=[media(url, 'image/png')]), + 'tool', + ) + + assert result.content == [TextContent(type='text', text='ok')] + assert [entry['log_level'] for entry in logs] == ['warning'] + + +def test_a_part_mcp_cannot_carry_is_dropped_with_a_warning() -> None: + with capture_logs() as logs: + result = multipart_to_call_result( + MultipartToolResponse(output=None, content=[Part(reasoning='thinking')]), + 'tool', + ) + + assert result.content == [] + assert [entry['log_level'] for entry in logs] == ['warning'] + + +def test_metadata_travels_as_meta() -> None: + result = multipart_to_call_result(MultipartToolResponse(output='x', metadata={'trace': 'a'}), 'tool') + + assert result.meta == {'trace': 'a'} + + +def test_a_re_exported_error_stays_an_error_without_accreting_the_flag() -> None: + """A client error envelope came from an MCP error, and goes back out as one.""" + response: MultipartToolResponse[object] = MultipartToolResponse( + output={'error': 'upstream failed'}, + metadata={'trace': 'a', 'isError': True}, + ) + + result = multipart_to_call_result(response, 'tool') + + assert result.isError is True + assert result.content == [TextContent(type='text', text='upstream failed')] + assert result.meta == {'trace': 'a'} + + +def test_error_result_carries_only_the_message() -> None: + result = error_result('Tool "missing" is not registered') + + assert result.isError is True + assert result.content == [TextContent(type='text', text='Tool "missing" is not registered')] + assert result.meta is None + + +@pytest.mark.asyncio +async def test_a_no_arg_tool_advertises_an_object_schema() -> None: + """Core infers {} for a no-arg tool, which MCP arguments cannot express.""" + ai = Genkit() + + @ai.tool() + async def ping() -> str: + """Answer.""" + return 'pong' + + tool = tool_to_mcp(ping) + + assert tool is not None + assert tool.inputSchema == {'type': 'object', 'properties': {}} + assert tool.description == 'Answer.' + + +@pytest.mark.asyncio +async def test_a_tool_with_a_scalar_argument_is_skipped_with_a_warning() -> None: + """MCP arguments are always an object, so a scalar-input tool cannot be listed.""" + ai = Genkit() + + @ai.tool() + async def shout(word: str) -> str: + """Shout.""" + return word.upper() + + action = shout + action.input_schema = {'type': 'string'} + + with capture_logs() as logs: + tool = tool_to_mcp(action) + + assert tool is None + assert [entry['log_level'] for entry in logs] == ['warning'] + + +class Node(BaseModel): + """A model that refers to itself, which pydantic describes with a top-level $ref.""" + + label: str + children: list['Node'] = [] + + +@pytest.mark.asyncio +async def test_a_tool_whose_input_refers_to_itself_is_described_as_an_object() -> None: + ai = Genkit() + + @ai.tool() + async def tree(node: Node) -> int: + """Count nodes.""" + return 1 + len(node.children) + + tool = tool_to_mcp(tree) + + assert tool is not None + assert tool.inputSchema['type'] == 'object' + assert tool.inputSchema['properties']['children']['items'] == {'$ref': '#/$defs/Node'} + assert 'Node' in tool.inputSchema['$defs'] + assert '$ref' not in tool.inputSchema + + +@pytest.mark.asyncio +async def test_a_schema_with_properties_but_no_type_is_described_as_an_object() -> None: + ai = Genkit() + + @ai.tool() + async def greet(name: str) -> str: + """Greet.""" + return name + + action = greet + action.input_schema = {'properties': {'name': {'type': 'string'}}, 'required': ['name']} + + tool = tool_to_mcp(action) + + assert tool is not None + assert tool.inputSchema == {'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name']} + + +@pytest.mark.asyncio +async def test_an_optional_object_input_is_skipped_with_a_warning() -> None: + """``Optional[Model]`` is ``anyOf`` with null, and MCP arguments are never null.""" + ai = Genkit() + + @ai.tool() + async def maybe(node: Node | None) -> int: + """Maybe count.""" + return 0 + + with capture_logs() as logs: + tool = tool_to_mcp(maybe) + + assert tool is None + assert [entry['log_level'] for entry in logs] == ['warning'] diff --git a/packages/genkit-mcp/tests/mcp_exports_test.py b/packages/genkit-mcp/tests/mcp_exports_test.py index 9d758e5be..aa796660b 100644 --- a/packages/genkit-mcp/tests/mcp_exports_test.py +++ b/packages/genkit-mcp/tests/mcp_exports_test.py @@ -20,6 +20,13 @@ def test_the_package_exports_exactly_its_public_surface() -> None: - assert genkit_mcp.__all__ == ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] + assert genkit_mcp.__all__ == [ + 'McpClient', + 'McpHost', + 'McpServer', + 'create_mcp_server', + 'define_mcp_client', + 'define_mcp_host', + ] for name in genkit_mcp.__all__: assert getattr(genkit_mcp, name) is not None diff --git a/packages/genkit-mcp/tests/mcp_server_test.py b/packages/genkit-mcp/tests/mcp_server_test.py new file mode 100644 index 000000000..aee4f6ca6 --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_server_test.py @@ -0,0 +1,307 @@ +# 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 +# +# SPDX-License-Identifier: Apache-2.0 + +"""Tests driving a Genkit-backed MCP server through an in-memory client.""" + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import pytest +from genkit_mcp._server import McpServer, create_mcp_server +from mcp import ClientSession +from mcp.shared.memory import create_connected_server_and_client_session +from mcp.types import CallToolResult, ImageContent, TextContent +from pydantic import BaseModel +from structlog.testing import capture_logs + +from genkit import Genkit, GenkitError, MultipartToolResponse, Part, Tool, ToolContext +from genkit.plugin_api import Action + + +class Shelf(BaseModel): + """Output of a tool whose schema MCP can advertise.""" + + title: str + count: int + + +class Greeting(BaseModel): + """Input of a tool whose schema MCP can carry.""" + + name: str + + +@asynccontextmanager +async def connected(server: McpServer) -> AsyncIterator[ClientSession]: + """Drive a server over the SDK's in-memory transport.""" + async with create_connected_server_and_client_session(server._server, raise_exceptions=True) as session: + yield session + + +def app() -> Genkit: + return Genkit() + + +def text_of(result: CallToolResult) -> str: + """Join the text blocks of a result, ignoring any other block kind.""" + return ''.join(block.text for block in result.content if isinstance(block, TextContent)) + + +@pytest.mark.asyncio +async def test_a_tool_defined_after_the_server_is_still_listed() -> None: + """Listing reads the app per request, so late definitions are not missed.""" + ai = app() + server = create_mcp_server(ai, 'bookshop') + + @ai.tool() + async def late() -> str: + """Defined after the server was built.""" + return 'here' + + async with connected(server) as session: + listed = await session.list_tools() + + assert [tool.name for tool in listed.tools] == ['late'] + assert listed.tools[0].description == 'Defined after the server was built.' + + +@pytest.mark.asyncio +async def test_the_server_advertises_its_name_and_version() -> None: + ai = app() + server = create_mcp_server(ai, 'bookshop', version='2.1.0') + + async with connected(server) as session: + result = await session.initialize() + + assert result.serverInfo.name == 'bookshop' + assert result.serverInfo.version == '2.1.0' + + +@pytest.mark.asyncio +async def test_capabilities_offer_tools_and_nothing_else() -> None: + """Prompts and resources are not served, so they are not advertised.""" + ai = app() + server = create_mcp_server(ai, 'bookshop') + + async with connected(server) as session: + result = await session.initialize() + + assert result.capabilities.tools is not None + assert result.capabilities.prompts is None + assert result.capabilities.resources is None + + +@pytest.mark.asyncio +async def test_a_string_tool_returns_text() -> None: + ai = app() + + @ai.tool() + async def greet(greeting: Greeting) -> str: + """Greet.""" + return f'hello {greeting.name}' + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('greet', {'name': 'ada'}) + + assert result.content == [TextContent(type='text', text='hello ada')] + assert result.isError is False + + +@pytest.mark.asyncio +async def test_a_tool_with_a_scalar_argument_is_neither_listed_nor_callable() -> None: + """MCP arguments are an object, so such a tool cannot be described or invoked.""" + ai = app() + + @ai.tool() + async def shout(word: str) -> str: + """Shout.""" + return word.upper() + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + listed = await session.list_tools() + result = await session.call_tool('shout', {'word': 'hi'}) + + assert listed.tools == [] + assert result.isError is True + assert 'is not registered' in text_of(result) + + +@pytest.mark.asyncio +async def test_an_object_tool_returns_structured_content_and_advertises_its_schema() -> None: + ai = app() + + @ai.tool() + async def shelf() -> Shelf: + """Describe a shelf.""" + return Shelf(title='Fiction', count=2) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + listed = await session.list_tools() + result = await session.call_tool('shelf', {}) + + assert listed.tools[0].outputSchema is not None + assert listed.tools[0].outputSchema.get('type') == 'object' + assert result.structuredContent == {'title': 'Fiction', 'count': 2} + + +@pytest.mark.asyncio +async def test_a_media_tool_returns_image_content() -> None: + ai = app() + + @ai.tool() + async def cover() -> MultipartToolResponse: + """Return a cover image.""" + return MultipartToolResponse( + output=None, + content=[Part.from_media(url='data:image/png;base64,aW1n', content_type='image/png')], + ) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('cover', {}) + + assert result.content == [ImageContent(type='image', mimeType='image/png', data='aW1n')] + + +@pytest.mark.asyncio +async def test_a_raising_tool_becomes_an_error_result_carrying_its_message() -> None: + ai = app() + + @ai.tool() + async def explode() -> str: + """Fail.""" + raise ValueError('shelf collapsed') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('explode', {}) + + assert result.isError is True + assert result.content == [TextContent(type='text', text="Tool 'explode' failed")] + + +@pytest.mark.asyncio +async def test_a_genkit_error_keeps_its_status_and_message_but_not_its_cause() -> None: + """A GenkitError's message is the app's choice, and its cause's text is not.""" + ai = app() + + @ai.tool() + async def book() -> str: + """Fail on purpose.""" + raise GenkitError( + status='INVALID_ARGUMENT', + message='date must be in the future', + cause=RuntimeError('GET https://api.example.com/v1?key=SECRET failed'), + ) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('book', {}) + + assert result.isError is True + assert result.content == [TextContent(type='text', text='INVALID_ARGUMENT: date must be in the future')] + + +@pytest.mark.asyncio +async def test_the_request_meta_reaches_the_tool_context() -> None: + ai = app() + seen: list[object] = [] + + @ai.tool() + async def trace(ctx: ToolContext) -> str: + """Record the context.""" + seen.append(ctx.context) + return 'ok' + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + await session.call_tool('trace', {}, meta={'requestId': 'r-1'}) + + assert seen == [{'mcp': {'_meta': {'requestId': 'r-1'}}}] + + +@pytest.mark.asyncio +async def test_a_tool_mcp_cannot_describe_is_warned_about_once() -> None: + """Listing and calling reuse each description, so the warning does not repeat per request.""" + ai = app() + + @ai.tool() + async def shout(word: str) -> str: + """Shout.""" + return word.upper() + + @ai.tool() + async def ping() -> str: + """Answer.""" + return 'pong' + + with capture_logs() as logs: + async with connected(create_mcp_server(ai, 'bookshop')) as session: + await session.list_tools() + await session.call_tool('ping', {}) + await session.list_tools() + + assert [entry['event'] for entry in logs if entry['log_level'] == 'warning'] == [ + 'skipping a tool whose input is not an object, which MCP arguments cannot express' + ] + + +@pytest.mark.asyncio +async def test_an_unknown_tool_is_an_error_result() -> None: + ai = app() + + @ai.tool() + async def known() -> str: + """Exist.""" + return 'here' + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('missing', {}) + + assert result.isError is True + assert 'is not registered' in text_of(result) + + +@pytest.mark.asyncio +async def test_tools_a_dynamic_action_provider_serves_are_not_served() -> None: + """Only tools defined on the app are served, as in JS and Go.""" + ai = app() + + @ai.tool() + async def known() -> str: + """Exist.""" + return 'here' + + async def remote() -> str: + """Served by a provider.""" + return 'there' + + async def provide() -> dict[str, list[Action]]: + return {'tool': [Tool(remote, name='remote')]} + + ai.define_dynamic_action_provider('elsewhere', provide) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + listed = await session.list_tools() + result = await session.call_tool('remote', {}) + + assert [tool.name for tool in listed.tools] == ['known'] + assert result.isError is True + + +@pytest.mark.asyncio +async def test_a_no_arg_tool_advertises_an_object_input_schema() -> None: + ai = app() + + @ai.tool() + async def ping() -> str: + """Answer.""" + return 'pong' + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + listed = await session.list_tools() + + assert listed.tools[0].inputSchema == {'type': 'object', 'properties': {}} From 8dab127c0796d951a09f886d92565d077dc89540 Mon Sep 17 00:00:00 2001 From: Jacob Cable Date: Fri, 23 Oct 2026 17:49:32 +0100 Subject: [PATCH 2/8] test(py/plugins/mcp): pin the stdio wire with a raw subprocess start() owns this process's stdin and stdout, and nothing in the slice exercised it. These tests drive the fixture app as a child with plain JSON-RPC lines, so they need no MCP client. Every stdout line after the first frame parses as JSON-RPC under GENKIT_LOG=debug, and a log line written while serving reaches stderr. A child forced into an ASCII locale, with UTF-8 mode and locale coercion off, still answers with non-ASCII text intact; under PYTHONIOENCODING alone the test passed without the fix, since a bare TextIOWrapper reads the locale, not that variable. redirect_stdout=False leaves sys.stdout alone, and a structlog logger cached before start() follows the swap to stderr. Upstream-Commit: genkit-ai/genkit@c1974e9a6 Upstream-PR: https://github.com/genkit-ai/genkit/pull/6882 --- packages/genkit-mcp/tests/genkit_server.py | 127 ++++++++++++++ packages/genkit-mcp/tests/mcp_stdio_test.py | 176 ++++++++++++++++++++ 2 files changed, 303 insertions(+) create mode 100644 packages/genkit-mcp/tests/genkit_server.py create mode 100644 packages/genkit-mcp/tests/mcp_stdio_test.py diff --git a/packages/genkit-mcp/tests/genkit_server.py b/packages/genkit-mcp/tests/genkit_server.py new file mode 100644 index 000000000..5b7cc9f71 --- /dev/null +++ b/packages/genkit-mcp/tests/genkit_server.py @@ -0,0 +1,127 @@ +# 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. +# SPDX-License-Identifier: Apache-2.0 + +"""A Genkit app served over MCP stdio, driven by the round-trip tests.""" + +import asyncio + +import structlog +from genkit_mcp import create_mcp_server +from pydantic import BaseModel + +from genkit import Genkit, GenkitError, MultipartToolResponse, Part +from genkit._core._typing import Resource + +logger = structlog.get_logger(__name__) + +IMAGE_URL = 'data:image/png;base64,aW1n' +AUDIO_URL = 'data:audio/wav;base64,c25k' +PDF_URL = 'data:application/pdf;base64,cGRm' +RESOURCE_URI = 'https://example.com/manual' + +SERVER_NAME = 'roundtrip' + +ai = Genkit() + + +class Shelf(BaseModel): + """Output of the one tool whose schema MCP can advertise.""" + + title: str + count: int + + +@ai.tool() +async def plain_text() -> str: + """Return a string.""" + await logger.ainfo('serving plain text') + return 'plain text' + + +@ai.tool() +async def mapping() -> object: + """Return an object.""" + return {'a': 1, 'b': [1, 2]} + + +@ai.tool() +async def listing() -> object: + """Return an array.""" + return [1, 'x'] + + +@ai.tool() +async def media() -> MultipartToolResponse: + """Return one content part of every kind MCP has a block for.""" + return MultipartToolResponse( + output='t', + content=[ + Part.from_media(url=IMAGE_URL, content_type='image/png'), + Part.from_media(url=AUDIO_URL, content_type='audio/wav'), + Part.from_media(url=PDF_URL, content_type='application/pdf'), + Part(resource=Resource(uri=RESOURCE_URI)), + ], + ) + + +@ai.tool() +async def annotated() -> MultipartToolResponse: + """Return output and metadata together.""" + return MultipartToolResponse(output={'k': 1}, metadata={'m': 2}) + + +@ai.tool() +async def explode() -> str: + """Fail.""" + raise ValueError('boom') + + +@ai.tool() +async def reject() -> str: + """Fail with a message meant for the model, caused by one that is not.""" + raise GenkitError( + status='INVALID_ARGUMENT', + message='date must be in the future', + cause=RuntimeError('GET https://api.example.com/v1?key=SECRET failed'), + ) + + +@ai.tool() +async def accented() -> str: + """Return text outside ASCII.""" + return 'café 東京' + + +@ai.tool() +async def noted_object() -> MultipartToolResponse: + """Return an object with a text part beside it.""" + return MultipartToolResponse(output={'k': 1}, content=[Part(text='note')]) + + +@ai.tool() +async def noted_array() -> MultipartToolResponse: + """Return an array with a text part beside it.""" + return MultipartToolResponse(output=[1, 2], content=[Part(text='note')]) + + +@ai.tool() +async def text_parts() -> MultipartToolResponse: + """Return text parts and no output.""" + return MultipartToolResponse(content=[Part(text='first '), Part(text='second')]) + + +@ai.tool() +async def shelf() -> Shelf: + """Return a typed object.""" + return Shelf(title='Poetry', count=3) + + +server = create_mcp_server(ai, SERVER_NAME) + +logger.info('genkit_server imported') + +if __name__ == '__main__': + asyncio.run(server.start()) diff --git a/packages/genkit-mcp/tests/mcp_stdio_test.py b/packages/genkit-mcp/tests/mcp_stdio_test.py new file mode 100644 index 000000000..e7c1b8e6b --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_stdio_test.py @@ -0,0 +1,176 @@ +# 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. +# SPDX-License-Identifier: Apache-2.0 + +"""Tests for serving over this process's stdin and stdout, with no MCP client in the way.""" + +import asyncio +import io +import json +import os +import sys +from pathlib import Path +from typing import Any + +import pytest +import structlog +from genkit_mcp import create_mcp_server + +from genkit import Genkit + +SERVER = Path(__file__).with_name('genkit_server.py') + +# Every await on the child process is bounded by this, so a lifecycle regression +# fails the suite rather than hanging it. There is no global pytest timeout. +LIMIT = 60 + +CALL_ID = 2 + + +def requests(tool: str) -> list[dict[str, Any]]: + """Open a session and call one tool, as a client would write them to stdin.""" + return [ + { + 'jsonrpc': '2.0', + 'id': 1, + 'method': 'initialize', + 'params': { + 'protocolVersion': '2025-06-18', + 'capabilities': {}, + 'clientInfo': {'name': 'stdio-test', 'version': '1.0.0'}, + }, + }, + {'jsonrpc': '2.0', 'method': 'notifications/initialized'}, + {'jsonrpc': '2.0', 'id': CALL_ID, 'method': 'tools/call', 'params': {'name': tool, 'arguments': {}}}, + ] + + +async def call_over_stdio(tool: str, **env: str) -> tuple[list[str], str]: + """Run the fixture app as a child, call one tool, and return its stdout lines and stderr.""" + process = await asyncio.create_subprocess_exec( + sys.executable, + str(SERVER), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + env={**os.environ, 'GENKIT_LOG': 'debug', **env}, + ) + assert process.stdin is not None + assert process.stdout is not None + + for request in requests(tool): + process.stdin.write((json.dumps(request) + '\n').encode()) + await asyncio.wait_for(process.stdin.drain(), timeout=LIMIT) + + lines = await asyncio.wait_for(_read_until_call_answered(process.stdout), timeout=LIMIT) + process.stdin.close() + rest, stderr = await asyncio.wait_for(process.communicate(), timeout=LIMIT) + return lines + rest.decode().splitlines(), stderr.decode() + + +@pytest.mark.asyncio +async def test_stdout_carries_only_json_rpc_once_the_server_is_serving() -> None: + """Logging while serving goes to stderr, so a debug-level app does not corrupt a frame. + + What the app logs before ``start()`` runs is another matter: stdout is not + the wire yet and nothing has been redirected, so those lines are on stdout. + """ + lines, stderr = await call_over_stdio('plain_text') + + wire = lines[_first_json_line(lines) :] + assert [line for line in wire if _decode(line) is None] == [] + assert 'genkit_server imported' in '\n'.join(lines[: _first_json_line(lines)]) + assert 'serving plain text' not in '\n'.join(lines) + assert 'serving plain text' in stderr + + +@pytest.mark.asyncio +async def test_text_outside_ascii_survives_a_server_whose_locale_cannot_encode_it() -> None: + lines, _ = await call_over_stdio( + 'accented', LC_ALL='C', LANG='C', PYTHONUTF8='0', PYTHONCOERCECLOCALE='0', PYTHONIOENCODING='ascii' + ) + + answer = next(message for line in lines if (message := _decode(line)) and message.get('id') == CALL_ID) + assert answer['result']['content'] == [{'type': 'text', 'text': 'café 東京'}] + + +@pytest.mark.asyncio +async def test_redirect_stdout_false_leaves_this_process_stdout_alone(monkeypatch: pytest.MonkeyPatch) -> None: + """Opting out means an app that already keeps stdout clear keeps its own arrangement.""" + server = create_mcp_server(Genkit(), 'quiet', redirect_stdout=False) + wire = _stream() + monkeypatch.setattr(sys, 'stdin', _stream()) + monkeypatch.setattr(sys, 'stdout', wire) + + await asyncio.wait_for(server.start(), timeout=LIMIT) + + assert sys.stdout is wire + + +@pytest.mark.asyncio +async def test_a_logger_built_before_the_swap_still_follows_it(monkeypatch: pytest.MonkeyPatch) -> None: + """The whole stdout arrangement rests on this: structlog's default logger defers to sys.stdout. + + Its PrintLogger passes file=None to print rather than capturing a stream, + so a logger cached before start() runs still lands on the redirected + stream instead of writing JSON-RPC's channel. + """ + cached = structlog.get_logger('cached-before-the-swap') + server = create_mcp_server(Genkit(), 'noisy') + wire_bytes = _KeptOpen() + wire = io.TextIOWrapper(wire_bytes, encoding='utf-8') + stderr = io.StringIO() + monkeypatch.setattr(sys, 'stdin', _stream()) + monkeypatch.setattr(sys, 'stdout', wire) + monkeypatch.setattr(sys, 'stderr', stderr) + + await asyncio.wait_for(server.start(), timeout=LIMIT) + cached.info('after the swap') + + assert 'after the swap' in stderr.getvalue() + assert b'after the swap' not in wire_bytes.getvalue() + + +class _KeptOpen(io.BytesIO): + """Bytes that stay readable after the server's own wrapper closes them.""" + + def close(self) -> None: + pass + + +def _stream() -> io.TextIOWrapper: + """A text stream backed by bytes, as a real stdin or stdout is.""" + return io.TextIOWrapper(_KeptOpen(), encoding='utf-8') + + +async def _read_until_call_answered(stdout: asyncio.StreamReader) -> list[str]: + """Collect stdout lines up to and including the answer to the tool call.""" + lines: list[str] = [] + while True: + raw = await stdout.readline() + if not raw: + raise AssertionError(f'the server closed stdout without answering: {lines}') + line = raw.decode().rstrip('\n') + lines.append(line) + message = _decode(line) + if message is not None and message.get('id') == CALL_ID: + return lines + + +def _decode(line: str) -> dict[str, Any] | None: + """Read one stdout line as a JSON-RPC message, or nothing when it is not one.""" + try: + message = json.loads(line) + except json.JSONDecodeError: + return None + return message if isinstance(message, dict) and message.get('jsonrpc') == '2.0' else None + + +def _first_json_line(lines: list[str]) -> int: + """Find where the wire opens, which is the first line the transport wrote.""" + for index, line in enumerate(lines): + if _decode(line) is not None: + return index + raise AssertionError(f'the server wrote no JSON-RPC at all: {lines}') From b35adeb0c8df9641377810b85104a68ae75e4b86 Mon Sep 17 00:00:00 2001 From: Jacob Cable Date: Fri, 23 Oct 2026 17:50:00 +0100 Subject: [PATCH 3/8] fix(py/plugins/mcp): flush stdout before the stdio transport takes it start() wraps sys.stdout.buffer in a new text stream for the transport. Text the app printed earlier without a newline sat in the old stream's buffer, which flushed whenever it was next written or collected: after the transport had started, so it could land between two frames. Flushing first puts it out ahead of the first frame. It still reaches the client as stray output, as anything logged before start() does, but it can no longer split a frame. Upstream-Commit: genkit-ai/genkit@05a4e5542 Upstream-PR: https://github.com/genkit-ai/genkit/pull/6882 --- packages/genkit-mcp/src/genkit_mcp/_server.py | 1 + packages/genkit-mcp/tests/mcp_stdio_test.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index c32aee449..b68920878 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -106,6 +106,7 @@ async def start(self) -> None: its life. A logger built before this call keeps the descriptor it captured. """ + sys.stdout.flush() streams = stdio_server( stdin=anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding='utf-8')), stdout=anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding='utf-8')), diff --git a/packages/genkit-mcp/tests/mcp_stdio_test.py b/packages/genkit-mcp/tests/mcp_stdio_test.py index e7c1b8e6b..6f2c30a54 100644 --- a/packages/genkit-mcp/tests/mcp_stdio_test.py +++ b/packages/genkit-mcp/tests/mcp_stdio_test.py @@ -133,6 +133,22 @@ async def test_a_logger_built_before_the_swap_still_follows_it(monkeypatch: pyte assert b'after the swap' not in wire_bytes.getvalue() +@pytest.mark.asyncio +async def test_text_buffered_before_start_reaches_stdout_ahead_of_the_wire(monkeypatch: pytest.MonkeyPatch) -> None: + """Unflushed text left in the old stdout would otherwise land between frames whenever it flushed.""" + server = create_mcp_server(Genkit(), 'buffered') + wire_bytes = _KeptOpen() + old_stdout = io.TextIOWrapper(wire_bytes, encoding='utf-8') + old_stdout.write('pending') + monkeypatch.setattr(sys, 'stdin', _stream()) + monkeypatch.setattr(sys, 'stdout', old_stdout) + monkeypatch.setattr(sys, 'stderr', io.StringIO()) + + await asyncio.wait_for(server.start(), timeout=LIMIT) + + assert wire_bytes.getvalue() == b'pending' + + class _KeptOpen(io.BytesIO): """Bytes that stay readable after the server's own wrapper closes them.""" From 690ad319e6fad0797e5e1ceaf4cd6265d2c25015 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:56:33 +0100 Subject: [PATCH 4/8] fix(py/plugins/mcp): keep error text and stray writes off the MCP wire Listing failures and non-public errors no longer reach the client verbatim, stdio serves on copies of fds 0 and 1 with fd 1 moved to stderr, output schemas are only advertised when the output is always there, and interrupts and data parts get deliberate results. --- packages/genkit-mcp/README.md | 53 +++--- packages/genkit-mcp/src/genkit_mcp/_export.py | 26 ++- packages/genkit-mcp/src/genkit_mcp/_server.py | 78 ++++++--- packages/genkit-mcp/tests/genkit_server.py | 120 ++++---------- packages/genkit-mcp/tests/mcp_export_test.py | 36 +++- packages/genkit-mcp/tests/mcp_server_test.py | 146 ++++++++++++++--- packages/genkit-mcp/tests/mcp_stdio_test.py | 154 +++++++----------- 7 files changed, 351 insertions(+), 262 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index d23bdc40e..27a866ebe 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -199,36 +199,43 @@ if __name__ == '__main__': The app's tools are read with `ai.list_tools()` on every `tools/list`, so a tool defined after the server was built is still served. A tool whose input is not an object, such as a single scalar or an optional model, is skipped: MCP arguments are always an object, and such a tool is not callable by -name either, rather than being listed and then failing. A model that refers to itself is served. An output schema is advertised only when it describes an object, since anything else -cannot be structured content. Tools a dynamic action provider supplies, from `define_mcp_client` -for instance, are not defined on the app and are not served. - -A tool that raises answers with an error result. A `GenkitError` (including `PublicError`) sends its -status and message, without the text of its cause. Any other exception sends only `Tool '' -failed`, since its text can carry a URL or a credential. The full error is logged on the server -either way, so raise a `GenkitError` for a failure the model should read and retry. +name either, rather than being listed and then failing. A model that refers to itself is served. +An output schema is advertised only for a tool that returns an object itself, such as `-> Shelf`. +A client rejects a result that lacks the structured content a schema promised, and a tool returning +`MultipartToolResponse[Shelf]` may leave its output out. Tools a dynamic action provider supplies, +from `define_mcp_client` for instance, are not defined on the app and are not served. + +A tool that raises answers with an error result. A `PublicError` sends its status and message. Any +other `GenkitError` sends `Tool '' failed: `, and any other exception `Tool '' +failed`, since a provider's error text can name a project, a resource path or a URL. So raise a +`PublicError` for a failure the model should read and retry. The full error is logged on the server +either way. A tool that interrupts for the user's input answers with an error result saying so, +since MCP cannot pause a call. A plugin that fails to start fails the listing, and the client is +told only that the server could not list its tools. ### stdio `await server.start()` serves on this process's stdin and stdout until stdin closes. stdout is the -wire, so `start()` captures the real one for the transport and then points `sys.stdout` at stderr -for the rest of the process's life, because structlog's builtin default writes to stdout and one -stray line corrupts a JSON-RPC frame. A logging configuration your app chose for itself is left -alone, and a logger built before `start()` keeps the descriptor it captured. Pass -`redirect_stdout=False` to opt out. +wire, so `start()` gives the transport a copy of file descriptor 1, whatever `sys.stdout` is at the +time, and then points both descriptor 1 and `sys.stdout` at stderr for the rest of the process's +life. One stray line corrupts a JSON-RPC frame, and structlog's builtin default writes to stdout, so +`print`, loggers, child processes and C extensions all write to stderr from then on. Text still +buffered for stdout is flushed ahead of the first frame. Pass `redirect_stdout=False` to leave +stdout as it is, for an app that keeps it clear itself. `await server.serve(read_stream, write_stream)` serves on any SDK stream pair instead, and touches nothing. -## Known gaps +### Known gaps Scalar outputs and strings that look like JSON do not round-trip exactly. Clients join every text -block into the output, so a text content part is sent only beside no output or an object output, and -is dropped with a warning otherwise. A media part whose URL is not absolute is dropped with a -warning. A tool whose input is not an object is not served at all, -and an output schema that is not an object is not advertised, so a client is told less about such a -tool than Genkit knows. Nothing sends `notifications/tools/list_changed`; the list is re-read per -request instead. Progress, cancellation, sampling and elicitation are not supported. A -plugin-namespaced tool name carries a `/`, which the MCP SDK warns about. Whatever the app logs -before `start()` runs is on stdout, which that call is too late to have redirected. stdio reads and -writes UTF-8 whatever the locale, but is untested on Windows. +block into the output, so a text or data content part is sent only beside no output or an object +output, and is dropped with a warning otherwise. A Genkit client reading a result with structured +content keeps that object and drops the text beside it. A media part whose URL is not absolute is +dropped with a warning, and one sent as a resource link is dropped by a Genkit client. A tool whose +input is not an object is not served at all, and an output schema is advertised only as described +above, so a client is told less about such a tool than Genkit knows. Nothing sends +`notifications/tools/list_changed`; the list is re-read per request instead. A client's +`notifications/cancelled` cancels the tool call. Progress, sampling and elicitation are not +supported. A plugin-namespaced tool name carries a `/`, which the MCP SDK warns about. stdio reads +and writes UTF-8 whatever the locale, but is untested on Windows. diff --git a/packages/genkit-mcp/src/genkit_mcp/_export.py b/packages/genkit-mcp/src/genkit_mcp/_export.py index c4b04d274..1287ad5a9 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_export.py +++ b/packages/genkit-mcp/src/genkit_mcp/_export.py @@ -69,10 +69,10 @@ def multipart_to_call_result(response: MultipartToolResponse, tool_name: str) -> """Convert what a Genkit tool returned into an MCP call result. MCP has one text channel, and clients join every text block into the - output. A text part is therefore sent only when that cannot change the - output a client reads back: when there is no output, or when the output is - an object carried as ``structuredContent``. Otherwise it is dropped with a - warning. + output. A text or data part, which travels as JSON text, is therefore sent + only when that cannot change the output a client reads back: when there is + no output, or when the output is an object carried as + ``structuredContent``. Otherwise it is dropped with a warning. Args: response: The envelope a ``tool.v2`` action returned. @@ -92,7 +92,8 @@ def multipart_to_call_result(response: MultipartToolResponse, tool_name: str) -> if output is not None: content.append(TextContent(type='text', text=_output_text(output))) for index, part in enumerate(response.content or []): - if part.text is not None and output is not None and structured is None: + is_text = part.text is not None or part.data is not None + if is_text and output is not None and structured is None: logger.warning('dropping a text part that would change the text output', tool=tool_name, index=index) continue block = _part_to_block(part, tool_name, index) @@ -154,12 +155,16 @@ def _object_schema(schema: dict[str, Any]) -> dict[str, Any] | None: def _output_schema(tool: Tool) -> dict[str, Any] | None: """Read the model-facing output schema, kept only when MCP can carry it. - The SDK rejects any unstructured result for a tool that declares an output - schema, and ``structuredContent`` is an object, so a non-object schema is - dropped rather than advertised. + A client rejects any result without ``structuredContent`` from a tool that + declares an output schema, and ``structuredContent`` is an object. So the + schema is advertised only when it is an object and the tool returns that + object itself. A tool returning a ``MultipartToolResponse`` may leave its + output out, so its schema is not advertised. """ original = _as_object(tool.model_output_schema) - return original if original.get('type') == 'object' else None + if original.get('type') != 'object' or tool.output_schema != tool.model_output_schema: + return None + return original def _tool_meta(tool: Tool) -> dict[str, Any] | None: @@ -196,6 +201,9 @@ def _part_to_block(part: Part, tool_name: str, index: int) -> ContentBlock | Non if part.text is not None: return TextContent(type='text', text=part.text) + if part.data is not None: + return TextContent(type='text', text=json.dumps(part.data)) + if part.media is not None: url = part.media.url match = _DATA_URL.match(url) diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index b68920878..f89acb92f 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -10,18 +10,19 @@ """A Genkit app served to MCP clients as an MCP server.""" +import os import sys -from io import TextIOWrapper -from typing import Any +from typing import Any, TextIO from weakref import WeakKeyDictionary import anyio from mcp.server.lowlevel import Server from mcp.server.stdio import stdio_server -from mcp.types import CallToolResult, Tool as McpTool +from mcp.shared.exceptions import McpError +from mcp.types import INTERNAL_ERROR, CallToolResult, ErrorData, Tool as McpTool from pydantic import TypeAdapter -from genkit import Genkit, GenkitError, MultipartToolResponse, Tool, get_logger +from genkit import Genkit, GenkitError, Interrupt, MultipartToolResponse, PublicError, Tool, get_logger from genkit_mcp._export import error_result, multipart_to_call_result, tool_to_mcp logger = get_logger(__name__) @@ -29,7 +30,9 @@ _JSON = TypeAdapter(object) DEFAULT_VERSION = '1.0.0' -"""What JS and Go both advertise when the app names no version.""" +"""The version a server advertises when the app names none.""" + +_LISTING_FAILED = 'The server could not list its tools' class McpServer: @@ -101,20 +104,18 @@ async def serve(self, read_stream: Any, write_stream: Any, *, raise_exceptions: async def start(self) -> None: """Serve on this process's stdin and stdout until stdin closes. - stdout is the wire, so it is captured before anything can write to it - and the process's own stdout is then pointed at stderr for the rest of - its life. A logger built before this call keeps the descriptor it - captured. + stdout is the wire. The transport writes to a copy of descriptor 1 + taken before anything else can, whatever ``sys.stdout`` is at the time. + Descriptor 1 and ``sys.stdout`` then point at stderr for the rest of + the process's life, so ``print``, loggers and child processes cannot + write between frames. """ - sys.stdout.flush() - streams = stdio_server( - stdin=anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding='utf-8')), - stdout=anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding='utf-8')), - ) + stdin, stdout = _wire_files() if self._redirect_stdout: _redirect_stdout_to_stderr() - async with streams as (read_stream, write_stream): - await self.serve(read_stream, write_stream) + with stdin, stdout: + async with stdio_server(stdin=anyio.wrap_file(stdin), stdout=anyio.wrap_file(stdout)) as streams: + await self.serve(*streams) async def _list_tools(self) -> list[McpTool]: """Describe every tool this server offers, read fresh from the app.""" @@ -126,8 +127,13 @@ async def _served_tools(self) -> list[tuple[Tool, McpTool]]: Listing and calling read the same pairs, so a tool MCP cannot describe is not reachable by name either. """ + try: + tools = await self._ai.list_tools() + except Exception as error: + logger.exception("could not list the app's tools for MCP") + raise McpError(ErrorData(code=INTERNAL_ERROR, message=_LISTING_FAILED)) from error served: list[tuple[Tool, McpTool]] = [] - for tool in await self._ai.list_tools(): + for tool in tools: if tool not in self._described: self._described[tool] = tool_to_mcp(tool) described = self._described[tool] @@ -141,13 +147,19 @@ async def _call_tool(self, name: str, arguments: dict[str, Any]) -> CallToolResu A raised error becomes an ``isError`` result and is logged here, where its traceback is still useful. """ - tool = await self._find_tool(name) + try: + tool = await self._find_tool(name) + except McpError as error: + return error_result(error.error.message) if tool is None: return error_result(f'Tool {name!r} is not registered') context = self._request_context() try: return multipart_to_call_result(await _run(tool, arguments, context), name) + except Interrupt: + logger.warning('an MCP tool call paused for input, which MCP cannot ask for', tool=name) + return error_result(f'Tool {name!r} paused for input from the user, which this server cannot ask for') except Exception as error: logger.exception('an MCP tool call failed', tool=name) return error_result(_client_message(name, error)) @@ -218,20 +230,34 @@ async def _run(tool: Tool, arguments: dict[str, Any], context: dict[str, Any] | def _client_message(tool_name: str, error: Exception) -> str: """Say why a tool failed without passing on text the app never chose to show. - A ``GenkitError`` keeps its status and message but not its cause's text, - which can carry a request URL or a credential. + A ``PublicError`` is the app's message for the caller, so its status and + message are sent. Any other ``GenkitError`` sends only its status, since a + provider's error text can name a project, a resource path or a URL. """ - if isinstance(error, GenkitError): + if isinstance(error, PublicError): return f'{error.status}: {error.message}' + if isinstance(error, GenkitError): + return f'Tool {tool_name!r} failed: {error.status}' return f'Tool {tool_name!r} failed' +def _wire_files() -> tuple[TextIO, TextIO]: + """Open copies of descriptors 0 and 1 for the transport, as UTF-8 whatever the locale. + + Text still buffered for stdout is flushed first, so it cannot land between frames. + """ + for stream in (sys.stdout, sys.__stdout__): + if stream is not None: + stream.flush() + return open(os.dup(0), encoding='utf-8'), open(os.dup(1), 'w', encoding='utf-8') + + def _redirect_stdout_to_stderr() -> None: - """Point this process's stdout at stderr, so nothing can corrupt the wire. + """Point this process's stdout at stderr, so nothing else can write to the wire. - Rebinding ``sys.stdout`` is enough to move a logger that was built before - this call: structlog's default ``PrintLogger`` passes ``file=None`` to - ``print``, which reads ``sys.stdout`` at call time. A logger bound to an - explicit stream is the app's own choice and is left where it points. + Moving descriptor 1 covers child processes, C code and any stream still + bound to the original stdout. Rebinding ``sys.stdout`` covers ``print`` + and structlog's default logger, which reads ``sys.stdout`` on every call. """ + os.dup2(2, 1) sys.stdout = sys.stderr diff --git a/packages/genkit-mcp/tests/genkit_server.py b/packages/genkit-mcp/tests/genkit_server.py index 5b7cc9f71..31fdf649a 100644 --- a/packages/genkit-mcp/tests/genkit_server.py +++ b/packages/genkit-mcp/tests/genkit_server.py @@ -4,91 +4,33 @@ # you may not use this file except in compliance with the License. # SPDX-License-Identifier: Apache-2.0 -"""A Genkit app served over MCP stdio, driven by the round-trip tests.""" +"""A Genkit app served over MCP stdio, run as a child process by the stdio tests. + +``MCP_TEST_PRE_REDIRECT=1`` points ``sys.stdout`` at stderr before serving, as +an app following the usual MCP advice does. ``MCP_TEST_NO_REDIRECT=1`` serves +with ``redirect_stdout=False``. +""" import asyncio +import os +import sys -import structlog from genkit_mcp import create_mcp_server -from pydantic import BaseModel - -from genkit import Genkit, GenkitError, MultipartToolResponse, Part -from genkit._core._typing import Resource -logger = structlog.get_logger(__name__) +from genkit import Genkit, get_logger -IMAGE_URL = 'data:image/png;base64,aW1n' -AUDIO_URL = 'data:audio/wav;base64,c25k' -PDF_URL = 'data:application/pdf;base64,cGRm' -RESOURCE_URI = 'https://example.com/manual' - -SERVER_NAME = 'roundtrip' +logger = get_logger(__name__) ai = Genkit() -class Shelf(BaseModel): - """Output of the one tool whose schema MCP can advertise.""" - - title: str - count: int - - @ai.tool() async def plain_text() -> str: """Return a string.""" - await logger.ainfo('serving plain text') + logger.info('serving plain text') return 'plain text' -@ai.tool() -async def mapping() -> object: - """Return an object.""" - return {'a': 1, 'b': [1, 2]} - - -@ai.tool() -async def listing() -> object: - """Return an array.""" - return [1, 'x'] - - -@ai.tool() -async def media() -> MultipartToolResponse: - """Return one content part of every kind MCP has a block for.""" - return MultipartToolResponse( - output='t', - content=[ - Part.from_media(url=IMAGE_URL, content_type='image/png'), - Part.from_media(url=AUDIO_URL, content_type='audio/wav'), - Part.from_media(url=PDF_URL, content_type='application/pdf'), - Part(resource=Resource(uri=RESOURCE_URI)), - ], - ) - - -@ai.tool() -async def annotated() -> MultipartToolResponse: - """Return output and metadata together.""" - return MultipartToolResponse(output={'k': 1}, metadata={'m': 2}) - - -@ai.tool() -async def explode() -> str: - """Fail.""" - raise ValueError('boom') - - -@ai.tool() -async def reject() -> str: - """Fail with a message meant for the model, caused by one that is not.""" - raise GenkitError( - status='INVALID_ARGUMENT', - message='date must be in the future', - cause=RuntimeError('GET https://api.example.com/v1?key=SECRET failed'), - ) - - @ai.tool() async def accented() -> str: """Return text outside ASCII.""" @@ -96,32 +38,32 @@ async def accented() -> str: @ai.tool() -async def noted_object() -> MultipartToolResponse: - """Return an object with a text part beside it.""" - return MultipartToolResponse(output={'k': 1}, content=[Part(text='note')]) - - -@ai.tool() -async def noted_array() -> MultipartToolResponse: - """Return an array with a text part beside it.""" - return MultipartToolResponse(output=[1, 2], content=[Part(text='note')]) - - -@ai.tool() -async def text_parts() -> MultipartToolResponse: - """Return text parts and no output.""" - return MultipartToolResponse(content=[Part(text='first '), Part(text='second')]) +async def raw_writes() -> str: + """Write to stdout below sys.stdout: a child process, the descriptor, and the original stream.""" + child = await asyncio.create_subprocess_exec(sys.executable, '-c', 'print("written by a child process")') + await child.wait() + os.write(1, b'written to descriptor 1\n') + assert sys.__stdout__ is not None + sys.__stdout__.write('written to the original stdout\n') + sys.__stdout__.flush() + return 'wrote' @ai.tool() -async def shelf() -> Shelf: - """Return a typed object.""" - return Shelf(title='Poetry', count=3) +async def prints() -> str: + """Print the way app code does.""" + sys.stdout.write('printed by a tool\n') + sys.stdout.flush() + return 'printed' -server = create_mcp_server(ai, SERVER_NAME) +server = create_mcp_server(ai, 'stdio-test', redirect_stdout=os.environ.get('MCP_TEST_NO_REDIRECT') != '1') -logger.info('genkit_server imported') +sys.stdout.write('written before start\n') if __name__ == '__main__': + if os.environ.get('MCP_TEST_PRE_REDIRECT') == '1': + sys.stdout = sys.stderr asyncio.run(server.start()) + sys.stdout.write('printed after the server stopped\n') + sys.stdout.flush() diff --git a/packages/genkit-mcp/tests/mcp_export_test.py b/packages/genkit-mcp/tests/mcp_export_test.py index cb6d56dfa..68d8bfe6d 100644 --- a/packages/genkit-mcp/tests/mcp_export_test.py +++ b/packages/genkit-mcp/tests/mcp_export_test.py @@ -102,7 +102,9 @@ def test_a_non_data_media_url_becomes_a_resource_link() -> None: def test_a_resource_part_becomes_a_resource_link() -> None: result = multipart_to_call_result( - MultipartToolResponse(output=None, content=[Part.model_validate({'resource': {'uri': 'https://example.test/docs'}})]), + MultipartToolResponse( + output=None, content=[Part.model_validate({'resource': {'uri': 'https://example.test/docs'}})] + ), 'tool', ) @@ -164,6 +166,20 @@ def test_a_part_mcp_cannot_carry_is_dropped_with_a_warning() -> None: assert [entry['log_level'] for entry in logs] == ['warning'] +def test_a_data_part_travels_as_json_text() -> None: + result = multipart_to_call_result(MultipartToolResponse(output=None, content=[Part(data={'a': [1, 2]})]), 'tool') + + assert result.content == [TextContent(type='text', text='{"a": [1, 2]}')] + + +def test_a_data_part_beside_a_non_object_output_is_dropped_with_a_warning() -> None: + with capture_logs() as logs: + result = multipart_to_call_result(MultipartToolResponse(output='ok', content=[Part(data={'a': 1})]), 'tool') + + assert result.content == [TextContent(type='text', text='ok')] + assert [entry['log_level'] for entry in logs] == ['warning'] + + def test_metadata_travels_as_meta() -> None: result = multipart_to_call_result(MultipartToolResponse(output='x', metadata={'trace': 'a'}), 'tool') @@ -207,6 +223,24 @@ async def ping() -> str: assert tool is not None assert tool.inputSchema == {'type': 'object', 'properties': {}} assert tool.description == 'Answer.' + assert tool.meta is None + + +@pytest.mark.asyncio +async def test_a_re_exported_client_tool_keeps_the_meta_of_its_origin() -> None: + ai = Genkit() + + @ai.tool() + async def echo() -> str: + """Echo.""" + return 'echo' + + echo.metadata['mcp'] = {'prefix': 'everything', 'tool': 'echo', '_meta': {'ui': 'compact'}} + + tool = tool_to_mcp(echo) + + assert tool is not None + assert tool.meta == {'ui': 'compact'} @pytest.mark.asyncio diff --git a/packages/genkit-mcp/tests/mcp_server_test.py b/packages/genkit-mcp/tests/mcp_server_test.py index aee4f6ca6..018ee8dd1 100644 --- a/packages/genkit-mcp/tests/mcp_server_test.py +++ b/packages/genkit-mcp/tests/mcp_server_test.py @@ -16,13 +16,14 @@ import pytest from genkit_mcp._server import McpServer, create_mcp_server from mcp import ClientSession +from mcp.shared.exceptions import McpError from mcp.shared.memory import create_connected_server_and_client_session from mcp.types import CallToolResult, ImageContent, TextContent from pydantic import BaseModel from structlog.testing import capture_logs -from genkit import Genkit, GenkitError, MultipartToolResponse, Part, Tool, ToolContext -from genkit.plugin_api import Action +from genkit import Genkit, MultipartToolResponse, Part, PublicError, Tool, ToolContext +from genkit.plugin_api import Action, ActionKind, Plugin, provider_error class Shelf(BaseModel): @@ -55,21 +56,26 @@ def text_of(result: CallToolResult) -> str: @pytest.mark.asyncio -async def test_a_tool_defined_after_the_server_is_still_listed() -> None: +async def test_a_tool_defined_after_a_listing_is_in_the_next_one_and_callable() -> None: """Listing reads the app per request, so late definitions are not missed.""" ai = app() server = create_mcp_server(ai, 'bookshop') - @ai.tool() - async def late() -> str: - """Defined after the server was built.""" - return 'here' - async with connected(server) as session: - listed = await session.list_tools() + before = await session.list_tools() + + @ai.tool() + async def late() -> str: + """Defined after the first listing.""" + return 'here' - assert [tool.name for tool in listed.tools] == ['late'] - assert listed.tools[0].description == 'Defined after the server was built.' + after = await session.list_tools() + result = await session.call_tool('late', {}) + + assert before.tools == [] + assert [tool.name for tool in after.tools] == ['late'] + assert after.tools[0].description == 'Defined after the first listing.' + assert text_of(result) == 'here' @pytest.mark.asyncio @@ -146,11 +152,46 @@ async def shelf() -> Shelf: listed = await session.list_tools() result = await session.call_tool('shelf', {}) - assert listed.tools[0].outputSchema is not None - assert listed.tools[0].outputSchema.get('type') == 'object' + assert listed.tools[0].outputSchema == Shelf.model_json_schema() assert result.structuredContent == {'title': 'Fiction', 'count': 2} +@pytest.mark.asyncio +async def test_a_tool_returning_a_tool_response_advertises_no_output_schema() -> None: + """Its output can be left out, and a client rejects a result missing what the schema promised.""" + ai = app() + + @ai.tool() + async def shelf_photo() -> MultipartToolResponse[Shelf]: + """Photograph a shelf.""" + return MultipartToolResponse(content=[Part.from_media(url='data:image/png;base64,aW1n')]) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + listed = await session.list_tools() + result = await session.call_tool('shelf_photo', {}) + + assert listed.tools[0].outputSchema is None + assert result.isError is False + assert result.content == [ImageContent(type='image', mimeType='image/png', data='aW1n')] + + +@pytest.mark.asyncio +async def test_a_tool_registered_as_a_plain_action_is_served() -> None: + """A tool action with no ``tool.v2`` companion returns its value, which becomes the output.""" + ai = app() + + async def shelf(_: dict[str, object]) -> Shelf: + return Shelf(title='Poetry', count=3) + + ai._registry.register_action_from_instance(Action(kind=ActionKind.TOOL, name='shelf', fn=shelf)) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('shelf', {}) + + assert result.isError is False + assert result.structuredContent == {'title': 'Poetry', 'count': 3} + + @pytest.mark.asyncio async def test_a_media_tool_returns_image_content() -> None: ai = app() @@ -170,7 +211,7 @@ async def cover() -> MultipartToolResponse: @pytest.mark.asyncio -async def test_a_raising_tool_becomes_an_error_result_carrying_its_message() -> None: +async def test_a_raising_tool_becomes_an_error_result_without_its_message() -> None: ai = app() @ai.tool() @@ -186,18 +227,14 @@ async def explode() -> str: @pytest.mark.asyncio -async def test_a_genkit_error_keeps_its_status_and_message_but_not_its_cause() -> None: - """A GenkitError's message is the app's choice, and its cause's text is not.""" +async def test_a_public_error_sends_its_status_and_message() -> None: + """A PublicError is the app's message for the caller.""" ai = app() @ai.tool() async def book() -> str: """Fail on purpose.""" - raise GenkitError( - status='INVALID_ARGUMENT', - message='date must be in the future', - cause=RuntimeError('GET https://api.example.com/v1?key=SECRET failed'), - ) + raise PublicError(status='INVALID_ARGUMENT', message='date must be in the future') async with connected(create_mcp_server(ai, 'bookshop')) as session: result = await session.call_tool('book', {}) @@ -206,6 +243,73 @@ async def book() -> str: assert result.content == [TextContent(type='text', text='INVALID_ARGUMENT: date must be in the future')] +@pytest.mark.asyncio +async def test_a_provider_error_sends_only_its_status() -> None: + """A provider's error text can name a project or a resource path, so it stays on the server.""" + ai = app() + + @ai.tool() + async def lookup() -> str: + """Call a model that is not reachable.""" + raise provider_error(RuntimeError('Permission denied on resource project acme-prod-1234'), http_status=403) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('lookup', {}) + + assert result.isError is True + assert result.content == [TextContent(type='text', text="Tool 'lookup' failed: PERMISSION_DENIED")] + + +@pytest.mark.asyncio +async def test_an_interrupt_is_an_error_result_without_a_traceback() -> None: + """MCP has no way to pause a call for the user, so an interrupt says so instead of looking like a crash.""" + ai = app() + ai.define_interrupt('confirm_order', description='Ask the diner to confirm.') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + with capture_logs() as logs: + result = await session.call_tool('confirm_order', {}) + + assert result.isError is True + assert text_of(result) == "Tool 'confirm_order' paused for input from the user, which this server cannot ask for" + assert [log['log_level'] for log in logs if log.get('tool') == 'confirm_order'] == ['warning'] + + +class _FailingPlugin(Plugin): + """Fails to start with text the client must not see.""" + + name = 'failing' + + async def init(self) -> list[Action]: + raise RuntimeError('GET https://api.example.com/v1?key=SECRET failed') + + async def resolve(self, action_type: ActionKind, name: str) -> Action | None: + return None + + async def list_actions(self) -> list[Action]: + return [] + + +@pytest.mark.asyncio +async def test_a_plugin_that_fails_to_start_keeps_its_error_text_on_the_server() -> None: + """Listing starts every plugin, and a failure there reaches the client only as a fixed sentence.""" + ai = Genkit(plugins=[_FailingPlugin()]) + + @ai.tool() + async def known() -> str: + """Exist.""" + return 'here' + + async with create_connected_server_and_client_session(create_mcp_server(ai, 'bookshop')._server) as session: + with pytest.raises(McpError) as listing: + await session.list_tools() + result = await session.call_tool('known', {}) + + assert listing.value.error.message == 'The server could not list its tools' + assert result.isError is True + assert text_of(result) == 'The server could not list its tools' + + @pytest.mark.asyncio async def test_the_request_meta_reaches_the_tool_context() -> None: ai = app() diff --git a/packages/genkit-mcp/tests/mcp_stdio_test.py b/packages/genkit-mcp/tests/mcp_stdio_test.py index 6f2c30a54..360b501ae 100644 --- a/packages/genkit-mcp/tests/mcp_stdio_test.py +++ b/packages/genkit-mcp/tests/mcp_stdio_test.py @@ -7,7 +7,6 @@ """Tests for serving over this process's stdin and stdout, with no MCP client in the way.""" import asyncio -import io import json import os import sys @@ -15,10 +14,6 @@ from typing import Any import pytest -import structlog -from genkit_mcp import create_mcp_server - -from genkit import Genkit SERVER = Path(__file__).with_name('genkit_server.py') @@ -26,15 +21,13 @@ # fails the suite rather than hanging it. There is no global pytest timeout. LIMIT = 60 -CALL_ID = 2 - -def requests(tool: str) -> list[dict[str, Any]]: - """Open a session and call one tool, as a client would write them to stdin.""" +def requests(tools: list[str]) -> list[dict[str, Any]]: + """Open a session and call each tool, as a client would write them to stdin.""" return [ { 'jsonrpc': '2.0', - 'id': 1, + 'id': 0, 'method': 'initialize', 'params': { 'protocolVersion': '2025-06-18', @@ -43,12 +36,15 @@ def requests(tool: str) -> list[dict[str, Any]]: }, }, {'jsonrpc': '2.0', 'method': 'notifications/initialized'}, - {'jsonrpc': '2.0', 'id': CALL_ID, 'method': 'tools/call', 'params': {'name': tool, 'arguments': {}}}, + *( + {'jsonrpc': '2.0', 'id': call_id, 'method': 'tools/call', 'params': {'name': tool, 'arguments': {}}} + for call_id, tool in enumerate(tools, start=1) + ), ] -async def call_over_stdio(tool: str, **env: str) -> tuple[list[str], str]: - """Run the fixture app as a child, call one tool, and return its stdout lines and stderr.""" +async def call_over_stdio(tools: list[str], **env: str) -> tuple[list[str], str]: + """Run the fixture app as a child, call each tool, and return its stdout lines and stderr.""" process = await asyncio.create_subprocess_exec( sys.executable, str(SERVER), @@ -59,110 +55,73 @@ async def call_over_stdio(tool: str, **env: str) -> tuple[list[str], str]: ) assert process.stdin is not None assert process.stdout is not None - - for request in requests(tool): - process.stdin.write((json.dumps(request) + '\n').encode()) - await asyncio.wait_for(process.stdin.drain(), timeout=LIMIT) - - lines = await asyncio.wait_for(_read_until_call_answered(process.stdout), timeout=LIMIT) - process.stdin.close() - rest, stderr = await asyncio.wait_for(process.communicate(), timeout=LIMIT) + assert process.stderr is not None + try: + for request in requests(tools): + process.stdin.write((json.dumps(request) + '\n').encode()) + await asyncio.wait_for(process.stdin.drain(), timeout=LIMIT) + lines = await asyncio.wait_for(_read_until_answered(process.stdout, len(tools)), timeout=LIMIT) + process.stdin.close() + rest, stderr = await asyncio.wait_for(process.communicate(), timeout=LIMIT) + except (AssertionError, asyncio.TimeoutError) as error: + process.kill() + _, stderr = await process.communicate() + raise AssertionError(f'{error!r}\nserver stderr:\n{stderr.decode()}') from error return lines + rest.decode().splitlines(), stderr.decode() @pytest.mark.asyncio async def test_stdout_carries_only_json_rpc_once_the_server_is_serving() -> None: - """Logging while serving goes to stderr, so a debug-level app does not corrupt a frame. + """Logging, a child process, descriptor 1 and the original stdout all land on stderr while serving. - What the app logs before ``start()`` runs is another matter: stdout is not - the wire yet and nothing has been redirected, so those lines are on stdout. + What the app writes before ``start()`` runs is another matter: stdout is not + the wire yet, so it is flushed there ahead of the first frame. """ - lines, stderr = await call_over_stdio('plain_text') + lines, stderr = await call_over_stdio(['plain_text', 'raw_writes']) - wire = lines[_first_json_line(lines) :] - assert [line for line in wire if _decode(line) is None] == [] - assert 'genkit_server imported' in '\n'.join(lines[: _first_json_line(lines)]) - assert 'serving plain text' not in '\n'.join(lines) - assert 'serving plain text' in stderr + first = _first_json_line(lines) + assert 'written before start' in lines[:first] + assert [line for line in lines[first:] if _decode(line) is None] == [] + assert _results(lines) == {1: 'plain text', 2: 'wrote'} + for text in ( + 'serving plain text', + 'written by a child process', + 'written to descriptor 1', + 'written to the original stdout', + ): + assert text in stderr @pytest.mark.asyncio async def test_text_outside_ascii_survives_a_server_whose_locale_cannot_encode_it() -> None: lines, _ = await call_over_stdio( - 'accented', LC_ALL='C', LANG='C', PYTHONUTF8='0', PYTHONCOERCECLOCALE='0', PYTHONIOENCODING='ascii' + ['accented'], LC_ALL='C', LANG='C', PYTHONUTF8='0', PYTHONCOERCECLOCALE='0', PYTHONIOENCODING='ascii' ) - answer = next(message for line in lines if (message := _decode(line)) and message.get('id') == CALL_ID) - assert answer['result']['content'] == [{'type': 'text', 'text': 'café 東京'}] + assert _results(lines) == {1: 'café 東京'} @pytest.mark.asyncio -async def test_redirect_stdout_false_leaves_this_process_stdout_alone(monkeypatch: pytest.MonkeyPatch) -> None: - """Opting out means an app that already keeps stdout clear keeps its own arrangement.""" - server = create_mcp_server(Genkit(), 'quiet', redirect_stdout=False) - wire = _stream() - monkeypatch.setattr(sys, 'stdin', _stream()) - monkeypatch.setattr(sys, 'stdout', wire) - - await asyncio.wait_for(server.start(), timeout=LIMIT) +async def test_an_app_that_already_moved_sys_stdout_is_still_answered_on_stdout() -> None: + """The wire is descriptor 1, not whatever ``sys.stdout`` happens to be when ``start()`` runs.""" + lines, _ = await call_over_stdio(['plain_text'], MCP_TEST_PRE_REDIRECT='1') - assert sys.stdout is wire + assert _results(lines) == {1: 'plain text'} @pytest.mark.asyncio -async def test_a_logger_built_before_the_swap_still_follows_it(monkeypatch: pytest.MonkeyPatch) -> None: - """The whole stdout arrangement rests on this: structlog's default logger defers to sys.stdout. +async def test_redirect_stdout_false_leaves_this_process_stdout_alone() -> None: + """Opting out keeps stdout where it was, and still usable once the server stops.""" + lines, stderr = await call_over_stdio(['prints'], MCP_TEST_NO_REDIRECT='1') - Its PrintLogger passes file=None to print rather than capturing a stream, - so a logger cached before start() runs still lands on the redirected - stream instead of writing JSON-RPC's channel. - """ - cached = structlog.get_logger('cached-before-the-swap') - server = create_mcp_server(Genkit(), 'noisy') - wire_bytes = _KeptOpen() - wire = io.TextIOWrapper(wire_bytes, encoding='utf-8') - stderr = io.StringIO() - monkeypatch.setattr(sys, 'stdin', _stream()) - monkeypatch.setattr(sys, 'stdout', wire) - monkeypatch.setattr(sys, 'stderr', stderr) - - await asyncio.wait_for(server.start(), timeout=LIMIT) - cached.info('after the swap') - - assert 'after the swap' in stderr.getvalue() - assert b'after the swap' not in wire_bytes.getvalue() + assert _results(lines) == {1: 'printed'} + assert 'printed by a tool' in lines + assert lines[-1] == 'printed after the server stopped' + assert 'printed by a tool' not in stderr -@pytest.mark.asyncio -async def test_text_buffered_before_start_reaches_stdout_ahead_of_the_wire(monkeypatch: pytest.MonkeyPatch) -> None: - """Unflushed text left in the old stdout would otherwise land between frames whenever it flushed.""" - server = create_mcp_server(Genkit(), 'buffered') - wire_bytes = _KeptOpen() - old_stdout = io.TextIOWrapper(wire_bytes, encoding='utf-8') - old_stdout.write('pending') - monkeypatch.setattr(sys, 'stdin', _stream()) - monkeypatch.setattr(sys, 'stdout', old_stdout) - monkeypatch.setattr(sys, 'stderr', io.StringIO()) - - await asyncio.wait_for(server.start(), timeout=LIMIT) - - assert wire_bytes.getvalue() == b'pending' - - -class _KeptOpen(io.BytesIO): - """Bytes that stay readable after the server's own wrapper closes them.""" - - def close(self) -> None: - pass - - -def _stream() -> io.TextIOWrapper: - """A text stream backed by bytes, as a real stdin or stdout is.""" - return io.TextIOWrapper(_KeptOpen(), encoding='utf-8') - - -async def _read_until_call_answered(stdout: asyncio.StreamReader) -> list[str]: - """Collect stdout lines up to and including the answer to the tool call.""" +async def _read_until_answered(stdout: asyncio.StreamReader, calls: int) -> list[str]: + """Collect stdout lines up to and including the answer to the last tool call.""" lines: list[str] = [] while True: raw = await stdout.readline() @@ -171,10 +130,19 @@ async def _read_until_call_answered(stdout: asyncio.StreamReader) -> list[str]: line = raw.decode().rstrip('\n') lines.append(line) message = _decode(line) - if message is not None and message.get('id') == CALL_ID: + if message is not None and message.get('id') == calls: return lines +def _results(lines: list[str]) -> dict[int, str]: + """Read the text each tool call answered with, by call id.""" + return { + message['id']: message['result']['content'][0]['text'] + for line in lines + if (message := _decode(line)) and message.get('id', 0) > 0 + } + + def _decode(line: str) -> dict[str, Any] | None: """Read one stdout line as a JSON-RPC message, or nothing when it is not one.""" try: From 47da108d529d28ae49873100b870e926b39a9304 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 15:14:44 +0100 Subject: [PATCH 5/8] fix(py/plugins/mcp): serve plain tool actions and odd results safely Plain tool actions get no output schema and dump by alias, error text follows genkit.web.error_body, unencodable results become error results, stdin moves to /dev/null with stdout, and descriptions are cached by name. --- packages/genkit-mcp/README.md | 47 ++++++---- packages/genkit-mcp/src/genkit_mcp/_export.py | 5 +- packages/genkit-mcp/src/genkit_mcp/_server.py | 84 +++++++++++------ packages/genkit-mcp/tests/genkit_server.py | 5 +- packages/genkit-mcp/tests/mcp_server_test.py | 92 ++++++++++++++++--- packages/genkit-mcp/tests/mcp_stdio_test.py | 9 +- packages/genkit/src/genkit/_ai/_aio.py | 2 +- 7 files changed, 177 insertions(+), 67 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 27a866ebe..2f8251427 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -200,28 +200,32 @@ The app's tools are read with `ai.list_tools()` on every `tools/list`, so a tool server was built is still served. A tool whose input is not an object, such as a single scalar or an optional model, is skipped: MCP arguments are always an object, and such a tool is not callable by name either, rather than being listed and then failing. A model that refers to itself is served. -An output schema is advertised only for a tool that returns an object itself, such as `-> Shelf`. -A client rejects a result that lacks the structured content a schema promised, and a tool returning -`MultipartToolResponse[Shelf]` may leave its output out. Tools a dynamic action provider supplies, -from `define_mcp_client` for instance, are not defined on the app and are not served. - -A tool that raises answers with an error result. A `PublicError` sends its status and message. Any -other `GenkitError` sends `Tool '' failed: `, and any other exception `Tool '' -failed`, since a provider's error text can name a project, a resource path or a URL. So raise a -`PublicError` for a failure the model should read and retry. The full error is logged on the server -either way. A tool that interrupts for the user's input answers with an error result saying so, -since MCP cannot pause a call. A plugin that fails to start fails the listing, and the client is -told only that the server could not list its tools. +An output schema is advertised only for a tool defined with `@ai.tool()` that returns an object +itself, such as `-> Shelf`. A client rejects a result that lacks the structured content a schema +promised, and a tool returning `MultipartToolResponse[Shelf]` may leave its output out. Tools a +dynamic action provider supplies, from `define_mcp_client` for instance, are not defined on the app +and are not served. + +A tool that raises answers with an error result, worded as a served flow's error body is. A +`PublicError` sends its status and message, and arguments the tool's input model rejects send the +failing fields without their values. Any other `GenkitError` sends `Tool '' failed: `, +and any other exception `Tool '' failed`, since a provider's error text can name a project, a +resource path or a URL. So raise a `PublicError` for a failure the model should read and retry. The +full error is logged on the server either way. A tool that interrupts for the user's input answers +with an error result saying so, since MCP cannot pause a call, and so does a result that cannot be +encoded as UTF-8. A plugin that fails to start fails the listing, and the client is told only that +the server could not list its tools. ### stdio -`await server.start()` serves on this process's stdin and stdout until stdin closes. stdout is the -wire, so `start()` gives the transport a copy of file descriptor 1, whatever `sys.stdout` is at the -time, and then points both descriptor 1 and `sys.stdout` at stderr for the rest of the process's -life. One stray line corrupts a JSON-RPC frame, and structlog's builtin default writes to stdout, so -`print`, loggers, child processes and C extensions all write to stderr from then on. Text still -buffered for stdout is flushed ahead of the first frame. Pass `redirect_stdout=False` to leave -stdout as it is, for an app that keeps it clear itself. +`await server.start()` serves on this process's stdin and stdout until stdin closes. They are the +wire, so `start()` gives the transport copies of file descriptors 0 and 1, whatever `sys.stdin` and +`sys.stdout` are at the time. It then points descriptor 1 and `sys.stdout` at stderr, and descriptor +0 at the null device, for the rest of the process's life. One stray line corrupts a JSON-RPC frame, +and structlog's builtin default writes to stdout, so `print`, loggers, child processes and C +extensions all write to stderr from then on, and a child process cannot read the client's requests. +Text still buffered for stdout is flushed ahead of the first frame. Pass `redirect_stdout=False` to +leave both as they are, for an app that keeps them clear itself. `await server.serve(read_stream, write_stream)` serves on any SDK stream pair instead, and touches nothing. @@ -234,7 +238,10 @@ output, and is dropped with a warning otherwise. A Genkit client reading a resul content keeps that object and drops the text beside it. A media part whose URL is not absolute is dropped with a warning, and one sent as a resource link is dropped by a Genkit client. A tool whose input is not an object is not served at all, and an output schema is advertised only as described -above, so a client is told less about such a tool than Genkit knows. Nothing sends +above, so a client is told less about such a tool than Genkit knows. The advertised schema is the +one Genkit validates input against, so an output model whose dumped JSON differs from it, through a +`serialization_alias` or a `computed_field` on a model that forbids extra fields, fails the client's +check of the result. Nothing sends `notifications/tools/list_changed`; the list is re-read per request instead. A client's `notifications/cancelled` cancels the tool call. Progress, sampling and elicitation are not supported. A plugin-namespaced tool name carries a `/`, which the MCP SDK warns about. stdio reads diff --git a/packages/genkit-mcp/src/genkit_mcp/_export.py b/packages/genkit-mcp/src/genkit_mcp/_export.py index 1287ad5a9..38375c6c4 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_export.py +++ b/packages/genkit-mcp/src/genkit_mcp/_export.py @@ -159,8 +159,11 @@ def _output_schema(tool: Tool) -> dict[str, Any] | None: declares an output schema, and ``structuredContent`` is an object. So the schema is advertised only when it is an object and the tool returns that object itself. A tool returning a ``MultipartToolResponse`` may leave its - output out, so its schema is not advertised. + output out, so its schema is not advertised, and neither is a plain tool + action's, which cannot tell the two apart. """ + if tool.wire_action is None: + return None original = _as_object(tool.model_output_schema) if original.get('type') != 'object' or tool.output_schema != tool.model_output_schema: return None diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index f89acb92f..5f4e1e65c 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -13,7 +13,6 @@ import os import sys from typing import Any, TextIO -from weakref import WeakKeyDictionary import anyio from mcp.server.lowlevel import Server @@ -23,6 +22,7 @@ from pydantic import TypeAdapter from genkit import Genkit, GenkitError, Interrupt, MultipartToolResponse, PublicError, Tool, get_logger +from genkit.web import error_body, error_status from genkit_mcp._export import error_result, multipart_to_call_result, tool_to_mcp logger = get_logger(__name__) @@ -64,13 +64,14 @@ def __init__( version: Version the server advertises. instructions: How a client should use this server. redirect_stdout: Whether ``start`` moves this process's stdout to - stderr. Leave it on unless the app already keeps stdout clear. + stderr and its stdin to the null device. Leave it on unless the + app already keeps both clear. """ self._ai = ai self._name = name self._version = version self._redirect_stdout = redirect_stdout - self._described: WeakKeyDictionary[Tool, McpTool | None] = WeakKeyDictionary() + self._described: dict[str, tuple[dict[str, Any], McpTool | None]] = {} self._server: Server[Any, Any] = Server(name, version=version, instructions=instructions) self._server.list_tools()(self._list_tools) self._server.call_tool()(self._call_tool) @@ -104,15 +105,16 @@ async def serve(self, read_stream: Any, write_stream: Any, *, raise_exceptions: async def start(self) -> None: """Serve on this process's stdin and stdout until stdin closes. - stdout is the wire. The transport writes to a copy of descriptor 1 - taken before anything else can, whatever ``sys.stdout`` is at the time. - Descriptor 1 and ``sys.stdout`` then point at stderr for the rest of - the process's life, so ``print``, loggers and child processes cannot - write between frames. + stdin and stdout are the wire. The transport reads and writes copies of + descriptors 0 and 1, taken whatever ``sys.stdin`` and ``sys.stdout`` + are at the time. With ``redirect_stdout`` on, descriptor 1 and + ``sys.stdout`` then point at stderr and descriptor 0 at the null device + for the rest of the process's life, so ``print``, loggers and child + processes can neither write between frames nor read them. """ stdin, stdout = _wire_files() if self._redirect_stdout: - _redirect_stdout_to_stderr() + _move_stdio_off_the_wire() with stdin, stdout: async with stdio_server(stdin=anyio.wrap_file(stdin), stdout=anyio.wrap_file(stdout)) as streams: await self.serve(*streams) @@ -134,9 +136,13 @@ async def _served_tools(self) -> list[tuple[Tool, McpTool]]: raise McpError(ErrorData(code=INTERNAL_ERROR, message=_LISTING_FAILED)) from error served: list[tuple[Tool, McpTool]] = [] for tool in tools: - if tool not in self._described: - self._described[tool] = tool_to_mcp(tool) - described = self._described[tool] + # A plain tool action comes back as a new view on every listing, so + # the description is keyed by name and the metadata the view shares. + cached = self._described.get(tool.name) + if cached is None or cached[0] is not tool.metadata: + cached = (tool.metadata, tool_to_mcp(tool)) + self._described[tool.name] = cached + described = cached[1] if described is not None: served.append((tool, described)) return served @@ -147,16 +153,17 @@ async def _call_tool(self, name: str, arguments: dict[str, Any]) -> CallToolResu A raised error becomes an ``isError`` result and is logged here, where its traceback is still useful. """ - try: - tool = await self._find_tool(name) - except McpError as error: - return error_result(error.error.message) + tool = await self._find_tool(name) if tool is None: return error_result(f'Tool {name!r} is not registered') context = self._request_context() try: - return multipart_to_call_result(await _run(tool, arguments, context), name) + result = multipart_to_call_result(await _run(tool, arguments, context), name) + # Fail here rather than in the transport, where a result that cannot + # be encoded, such as text with a lone surrogate, ends the session. + result.model_dump_json(by_alias=True, exclude_none=True) + return result except Interrupt: logger.warning('an MCP tool call paused for input, which MCP cannot ask for', tool=name) return error_result(f'Tool {name!r} paused for input from the user, which this server cannot ask for') @@ -216,26 +223,38 @@ async def _run(tool: Tool, arguments: dict[str, Any], context: dict[str, Any] | A tool built as a ``Tool`` has a ``tool.v2`` action that returns the envelope already. A plain tool action returns its function's value, which - becomes the envelope's output. + becomes the envelope's output, dumped by alias as JSON. """ wire = tool.wire_action if wire is not None: return (await wire.run(arguments, context=context)).response output = (await tool.run(arguments, context=context)).response if isinstance(output, MultipartToolResponse): - return output - return MultipartToolResponse(output=_JSON.dump_python(output, mode='json')) + return MultipartToolResponse( + output=_as_json(output.output), + content=output.content, + metadata=_as_json(output.metadata), + ) + return MultipartToolResponse(output=_as_json(output)) + + +def _as_json(value: object) -> Any: # noqa: ANN401 - whatever JSON the value dumps to + """Dump a tool's value to JSON data, by alias as Genkit's own tools do.""" + return _JSON.dump_python(value, mode='json', by_alias=True) def _client_message(tool_name: str, error: Exception) -> str: """Say why a tool failed without passing on text the app never chose to show. - A ``PublicError`` is the app's message for the caller, so its status and - message are sent. Any other ``GenkitError`` sends only its status, since a - provider's error text can name a project, a resource path or a URL. + The rule is a served flow's: a ``PublicError`` sends its status and + message, and arguments the tool's own schema rejects send the failing + fields without their values. Any other ``GenkitError`` sends only its + status, since a provider's error text can name a project, a resource path + or a URL. """ - if isinstance(error, PublicError): - return f'{error.status}: {error.message}' + if isinstance(error, PublicError) or error_status(error) < 500: + body = error_body(error) + return f'{body["status"]}: {body["message"]}' if isinstance(error, GenkitError): return f'Tool {tool_name!r} failed: {error.status}' return f'Tool {tool_name!r} failed' @@ -252,12 +271,17 @@ def _wire_files() -> tuple[TextIO, TextIO]: return open(os.dup(0), encoding='utf-8'), open(os.dup(1), 'w', encoding='utf-8') -def _redirect_stdout_to_stderr() -> None: - """Point this process's stdout at stderr, so nothing else can write to the wire. +def _move_stdio_off_the_wire() -> None: + """Point stdout at stderr and stdin at the null device, so nothing else can use the wire. - Moving descriptor 1 covers child processes, C code and any stream still - bound to the original stdout. Rebinding ``sys.stdout`` covers ``print`` - and structlog's default logger, which reads ``sys.stdout`` on every call. + Moving the descriptors covers child processes, C code and any stream still + bound to the originals. Rebinding ``sys.stdout`` covers ``print`` and + structlog's default logger, which reads ``sys.stdout`` on every call. """ os.dup2(2, 1) + null = os.open(os.devnull, os.O_RDONLY) + try: + os.dup2(null, 0) + finally: + os.close(null) sys.stdout = sys.stderr diff --git a/packages/genkit-mcp/tests/genkit_server.py b/packages/genkit-mcp/tests/genkit_server.py index 31fdf649a..2261f157f 100644 --- a/packages/genkit-mcp/tests/genkit_server.py +++ b/packages/genkit-mcp/tests/genkit_server.py @@ -39,8 +39,9 @@ async def accented() -> str: @ai.tool() async def raw_writes() -> str: - """Write to stdout below sys.stdout: a child process, the descriptor, and the original stream.""" - child = await asyncio.create_subprocess_exec(sys.executable, '-c', 'print("written by a child process")') + """Use stdio below sys.stdout: a child process, the descriptor, and the original stream.""" + script = 'import sys; print("written by a child process"); print("child read", repr(sys.stdin.read()))' + child = await asyncio.create_subprocess_exec(sys.executable, '-c', script) await child.wait() os.write(1, b'written to descriptor 1\n') assert sys.__stdout__ is not None diff --git a/packages/genkit-mcp/tests/mcp_server_test.py b/packages/genkit-mcp/tests/mcp_server_test.py index 018ee8dd1..4971e388d 100644 --- a/packages/genkit-mcp/tests/mcp_server_test.py +++ b/packages/genkit-mcp/tests/mcp_server_test.py @@ -19,7 +19,7 @@ from mcp.shared.exceptions import McpError from mcp.shared.memory import create_connected_server_and_client_session from mcp.types import CallToolResult, ImageContent, TextContent -from pydantic import BaseModel +from pydantic import BaseModel, Field, field_validator from structlog.testing import capture_logs from genkit import Genkit, MultipartToolResponse, Part, PublicError, Tool, ToolContext @@ -39,6 +39,25 @@ class Greeting(BaseModel): name: str +class Label(BaseModel): + """Output whose field travels under an alias.""" + + shelf_title: str = Field(alias='shelfTitle') + + +class Order(BaseModel): + """Input whose validator rejects values its JSON schema allows.""" + + qty: int + + @field_validator('qty') + @classmethod + def positive(cls, value: int) -> int: + if value <= 0: + raise ValueError(f'{value} is not a positive quantity') + return value + + @asynccontextmanager async def connected(server: McpServer) -> AsyncIterator[ClientSession]: """Drive a server over the SDK's in-memory transport.""" @@ -176,20 +195,67 @@ async def shelf_photo() -> MultipartToolResponse[Shelf]: @pytest.mark.asyncio -async def test_a_tool_registered_as_a_plain_action_is_served() -> None: +async def test_a_tool_registered_as_a_plain_action_is_served_by_alias_without_an_output_schema() -> None: """A tool action with no ``tool.v2`` companion returns its value, which becomes the output.""" ai = app() - async def shelf(_: dict[str, object]) -> Shelf: - return Shelf(title='Poetry', count=3) + async def label(_: dict[str, object]) -> Label: + return Label(shelfTitle='Poetry') + + async def photo(_: dict[str, object]) -> MultipartToolResponse[Label]: + return MultipartToolResponse( + output=Label(shelfTitle='Poetry'), + content=[Part.from_media(url='data:image/png;base64,aW1n')], + ) - ai._registry.register_action_from_instance(Action(kind=ActionKind.TOOL, name='shelf', fn=shelf)) + ai._registry.register_action_from_instance(Action(kind=ActionKind.TOOL, name='label', fn=label)) + ai._registry.register_action_from_instance(Action(kind=ActionKind.TOOL, name='photo', fn=photo)) async with connected(create_mcp_server(ai, 'bookshop')) as session: - result = await session.call_tool('shelf', {}) + listed = await session.list_tools() + labelled = await session.call_tool('label', {}) + photographed = await session.call_tool('photo', {}) - assert result.isError is False - assert result.structuredContent == {'title': 'Poetry', 'count': 3} + assert [tool.outputSchema for tool in listed.tools] == [None, None] + assert labelled.structuredContent == {'shelfTitle': 'Poetry'} + assert photographed.isError is False + assert photographed.structuredContent == {'shelfTitle': 'Poetry'} + assert photographed.content[1:] == [ImageContent(type='image', mimeType='image/png', data='aW1n')] + + +@pytest.mark.asyncio +async def test_arguments_the_tool_rejects_name_the_field_but_not_the_validator_text() -> None: + """The MCP SDK checks the JSON schema only, so the model learns which argument to fix from Genkit.""" + ai = app() + + @ai.tool() + async def order(order: Order) -> str: + """Order copies.""" + return f'{order.qty} ordered' + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('order', {'qty': -3}) + + assert result.isError is True + assert text_of(result).startswith("INVALID_ARGUMENT: Invalid input for tool 'order': qty:") + assert 'positive quantity' not in text_of(result) + + +@pytest.mark.asyncio +async def test_a_result_that_cannot_be_encoded_is_an_error_result() -> None: + """Text with a lone surrogate, as a non-UTF-8 file name decodes to, would otherwise end the session.""" + ai = app() + + @ai.tool() + async def filename() -> str: + """Name a file.""" + return 'notes-\udcff.txt' + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.call_tool('filename', {}) + + assert result.isError is True + assert text_of(result) == "Tool 'filename' failed" @pytest.mark.asyncio @@ -342,15 +408,19 @@ async def ping() -> str: """Answer.""" return 'pong' + async def whisper(word: str) -> str: + return word.lower() + + ai._registry.register_action_from_instance(Action(kind=ActionKind.TOOL, name='whisper', fn=whisper)) + with capture_logs() as logs: async with connected(create_mcp_server(ai, 'bookshop')) as session: await session.list_tools() await session.call_tool('ping', {}) await session.list_tools() - assert [entry['event'] for entry in logs if entry['log_level'] == 'warning'] == [ - 'skipping a tool whose input is not an object, which MCP arguments cannot express' - ] + skipped = [entry['tool'] for entry in logs if entry['log_level'] == 'warning'] + assert sorted(skipped) == ['shout', 'whisper'] @pytest.mark.asyncio diff --git a/packages/genkit-mcp/tests/mcp_stdio_test.py b/packages/genkit-mcp/tests/mcp_stdio_test.py index 360b501ae..b21f3dc5b 100644 --- a/packages/genkit-mcp/tests/mcp_stdio_test.py +++ b/packages/genkit-mcp/tests/mcp_stdio_test.py @@ -63,10 +63,12 @@ async def call_over_stdio(tools: list[str], **env: str) -> tuple[list[str], str] lines = await asyncio.wait_for(_read_until_answered(process.stdout, len(tools)), timeout=LIMIT) process.stdin.close() rest, stderr = await asyncio.wait_for(process.communicate(), timeout=LIMIT) - except (AssertionError, asyncio.TimeoutError) as error: + except BaseException as error: process.kill() _, stderr = await process.communicate() - raise AssertionError(f'{error!r}\nserver stderr:\n{stderr.decode()}') from error + if isinstance(error, (AssertionError, asyncio.TimeoutError)): + raise AssertionError(f'{error!r}\nserver stderr:\n{stderr.decode()}') from error + raise return lines + rest.decode().splitlines(), stderr.decode() @@ -74,6 +76,8 @@ async def call_over_stdio(tools: list[str], **env: str) -> tuple[list[str], str] async def test_stdout_carries_only_json_rpc_once_the_server_is_serving() -> None: """Logging, a child process, descriptor 1 and the original stdout all land on stderr while serving. + A child process cannot read the client's requests either: its stdin is the null device. + What the app writes before ``start()`` runs is another matter: stdout is not the wire yet, so it is flushed there ahead of the first frame. """ @@ -86,6 +90,7 @@ async def test_stdout_carries_only_json_rpc_once_the_server_is_serving() -> None for text in ( 'serving plain text', 'written by a child process', + "child read ''", 'written to descriptor 1', 'written to the original stdout', ): diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 3bf49f721..4c6a51be5 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -711,7 +711,7 @@ async def menu_price(dish: str) -> float: async def list_tools(self) -> list[Tool]: """Return every tool registered on this app, sorted by name. - Each is the same handle ``lookup_tool`` returns. Every plugin is initialized + Each is the kind of handle ``lookup_tool`` returns. Every plugin is initialized first, so tools a plugin registers in ``init()`` are included, and a plugin whose ``init()`` fails makes this raise. Tools a plugin only lists in ``list_actions()`` are registered, and so included, once something has From 4fe74b2a27bbe7037cf11bbca5fd1c7876eca884 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 15:26:05 +0100 Subject: [PATCH 6/8] fix(py/plugins/mcp): check every MCP result encodes and refresh changed descriptions --- packages/genkit-mcp/README.md | 41 +++++++-------- packages/genkit-mcp/src/genkit_mcp/_server.py | 50 ++++++++++++++----- packages/genkit-mcp/tests/mcp_server_test.py | 36 +++++++++++-- 3 files changed, 91 insertions(+), 36 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 2f8251427..9b2aeec70 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -200,21 +200,23 @@ The app's tools are read with `ai.list_tools()` on every `tools/list`, so a tool server was built is still served. A tool whose input is not an object, such as a single scalar or an optional model, is skipped: MCP arguments are always an object, and such a tool is not callable by name either, rather than being listed and then failing. A model that refers to itself is served. -An output schema is advertised only for a tool defined with `@ai.tool()` that returns an object -itself, such as `-> Shelf`. A client rejects a result that lacks the structured content a schema -promised, and a tool returning `MultipartToolResponse[Shelf]` may leave its output out. Tools a -dynamic action provider supplies, from `define_mcp_client` for instance, are not defined on the app -and are not served. - -A tool that raises answers with an error result, worded as a served flow's error body is. A -`PublicError` sends its status and message, and arguments the tool's input model rejects send the -failing fields without their values. Any other `GenkitError` sends `Tool '' failed: `, -and any other exception `Tool '' failed`, since a provider's error text can name a project, a -resource path or a URL. So raise a `PublicError` for a failure the model should read and retry. The -full error is logged on the server either way. A tool that interrupts for the user's input answers -with an error result saying so, since MCP cannot pause a call, and so does a result that cannot be -encoded as UTF-8. A plugin that fails to start fails the listing, and the client is told only that -the server could not list its tools. +An output schema is advertised only for a tool built as a `Tool`, as `@ai.tool()` builds one, that +returns an object itself, such as `-> Shelf`. A client rejects a result that lacks the structured +content a schema promised, and a tool returning `MultipartToolResponse[Shelf]` may leave its output +out. Tools a dynamic action provider supplies, from `define_mcp_client` for instance, are not +defined on the app and are not served. + +Arguments that do not match a tool's input schema are rejected by the MCP SDK before the tool runs, +with an error that quotes them. A tool that raises answers with an error result, worded as a served +flow's error body is. A `PublicError` sends its status and message, and arguments the input model's +own validators reject send the failing fields without their values. Any other `GenkitError` sends +`Tool '' failed: `, and any other exception `Tool '' failed`, since a provider's +error text can name a project, a resource path or a URL. So raise a `PublicError` for a failure the +model should read and retry. The full error is logged on the server either way. A tool that +interrupts for the user's input answers with an error result saying so, since MCP cannot pause a +call. A result that cannot be encoded as UTF-8 answers with `Tool '' failed`. A plugin that +fails to start fails the listing, and the client is told only that the server could not list its +tools. ### stdio @@ -241,8 +243,7 @@ input is not an object is not served at all, and an output schema is advertised above, so a client is told less about such a tool than Genkit knows. The advertised schema is the one Genkit validates input against, so an output model whose dumped JSON differs from it, through a `serialization_alias` or a `computed_field` on a model that forbids extra fields, fails the client's -check of the result. Nothing sends -`notifications/tools/list_changed`; the list is re-read per request instead. A client's -`notifications/cancelled` cancels the tool call. Progress, sampling and elicitation are not -supported. A plugin-namespaced tool name carries a `/`, which the MCP SDK warns about. stdio reads -and writes UTF-8 whatever the locale, but is untested on Windows. +check of the result. Nothing sends `notifications/tools/list_changed`; the list is re-read per +request instead. A client's `notifications/cancelled` cancels the tool call. Progress, sampling and +elicitation are not supported. A plugin-namespaced tool name carries a `/`, which the MCP SDK warns +about. stdio reads and writes UTF-8 whatever the locale, but is untested on Windows. diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index 5f4e1e65c..c0242d119 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -71,7 +71,7 @@ def __init__( self._name = name self._version = version self._redirect_stdout = redirect_stdout - self._described: dict[str, tuple[dict[str, Any], McpTool | None]] = {} + self._described: dict[str, tuple[tuple[object, ...], McpTool | None]] = {} self._server: Server[Any, Any] = Server(name, version=version, instructions=instructions) self._server.list_tools()(self._list_tools) self._server.call_tool()(self._call_tool) @@ -113,9 +113,9 @@ async def start(self) -> None: processes can neither write between frames nor read them. """ stdin, stdout = _wire_files() - if self._redirect_stdout: - _move_stdio_off_the_wire() with stdin, stdout: + if self._redirect_stdout: + _move_stdio_off_the_wire() async with stdio_server(stdin=anyio.wrap_file(stdin), stdout=anyio.wrap_file(stdout)) as streams: await self.serve(*streams) @@ -137,10 +137,11 @@ async def _served_tools(self) -> list[tuple[Tool, McpTool]]: served: list[tuple[Tool, McpTool]] = [] for tool in tools: # A plain tool action comes back as a new view on every listing, so - # the description is keyed by name and the metadata the view shares. + # the description is keyed by name and by everything it is built from. + source = _description_source(tool) cached = self._described.get(tool.name) - if cached is None or cached[0] is not tool.metadata: - cached = (tool.metadata, tool_to_mcp(tool)) + if cached is None or cached[0] != source: + cached = (source, tool_to_mcp(tool)) self._described[tool.name] = cached described = cached[1] if described is not None: @@ -150,6 +151,20 @@ async def _served_tools(self) -> list[tuple[Tool, McpTool]]: async def _call_tool(self, name: str, arguments: dict[str, Any]) -> CallToolResult: """Run one tool and map what it returned, reporting every failure as a result. + A result that cannot be encoded, such as text with a lone surrogate, + fails here rather than in the transport, where it would end the session. + """ + result = await self._answer(name, arguments) + try: + result.model_dump_json(by_alias=True, exclude_none=True) + except ValueError: + logger.exception('an MCP tool result could not be encoded', tool=name) + return error_result(f'Tool {name!r} failed') + return result + + async def _answer(self, name: str, arguments: dict[str, Any]) -> CallToolResult: + """Run one tool and map what it returned or raised. + A raised error becomes an ``isError`` result and is logged here, where its traceback is still useful. """ @@ -159,11 +174,7 @@ async def _call_tool(self, name: str, arguments: dict[str, Any]) -> CallToolResu context = self._request_context() try: - result = multipart_to_call_result(await _run(tool, arguments, context), name) - # Fail here rather than in the transport, where a result that cannot - # be encoded, such as text with a lone surrogate, ends the session. - result.model_dump_json(by_alias=True, exclude_none=True) - return result + return multipart_to_call_result(await _run(tool, arguments, context), name) except Interrupt: logger.warning('an MCP tool call paused for input, which MCP cannot ask for', tool=name) return error_result(f'Tool {name!r} paused for input from the user, which this server cannot ask for') @@ -204,7 +215,8 @@ def create_mcp_server( name: Name the server advertises. version: Version the server advertises. instructions: How a client should use this server. - redirect_stdout: Whether ``start`` moves this process's stdout to stderr. + redirect_stdout: Whether ``start`` moves this process's stdout to stderr + and its stdin to the null device. Returns: A server ready for ``start`` or ``serve``. @@ -218,6 +230,18 @@ def create_mcp_server( ) +def _description_source(tool: Tool) -> tuple[object, ...]: + """Everything ``tool_to_mcp`` reads, so an unchanged tool reuses its description.""" + return ( + tool.description, + tool.input_schema, + tool.output_schema, + tool.model_output_schema, + tool.wire_action is None, + tool.metadata.get('mcp'), + ) + + async def _run(tool: Tool, arguments: dict[str, Any], context: dict[str, Any] | None) -> MultipartToolResponse: """Run a tool and return what it produced as a tool response envelope. @@ -278,9 +302,9 @@ def _move_stdio_off_the_wire() -> None: bound to the originals. Rebinding ``sys.stdout`` covers ``print`` and structlog's default logger, which reads ``sys.stdout`` on every call. """ - os.dup2(2, 1) null = os.open(os.devnull, os.O_RDONLY) try: + os.dup2(2, 1) os.dup2(null, 0) finally: os.close(null) diff --git a/packages/genkit-mcp/tests/mcp_server_test.py b/packages/genkit-mcp/tests/mcp_server_test.py index 4971e388d..473dd241d 100644 --- a/packages/genkit-mcp/tests/mcp_server_test.py +++ b/packages/genkit-mcp/tests/mcp_server_test.py @@ -251,11 +251,41 @@ async def filename() -> str: """Name a file.""" return 'notes-\udcff.txt' + @ai.tool() + async def missing() -> str: + """Report a file that is not there.""" + raise PublicError(status='NOT_FOUND', message='no file notes-\udcff.txt') + async with connected(create_mcp_server(ai, 'bookshop')) as session: - result = await session.call_tool('filename', {}) + returned = await session.call_tool('filename', {}) + raised = await session.call_tool('missing', {}) - assert result.isError is True - assert text_of(result) == "Tool 'filename' failed" + assert (returned.isError, text_of(returned)) == (True, "Tool 'filename' failed") + assert (raised.isError, text_of(raised)) == (True, "Tool 'missing' failed") + + +@pytest.mark.asyncio +async def test_a_tool_registered_again_under_its_name_is_described_afresh() -> None: + """A plugin may hand the same metadata to a replacement, so the description follows what it is built from.""" + ai = app() + metadata: dict[str, object] = {} + + async def lookup(_: dict[str, object]) -> str: + return 'found' + + def register(input_schema: dict[str, object]) -> None: + action = Action(kind=ActionKind.TOOL, name='lookup', fn=lookup, metadata=metadata) + action.input_schema = input_schema + ai._registry.register_action_from_instance(action) + + register({'type': 'object', 'properties': {'isbn': {'type': 'string'}}}) + async with connected(create_mcp_server(ai, 'bookshop')) as session: + before = await session.list_tools() + register({'type': 'object', 'properties': {'title': {'type': 'string'}}}) + after = await session.list_tools() + + assert list(before.tools[0].inputSchema['properties']) == ['isbn'] + assert list(after.tools[0].inputSchema['properties']) == ['title'] @pytest.mark.asyncio From 9f0a31cf1e8464eee8393a7e98cf2d183ef7ed37 Mon Sep 17 00:00:00 2001 From: Hilary Date: Wed, 11 Nov 2026 13:48:04 +0100 Subject: [PATCH 7/8] docs(mcp): link the server tracking issue in this repo --- packages/genkit-mcp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 9b2aeec70..43ea33bcf 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -5,7 +5,7 @@ exposes that server's tools as Genkit `tool` actions through a dynamic action pr serves a Genkit app's own tools to MCP clients. Tracking issues: (client), - (server) + (server) ## Usage From 43c52de16bc4fead61d1183354746322bdf6a311 Mon Sep 17 00:00:00 2001 From: Hilary Date: Wed, 11 Nov 2026 14:12:24 +0100 Subject: [PATCH 8/8] fix(mcp): log an error meant for the caller as one line, not a traceback --- packages/genkit-mcp/README.md | 7 +++-- packages/genkit-mcp/src/genkit_mcp/_server.py | 20 +++++++++++-- packages/genkit-mcp/tests/mcp_server_test.py | 28 +++++++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 43ea33bcf..075f60667 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -212,9 +212,10 @@ flow's error body is. A `PublicError` sends its status and message, and argument own validators reject send the failing fields without their values. Any other `GenkitError` sends `Tool '' failed: `, and any other exception `Tool '' failed`, since a provider's error text can name a project, a resource path or a URL. So raise a `PublicError` for a failure the -model should read and retry. The full error is logged on the server either way. A tool that -interrupts for the user's input answers with an error result saying so, since MCP cannot pause a -call. A result that cannot be encoded as UTF-8 answers with `Tool '' failed`. A plugin that +model should read and retry. Such an error, like rejected arguments, is logged on the server as one +warning line. Any other failure is logged with its traceback. A tool that interrupts for the user's +input answers with an error result saying so, since MCP cannot pause a call. A result that cannot +be encoded as UTF-8 answers with `Tool '' failed`. A plugin that fails to start fails the listing, and the client is told only that the server could not list its tools. diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index c0242d119..285455b4c 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -179,8 +179,12 @@ async def _answer(self, name: str, arguments: dict[str, Any]) -> CallToolResult: logger.warning('an MCP tool call paused for input, which MCP cannot ask for', tool=name) return error_result(f'Tool {name!r} paused for input from the user, which this server cannot ask for') except Exception as error: - logger.exception('an MCP tool call failed', tool=name) - return error_result(_client_message(name, error)) + message = _client_message(name, error) + if _for_the_caller(error): + logger.warning('an MCP tool call failed', tool=name, error=message) + else: + logger.exception('an MCP tool call failed', tool=name) + return error_result(message) def _request_context(self) -> dict[str, Any] | None: """Pass the request's MCP ``_meta`` in the shape the client's handler reads.""" @@ -276,7 +280,7 @@ def _client_message(tool_name: str, error: Exception) -> str: status, since a provider's error text can name a project, a resource path or a URL. """ - if isinstance(error, PublicError) or error_status(error) < 500: + if _for_the_caller(error): body = error_body(error) return f'{body["status"]}: {body["message"]}' if isinstance(error, GenkitError): @@ -284,6 +288,16 @@ def _client_message(tool_name: str, error: Exception) -> str: return f'Tool {tool_name!r} failed' +def _for_the_caller(error: Exception) -> bool: + """Whether the error is the tool answering the caller rather than failing. + + A ``PublicError`` and arguments the tool's input model rejects are both + meant for the model to read, so a log line is enough and no traceback is + kept for them. + """ + return isinstance(error, PublicError) or error_status(error) < 500 + + def _wire_files() -> tuple[TextIO, TextIO]: """Open copies of descriptors 0 and 1 for the transport, as UTF-8 whatever the locale. diff --git a/packages/genkit-mcp/tests/mcp_server_test.py b/packages/genkit-mcp/tests/mcp_server_test.py index 473dd241d..ef922d15c 100644 --- a/packages/genkit-mcp/tests/mcp_server_test.py +++ b/packages/genkit-mcp/tests/mcp_server_test.py @@ -339,6 +339,34 @@ async def book() -> str: assert result.content == [TextContent(type='text', text='INVALID_ARGUMENT: date must be in the future')] +@pytest.mark.asyncio +async def test_an_error_for_the_caller_logs_one_line_and_a_crash_logs_its_traceback() -> None: + """A deliberate error is the tool answering, so only a real failure keeps its traceback.""" + ai = app() + + @ai.tool() + async def find_book() -> str: + """Find a book.""" + raise PublicError(status='NOT_FOUND', message='no such book') + + @ai.tool() + async def explode() -> str: + """Fail.""" + raise ValueError('shelf collapsed') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + with capture_logs() as logs: + await session.call_tool('find_book', {}) + await session.call_tool('explode', {}) + + failures = [ + (entry['tool'], entry['log_level'], entry.get('exc_info', False)) + for entry in logs + if entry['event'] == 'an MCP tool call failed' + ] + assert failures == [('find_book', 'warning', False), ('explode', 'error', True)] + + @pytest.mark.asyncio async def test_a_provider_error_sends_only_its_status() -> None: """A provider's error text can name a project or a resource path, so it stays on the server."""