Skip to content
94 changes: 91 additions & 3 deletions packages/genkit-mcp/README.md
Original file line number Diff line number Diff line change
@@ -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: <https://github.com/genkit-ai/genkit/issues/6194>
Tracking issues: <https://github.com/genkit-ai/genkit/issues/6194> (client),
<https://github.com/genkit-ai/genkit-python/issues/91> (server)

## Usage

Expand Down Expand Up @@ -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 '<name>' failed: <status>`, and any other exception `Tool '<name>' 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 '<name>' 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.
2 changes: 1 addition & 1 deletion packages/genkit-mcp/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
8 changes: 5 additions & 3 deletions packages/genkit-mcp/src/genkit_mcp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
255 changes: 255 additions & 0 deletions packages/genkit-mcp/src/genkit_mcp/_export.py
Original file line number Diff line number Diff line change
@@ -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<mime>[^;,]+);base64,(?P<data>.*)$', 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,
),
)
Loading
Loading