diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index edad9de81..075f60667 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,89 @@ 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 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. 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. + +### stdio + +`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. + +### 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 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. 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. 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..38375c6c4 --- /dev/null +++ b/packages/genkit-mcp/src/genkit_mcp/_export.py @@ -0,0 +1,255 @@ +# 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 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. + 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 []): + 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) + 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. + + 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, 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 + return original + + +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.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) + 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..285455b4c --- /dev/null +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -0,0 +1,325 @@ +# 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 os +import sys +from typing import Any, TextIO + +import anyio +from mcp.server.lowlevel import Server +from mcp.server.stdio import stdio_server +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, 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__) + +_JSON = TypeAdapter(object) + +DEFAULT_VERSION = '1.0.0' +"""The version a server advertises when the app names none.""" + +_LISTING_FAILED = 'The server could not list its tools' + + +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 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: 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) + + @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. + + 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() + 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) + + 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. + """ + 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 tools: + # A plain tool action comes back as a new view on every listing, so + # 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] != source: + cached = (source, tool_to_mcp(tool)) + self._described[tool.name] = cached + described = cached[1] + 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 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. + """ + 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 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: + 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.""" + 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 + and its stdin to the null device. + + Returns: + A server ready for ``start`` or ``serve``. + """ + return McpServer( + ai, + name, + version=version, + instructions=instructions, + redirect_stdout=redirect_stdout, + ) + + +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. + + 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, 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 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. + + 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 _for_the_caller(error): + 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' + + +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. + + 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 _move_stdio_off_the_wire() -> None: + """Point stdout at stderr and stdin at the null device, so nothing else can use the wire. + + 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. + """ + null = os.open(os.devnull, os.O_RDONLY) + try: + os.dup2(2, 1) + 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 new file mode 100644 index 000000000..2261f157f --- /dev/null +++ b/packages/genkit-mcp/tests/genkit_server.py @@ -0,0 +1,70 @@ +# 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, 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 + +from genkit_mcp import create_mcp_server + +from genkit import Genkit, get_logger + +logger = get_logger(__name__) + +ai = Genkit() + + +@ai.tool() +async def plain_text() -> str: + """Return a string.""" + logger.info('serving plain text') + return 'plain text' + + +@ai.tool() +async def accented() -> str: + """Return text outside ASCII.""" + return 'café 東京' + + +@ai.tool() +async def raw_writes() -> str: + """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 + sys.__stdout__.write('written to the original stdout\n') + sys.__stdout__.flush() + return 'wrote' + + +@ai.tool() +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, 'stdio-test', redirect_stdout=os.environ.get('MCP_TEST_NO_REDIRECT') != '1') + +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 new file mode 100644 index 000000000..68d8bfe6d --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_export_test.py @@ -0,0 +1,323 @@ +# 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_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') + + 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.' + 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 +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..ef922d15c --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_server_test.py @@ -0,0 +1,539 @@ +# 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.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, Field, field_validator +from structlog.testing import capture_logs + +from genkit import Genkit, MultipartToolResponse, Part, PublicError, Tool, ToolContext +from genkit.plugin_api import Action, ActionKind, Plugin, provider_error + + +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 + + +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.""" + 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_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') + + async with connected(server) as session: + before = await session.list_tools() + + @ai.tool() + async def late() -> str: + """Defined after the first listing.""" + return 'here' + + 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 +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 == 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_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 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='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: + listed = await session.list_tools() + labelled = await session.call_tool('label', {}) + photographed = await session.call_tool('photo', {}) + + 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' + + @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: + returned = await session.call_tool('filename', {}) + raised = await session.call_tool('missing', {}) + + 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 +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_without_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_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 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', {}) + + 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_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.""" + 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() + 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' + + 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() + + skipped = [entry['tool'] for entry in logs if entry['log_level'] == 'warning'] + assert sorted(skipped) == ['shout', 'whisper'] + + +@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': {}} 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..b21f3dc5b --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_stdio_test.py @@ -0,0 +1,165 @@ +# 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 json +import os +import sys +from pathlib import Path +from typing import Any + +import pytest + +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 + + +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': 0, + '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': {}}} + for call_id, tool in enumerate(tools, start=1) + ), + ] + + +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), + 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 + 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 BaseException as error: + process.kill() + _, stderr = await process.communicate() + 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() + + +@pytest.mark.asyncio +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. + """ + lines, stderr = await call_over_stdio(['plain_text', 'raw_writes']) + + 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', + "child read ''", + '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' + ) + + assert _results(lines) == {1: 'café 東京'} + + +@pytest.mark.asyncio +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 _results(lines) == {1: 'plain text'} + + +@pytest.mark.asyncio +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') + + 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 + + +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() + 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') == 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: + 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}') 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