Skip to content

feat(py/plugins/mcp): serve Genkit tools over MCP stdio - #6882

Closed
cabljac wants to merge 15 commits into
mainfrom
feat/py-mcp-server-1-stdio
Closed

cabljac wants to merge 15 commits into
mainfrom
feat/py-mcp-server-1-stdio

Conversation

@cabljac

@cabljac cabljac commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #6365 (package scaffold) and #6881 (ai.list_tools()). The first commit is #6881's and drops on rebase once it merges. Review the second commit only. Independent of the client stack (#6366 to #6384).

What's new

create_mcp_server(ai, name, *, version='1.0.0', instructions=None, redirect_stdout=True) serves a Genkit app's own tools to MCP clients. await server.start() serves on stdio until stdin closes. await server.serve(read, write) serves on any SDK stream pair. These are the package's first public names: McpServer, create_mcp_server.

  • Built on the lowlevel SDK Server, not FastMCP. Each tools/list reads ai.list_tools(), so a tool defined after the server is still served.
  • Every tool defined on the app is served, as in JS and Go. Tools a dynamic action provider serves are not.
  • A tool whose input is not an object is skipped (warned once), since MCP arguments are always an object. {} becomes {'type': 'object', 'properties': {}}.
  • outputSchema is advertised only for an object schema, read from originalOutputSchema.
  • A tool error is an isError result. A GenkitError sends status: message without its cause. Anything else sends only Tool '<name>' failed. This is stricter than JS, because exception text can carry a URL or a credential.
  • start() captures the real stdout for the transport, then points sys.stdout at stderr. It flushes the old stdout first, so text printed before start() cannot land between frames. stdio is UTF-8 whatever the locale.
from genkit import Genkit
from genkit_mcp import create_mcp_server

ai = Genkit()

@ai.tool()
async def opening_hours(day: Day) -> str:
    """Report the shop's opening hours for a day of the week."""
    ...

server = create_mcp_server(ai, 'bookshop', instructions='Ask about the shop.')
asyncio.run(server.start())

Part of genkit-ai/genkit-python#219.

Why

Python can call an MCP server but cannot be one. JS (createMcpServer) and Go both ship a server. stdout is the stdio wire, and structlog's default logger writes there, so one log line corrupts a JSON-RPC frame.

Tests

  • tests/mcp_server_test.py: in-memory client session. Late tools are listed, name, version and tools-only capabilities, text, structured and media results, error results with and without a GenkitError cause, request _meta reaches the tool context, unknown tools, DAP tools not served.
  • tests/mcp_export_test.py: output and part mapping to MCP content, dropped parts warn, input schema shapes, including self-referencing and optional models.
  • tests/mcp_stdio_test.py: start() in a raw subprocess, with no client. stdout carries only JSON-RPC under GENKIT_LOG=debug, non-ASCII text survives an ASCII locale, text buffered before start() is flushed ahead of the first frame, redirect_stdout=False leaves stdout alone, and a logger cached before start() follows the swap.
  • tests/mcp_exports_test.py: the public surface.
  • py/packages/genkit-mcp: 64 passed. ruff, pyrefly, ty and pyright clean.

Not in this PR

  • Round-trip tests and sample: the round trip through define_mcp_client, the inverse checks against call_result_to_multipart, and the mcp-server-hello sample all need the client. They follow once both stacks land.
  • Publishing: the publish workflow entry and genkit[mcp] extra land with the client in feat(py/plugins/mcp): define MCP servers as dynamic tool providers #6369.
  • Prompts: needs a core ai.list_prompts(). Follow-up.
  • Resources and list_changed: not served. Progress, cancellation, sampling and elicitation are not supported.
  • Conflicts: __init__.py, mcp_exports_test.py, README.md and pyproject.toml (anyio) also change in the client stack. Whichever lands second takes both sides.

cabljac and others added 13 commits October 20, 2026 11:37
Python has no MCP client, so Python users cannot call tools hosted by an
MCP server. JS and Go both ship one.

