Skip to content

feat(mcp): serve Genkit tools over MCP stdio - #93

Open
hilariie wants to merge 8 commits into
feat/core-list-toolsfrom
feat/mcp-server-stdio
Open

hilariie wants to merge 8 commits into
feat/core-list-toolsfrom
feat/mcp-server-stdio

Conversation

@hilariie

Copy link
Copy Markdown
Contributor

Stacked on #92 (ai.list_tools()), which merges first.

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, and await server.serve(read, write) serves on any MCP SDK stream pair.

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())

Changes

  • McpServer and create_mcp_server join the genkit_mcp exports, built on the MCP SDK's lowlevel Server. Each tools/list reads ai.list_tools(), so a tool defined after the server is still served. Tools a dynamic action provider serves are not.
  • A tool whose input is not an object is neither listed nor callable, since MCP arguments are always an object.
  • An output schema is advertised only for a Tool that returns an object itself. A tool returning MultipartToolResponse[T] can leave its output out, and a client rejects a result without the structured content its schema promised.
  • A PublicError sends its status and message, and arguments the input model's own validators reject name the failing fields, as genkit.web.error_body does for served flows. Any other GenkitError sends only its status and anything else Tool '<name>' failed, since provider text can carry a project id or a URL. A plugin that fails to start fails the listing with a fixed message.
  • An interrupt answers with an error result saying MCP cannot pause for input, and a result that cannot be encoded becomes an error result instead of ending the session.
  • start() gives the transport copies of fds 0 and 1, then points fd 1 and sys.stdout at stderr and fd 0 at the null device. print, loggers, child processes and C extensions cannot write between frames or read the client's requests. redirect_stdout=False leaves both alone.
  • Data parts travel as JSON text, under the same rule as text parts.

Not in this PR: the sample (S2), streamable HTTP (S3), prompts (S4), and the opt-in walk over dynamic action provider tools.

Breaking changes

None.

Verification

  • mcp_server_test.py drives the server through the SDK's in-memory client: late tools, schemas, plain tool actions, every error path, interrupts, unencodable results and request _meta.
  • mcp_stdio_test.py runs the server as a child process and checks that stdout carries only JSON-RPC while tools print, log, spawn children and write to fd 1, that an app which already moved sys.stdout is still answered, and that non-ASCII text survives an ASCII locale.
  • mcp_export_test.py covers the result and schema mapping.

Part of #91.

cabljac and others added 7 commits November 11, 2026 13:47
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.

Upstream-Commit: genkit-ai/genkit@504c426f0
Upstream-PR: genkit-ai/genkit#6882
start() owns this process's stdin and stdout, and nothing in the slice
exercised it. These tests drive the fixture app as a child with plain
JSON-RPC lines, so they need no MCP client.

Every stdout line after the first frame parses as JSON-RPC under
GENKIT_LOG=debug, and a log line written while serving reaches stderr.
A child forced into an ASCII locale, with UTF-8 mode and locale
coercion off, still answers with non-ASCII text intact; under
PYTHONIOENCODING alone the test passed without the fix, since a bare
TextIOWrapper reads the locale, not that variable. redirect_stdout=False
leaves sys.stdout alone, and a structlog logger cached before start()
follows the swap to stderr.

Upstream-Commit: genkit-ai/genkit@c1974e9a6
Upstream-PR: genkit-ai/genkit#6882
start() wraps sys.stdout.buffer in a new text stream for the transport.
Text the app printed earlier without a newline sat in the old stream's
buffer, which flushed whenever it was next written or collected: after
the transport had started, so it could land between two frames.
Flushing first puts it out ahead of the first frame. It still reaches
the client as stray output, as anything logged before start() does,
but it can no longer split a frame.

Upstream-Commit: genkit-ai/genkit@05a4e5542
Upstream-PR: genkit-ai/genkit#6882
Listing failures and non-public errors no longer reach the client verbatim,
stdio serves on copies of fds 0 and 1 with fd 1 moved to stderr, output
schemas are only advertised when the output is always there, and interrupts
and data parts get deliberate results.
Plain tool actions get no output schema and dump by alias, error text follows
genkit.web.error_body, unencodable results become error results, stdin moves
to /dev/null with stdout, and descriptions are cached by name.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants