Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 77 additions & 1 deletion packages/genkit-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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. It also
serves a Genkit app's own tools to MCP clients.
serves a Genkit app's own tools to MCP clients over stdio or streamable HTTP.

Tracking issues: <https://github.com/genkit-ai/genkit/issues/6194> (client),
<https://github.com/genkit-ai/genkit-python/issues/91> (server)
Expand Down Expand Up @@ -232,6 +232,82 @@ 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.

### Streamable HTTP

`server.asgi_app()` returns a Starlette app answering on `/mcp`, which uvicorn or any ASGI server
can serve as it is:

```python
app = server.asgi_app() # uvicorn myserver:app
```

Pass `stateless=True` for a fresh transport per request with no session id, `json_response=True` for
one JSON body instead of an SSE stream, and, when stateful, `event_store=` to let a reconnecting
client replay what it missed. Nothing here touches stdout: only stdio makes stdout the wire.

The endpoint has no authentication. Anyone who can reach it can list and call every tool the app
defines, so bind it to localhost, which uvicorn does by default, or put authentication in front of
it before you bind it to a public interface. Mounting it in an app that already authenticates
requests is one way to do that.

A request whose `Host` header is not allowed gets a 421, and one from a browser whose `Origin` is not
allowed gets a 403. By default only localhost, `127.0.0.1` and `[::1]` on any port, over http or
https, are allowed, so a web page cannot reach a local server by rebinding its own name to
`127.0.0.1`. Behind a proxy or on a public name, list the `Host` the server receives, which is the
proxy's upstream address unless the proxy passes the client's on, and the `Origin` browsers send:

```python
app = server.asgi_app(
allowed_hosts=['tools.example.com'],
allowed_origins=['https://app.example.com'],
)
```

`allowed_origins` only decides which origins get past the 403. The app sends no CORS headers, so a
page on another origin also needs them added:

```python
from starlette.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=['https://app.example.com'],
allow_methods=['GET', 'POST', 'DELETE'],
allow_headers=['content-type', 'accept', 'mcp-session-id', 'mcp-protocol-version', 'last-event-id'],
expose_headers=['mcp-session-id'],
)
```

In the default stateful mode, the MCP SDK closes a session after 30 minutes with nothing in flight
and holds at most 10,000 at once, answering 503 beyond that. It refuses a request body over 4 MiB
with a 413 in either mode. Nothing limits request rate here, so do that at a reverse proxy.

Starlette does not run a mounted app's lifespan, and the session manager inside needs one, so
mounting into an existing app means chaining it:

```python
from contextlib import asynccontextmanager

from fastapi import FastAPI

mcp_app = server.asgi_app()


@asynccontextmanager
async def lifespan(app: FastAPI):
async with mcp_app.router.lifespan_context(app):
yield


app = FastAPI(lifespan=lifespan)
app.mount('/api', mcp_app) # the endpoint is then /api/mcp
```

The app `asgi_app()` returns can start its lifespan only once, so each test that starts one needs
its own.
Starlette's `TestClient` sends `Host: testserver` unless told otherwise, which gets a 421; pass
`base_url='http://localhost'`.

### Known gaps

Scalar outputs and strings that look like JSON do not round-trip exactly. Clients join every text
Expand Down
3 changes: 2 additions & 1 deletion packages/genkit-mcp/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ dependencies = [
"anyio>=4.9.0",
"exceptiongroup>=1.2.0; python_version < '3.11'",
"genkit>=0.13.0,<2",
"mcp>=1.26.0,<2",
"mcp>=1.30.0,<2",
"pydantic>=2.10.5",
"starlette>=0.46.1",
]
description = "Model Context Protocol for Genkit. Exposes MCP servers' tools as Genkit tools and serves Genkit tools over MCP."
keywords = [
Expand Down
131 changes: 131 additions & 0 deletions packages/genkit-mcp/src/genkit_mcp/_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,22 @@

import os
import sys
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from typing import Any, TextIO

import anyio
from mcp.server.lowlevel import Server
from mcp.server.stdio import stdio_server
from mcp.server.streamable_http import EventStore
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.server.transport_security import TransportSecuritySettings
from mcp.shared.exceptions import McpError
from mcp.types import INTERNAL_ERROR, CallToolResult, ErrorData, Tool as McpTool
from pydantic import TypeAdapter
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.types import Receive, Scope, Send

from genkit import Genkit, GenkitError, Interrupt, MultipartToolResponse, PublicError, Tool, get_logger
from genkit.web import error_body, error_status
Expand All @@ -34,6 +42,12 @@

_LISTING_FAILED = 'The server could not list its tools'

LOCAL_HOSTS = ('localhost', 'localhost:*', '127.0.0.1', '127.0.0.1:*', '[::1]', '[::1]:*')
"""``Host`` values the HTTP endpoint accepts unless told otherwise."""

LOCAL_ORIGINS = tuple(f'{scheme}://{host}' for scheme in ('http', 'https') for host in LOCAL_HOSTS)
"""``Origin`` values the HTTP endpoint accepts unless told otherwise."""


class McpServer:
"""Serves a Genkit app's tools to MCP clients.
Expand Down Expand Up @@ -119,6 +133,94 @@ async def start(self) -> None:
async with stdio_server(stdin=anyio.wrap_file(stdin), stdout=anyio.wrap_file(stdout)) as streams:
await self.serve(*streams)

def _session_manager(
self,
*,
stateless: bool = False,
json_response: bool = False,
event_store: EventStore | None = None,
security: TransportSecuritySettings,
) -> StreamableHTTPSessionManager:
"""Build a new streamable HTTP session manager, since one can run only once."""
return StreamableHTTPSessionManager(
app=self._server,
event_store=event_store,
json_response=json_response,
stateless=stateless,
security_settings=security,
)

def asgi_app(
self,
path: str = '/mcp',
*,
stateless: bool = False,
json_response: bool = False,
event_store: EventStore | None = None,
allowed_hosts: Sequence[str] = LOCAL_HOSTS,
allowed_origins: Sequence[str] = LOCAL_ORIGINS,
) -> Starlette:
"""Build an ASGI app serving this server over streamable HTTP.

The app owns a manager of its own and opens it in its lifespan, so
whatever runs the app has to run that lifespan, and can run it only
once; call ``asgi_app`` again for an app to start afresh. Starlette does
not run a mounted app's lifespan, so mounting this one means chaining
its ``router.lifespan_context`` into the host app's.

The endpoint has no authentication: anyone who can reach it can call
every tool. A request whose ``Host`` is not in ``allowed_hosts`` gets a
421, and one whose ``Origin`` is not in ``allowed_origins`` gets a 403,
so a web page cannot reach a local server through DNS rebinding.

stdout is untouched here, unlike ``start``: HTTP carries no wire on it.

Args:
path: Route the endpoint answers on, within this app.
stateless: Whether each request gets a fresh transport.
json_response: Whether a response is one JSON body rather than an
SSE stream.
event_store: Where to record events for a reconnecting client.
Stateful only.
allowed_hosts: ``Host`` header values to accept. ``name:*``
accepts any port. Defaults to localhost on any port.
allowed_origins: ``Origin`` header values to accept from a
browser. ``scheme://name:*`` accepts any port. A request
with no ``Origin`` is accepted. Defaults to localhost on any
port, over http or https. The app sends no CORS headers.

Returns:
A Starlette app to serve, mount, or wrap in middleware.

Raises:
TypeError: If ``allowed_hosts`` or ``allowed_origins`` is a single
string rather than a sequence of them.
ValueError: If ``event_store`` is given with ``stateless=True``,
where there is no session to replay.
"""
for argument, value in (('allowed_hosts', allowed_hosts), ('allowed_origins', allowed_origins)):
if isinstance(value, str):
raise TypeError(f'{argument} takes a sequence of strings, not one string: [{value!r}]')
if stateless and event_store is not None:
raise ValueError('event_store needs a stateful app; a stateless one would never use it')
manager = self._session_manager(
stateless=stateless,
json_response=json_response,
event_store=event_store,
security=TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=list(allowed_hosts),
allowed_origins=list(allowed_origins),
),
)

@asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[None]:
async with manager.run():
yield

return Starlette(routes=[Route(path, endpoint=_StreamableHttpEndpoint(manager))], lifespan=lifespan)

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()]
Expand Down Expand Up @@ -309,3 +411,32 @@ def _move_stdio_off_the_wire() -> None:
finally:
os.close(null)
sys.stdout = sys.stderr


class _StreamableHttpEndpoint:
"""A streamable HTTP session manager as a plain ASGI app.

Starlette hands a callable instance every method as raw ASGI, so the
manager writes its own response to GET, POST and DELETE alike. On a
``Route`` the path itself is served, not redirected to one ending in a
slash.
"""

def __init__(self, manager: StreamableHTTPSessionManager) -> None:
"""Wrap one session manager.

Args:
manager: The manager to serve, whose ``run()`` context has to be
open before this app handles anything.
"""
self.manager = manager

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""Hand one ASGI request to the session manager.

Args:
scope: The ASGI connection scope.
receive: Where the request body arrives.
send: Where the response goes.
"""
await self.manager.handle_request(scope, receive, send)
Loading
Loading