Add the genkit-mcp package and wire it into the workspace: root dependency
and uv source, type-checker source lists, and the mcp dependency moved from
the root dev group into the package that needs it. structlog is declared
here, as the other plugins declare it, rather than leaned on through genkit.

_errors.py lands here, with the scaffold, because it is nothing but class
definitions. The base is McpClientError, and it deliberately does not derive
from RuntimeError: the MCP SDK reports a tool result that fails the server's
own output schema as a bare RuntimeError, and the tool wrapper folds that one
into an isError envelope for the model. Sharing a base class with it would
send a dead subprocess to the model as a retryable tool error. McpError is
taken by the SDK, so the names here are McpClientError,
McpConnectionClosedError, McpConnectionFailedError and McpProtocolError.

McpStdioServerConfig.env documented the opposite of what the SDK does.
stdio_client passes get_default_environment() when env is None, which is
HOME, LOGNAME, PATH, SHELL, TERM and USER on posix, and merges a supplied env
over that same minimum rather than replacing it. Neither case inherits this
process's environment, so a user who expects GEMINI_API_KEY or AWS_* to reach
the child gets a silent failure. cwd accepts os.PathLike too, matching the
SDK, so a Path does not have to be stringified.

The package is deliberately absent from the publish workflow and exports no
public API. Both arrive with the client implementation, so no release can
ship a genkit-mcp whose entry point raises, or a genkit[mcp] extra pointing
at a distribution that does not exist on PyPI.
mcp 2.x renames isError, structuredContent and inputSchema to snake_case,
so a fresh install outside the lock resolved an SDK this package does not
speak. Cap the dependency at <2 to match the 1.26 lock.

The close and restart docstrings contradicted McpConnectionClosedError
about whether a closed client could come back.

The stdio config carries secrets in env, so its values must not leak
through repr or validation errors. A misspelled key such as enviroment
was silently dropped, which launched the server without its secret;
unknown keys now fail, while the type marker that mcpServers blocks
carry is still accepted.
…lic surface

The Python plugins on main export only what a caller needs, take flat
keyword arguments instead of nested option objects (#6706), and report
failures as GenkitError with a status rather than plugin error classes
(#6710). The MCP client follows the same rules.

define_mcp_client takes command, args, env and cwd as keyword
arguments. McpStdioServerConfig stays as the internal model those
arguments build. The provider name is also the tool name prefix, as in
the Go plugin, so tool_prefix goes away. disabled goes away too: not
calling define_mcp_client does the same.

The error classes become private GenkitError subclasses: a closed
client is FAILED_PRECONDITION, a server that cannot start or dies is
UNAVAILABLE, and a protocol violation is INTERNAL.
anyio.fail_after(0) raises at the first checkpoint, so a timeout of 0,
which reads as "no timeout", would fail every request at once. Raise
ValueError for zero or negative values in define_mcp_client and in
McpConnection, and document None as the only way to disable the timeout.
Some servers take credentials as arguments, for example a postgres
connection URL, so args are hidden from repr like env.
…ive values

Core treats 0 like None and uses the 3 second default, and a negative
value disables the cache. A caller passing 0 to mean "always re-list"
would otherwise get 3 seconds.
…v UI

The client holds one connection per event loop, and the Dev UI
reflection server runs its own loop, so a second server process starts
while it runs. State a stateful server keeps diverges between the two,
and servers that take a port, lock file or browser profile can clash.
The copied list of inherited variables mirrored a private SDK constant
and would drift. Reference the public mcp.client.stdio function instead
and keep the warning that the parent environment is not inherited.
Wrap the top-level await in an async main run by asyncio.run, configure
a model, and close the client in a finally block.
Add Framework :: AsyncIO, Framework :: Pydantic :: 2, Typing :: Typed
and the rest of the block genkit-middleware declares.
ai.registry is private since #6690, and Genkit can look up one tool by
name but cannot enumerate them. Anything that serves an app's tools to
something else, such as an MCP server, has no public way to find them.

list_tools() returns one Tool handle per registered tool, the same
handle lookup_tool() returns. It promises no order: plugin tools are
registered when plugins start, not where the app defines them. It
starts every plugin first, since Python starts plugins lazily and a
plugin may register tools in init(). A plugin whose init() fails makes
it raise, as registry listing already does, rather than return a list
that looks complete but is missing that plugin's tools.

Tools a plugin only advertises in list_actions() and builds in
resolve() are listed once something has looked them up. Building them
eagerly would call every plugin's list_actions(), which for some
plugins is a network call. Tools a dynamic action provider serves are
left out: they are not defined on the app, and listing them would reach
the provider's transport. Both match Go's genkit.ListTools, which lists
registered tools only.

The GenkitLike protocol middleware sees is unchanged.
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 '<name>' 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.
@github-actions github-actions Bot added docs Improvements or additions to documentation python Python config labels Oct 23, 2026
@cabljac
cabljac changed the base branch from feat/py-mcp-scaffold to main October 23, 2026 16:40
@cabljac
cabljac added this pull request to stack #6884 October 23, 2026 16:40
@cabljac
cabljac removed this pull request from stack #6884 October 23, 2026 16:40
@cabljac
cabljac changed the base branch from main to feat/py-mcp-scaffold October 23, 2026 16:40
@cabljac
cabljac added this pull request to stack #6885 October 23, 2026 16:40

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the MCP (Model Context Protocol) server implementation for Genkit in Python, allowing Genkit app tools to be served to MCP clients. It adds the McpServer class, helper functions, and a new list_tools method on the main Genkit class, supported by comprehensive unit and integration tests. The review feedback highlights several runtime issues, including an invalid async call to logger.aexception which will cause an AttributeError, a potential TypeError when matching non-string media URLs, a risk of TypeError when using WeakKeyDictionary with non-weak-referenceable keys, and the recommendation to flush sys.stdout before redirecting it to prevent stream corruption.

return error_result(f'Tool {name!r} did not return a tool response')
return multipart_to_call_result(response, name)
except Exception as error:
await logger.aexception('an MCP tool call failed', tool=name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

structlog loggers do not have an async aexception method. Calling await logger.aexception(...) will raise an AttributeError at runtime, crashing the error handler. Use the synchronous logger.exception(...) instead.

Suggested change
await logger.aexception('an MCP tool call failed', tool=name)
logger.exception('an MCP tool call failed', tool=name)

Comment on lines +205 to +206
url = part.media.url
match = _DATA_URL.match(url)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If part.media.url is None or not a string, calling _DATA_URL.match(url) will raise a TypeError: expected string or bytes-like object. We should defensively check that url is a string before matching.

        url = part.media.url
        if not isinstance(url, str):
            logger.warning('dropping a media part with missing or invalid URL', tool=tool_name, index=index)
            return None
        match = _DATA_URL.match(url)

self._name = name
self._version = version
self._redirect_stdout = redirect_stdout
self._described: WeakKeyDictionary[Action, Tool | None] = WeakKeyDictionary()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using WeakKeyDictionary requires keys to be weak-referenceable. Many Pydantic models or classes with __slots__ do not support weak references by default, which can lead to a TypeError at runtime. Since Action objects are long-lived registry singletons, there is no risk of memory leaks, so a standard dict is safer and simpler.

Suggested change
self._described: WeakKeyDictionary[Action, Tool | None] = WeakKeyDictionary()
self._described: dict[Action, Tool | None] = {}

``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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It is highly recommended to flush sys.stdout before reassigning it to sys.stderr. Any buffered data in sys.stdout could otherwise be flushed later and corrupt the MCP JSON-RPC stdio stream.

Suggested change
sys.stdout = sys.stderr
sys.stdout.flush()
sys.stdout = sys.stderr

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.
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.
Base automatically changed from feat/py-mcp-scaffold to main October 30, 2026 10:54
@hilariie

Copy link
Copy Markdown
Contributor

Moved to genkit-ai/genkit-python/pull/93

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

config docs Improvements or additions to documentation python Python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants