From 2a4dd000f91935ad5c79629dabeb97455d800b3a Mon Sep 17 00:00:00 2001 From: Jacob Cable Date: Mon, 21 Sep 2026 11:20:17 +0100 Subject: [PATCH 01/10] feat(py/plugins/mcp): serve MCP over streamable HTTP as an ASGI app stdio ties a server to one client that owns the process. Streamable HTTP is how a server is reached by several clients, or by any client that did not start it, and the SDK already ships the transport. starlette is already a core dependency, so this is an ASGI app with no extra. genkit-mcp now imports starlette itself, so it declares it directly. asgi_app() is the one public addition. It returns a Starlette app that owns a session manager and opens it in its own lifespan. Each call builds a new manager, because run() can be entered once per instance and cannot be re-entered, so a shared one would make the second app fail at startup. The raw session manager and the endpoint wrapping it stay private: asgi_app() covers serving and mounting, and nothing else needs them yet. The endpoint is a Route on an exact path, not a Mount: a Mount redirects the path it is mounted on to one with a trailing slash, and the client POSTs the path it was given. The endpoint is a class rather than a function because Starlette reads a function endpoint as a request handler, which never sees the GET and DELETE the transport needs. The endpoint has no authentication, so it checks where a request comes from. The SDK's transport turns DNS rebinding protection off unless it is given settings, and the MCP spec says a server must validate Origin. Without the check, a web page that rebinds its own name to 127.0.0.1 reaches a local server and can call every tool. asgi_app() always turns the check on: Host must be in allowed_hosts (else 421) and a browser's Origin in allowed_origins (else 403). Both default to localhost, 127.0.0.1 and [::1] on any port, which is what the SDK's FastMCP allows when bound to localhost; bare names are allowed too, since a client on port 80 sends no port. A deployment on a public name lists its own. There is no switch to turn the check off. The README says to bind to localhost or put authentication in front, and that sessions and request bodies are not limited here. Mounting the app into an existing one needs its lifespan chained into the host's, because Starlette runs no mounted app's lifespan and the manager's task group is created there. The README says so and a test pins it. An app whose lifespan never ran fails each request with the SDK's "Task group is not initialized" rather than hanging, and a test pins that as well. start() moves this process's stdout because stdout is the stdio wire. Nothing on this path does, and a test pins that too. The tests drive the app through an httpx ASGI transport, so a real client session runs against it with no port bound and nothing polled. They cover the host and origin checks, the redirect from a trailing slash, and a DELETE ending a session. Under a real uvicorn, a request with a hostile Host got 421 and one with a hostile Origin got 403. Upstream-Commit: genkit-ai/genkit@591621485 Upstream-PR: https://github.com/genkit-ai/genkit/pull/6883 --- packages/genkit-mcp/README.md | 57 +++- packages/genkit-mcp/pyproject.toml | 1 + packages/genkit-mcp/src/genkit_mcp/_server.py | 125 ++++++++ packages/genkit-mcp/tests/mcp_http_test.py | 302 ++++++++++++++++++ uv.lock | 2 + 5 files changed, 486 insertions(+), 1 deletion(-) create mode 100644 packages/genkit-mcp/tests/mcp_http_test.py diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 43ea33bcf..c55dc49e4 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -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: (client), (server) @@ -232,6 +232,61 @@ 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 `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 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 what clients will send: + +```python +app = server.asgi_app( + allowed_hosts=['tools.example.com'], + allowed_origins=['https://app.example.com'], +) +``` + +In the default stateful mode, each session stays open until its client sends `DELETE` or the process +ends, and the MCP SDK reads a whole request body before it parses it. Neither has a limit here. +`stateless=True` keeps no sessions. Limit body size and request rate 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 +``` + ### Known gaps Scalar outputs and strings that look like JSON do not round-trip exactly. Clients join every text diff --git a/packages/genkit-mcp/pyproject.toml b/packages/genkit-mcp/pyproject.toml index 17437e89d..f0081eb2b 100644 --- a/packages/genkit-mcp/pyproject.toml +++ b/packages/genkit-mcp/pyproject.toml @@ -44,6 +44,7 @@ dependencies = [ "genkit>=0.13.0,<2", "mcp>=1.26.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 = [ diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index c0242d119..a253923d8 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -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 @@ -34,6 +42,19 @@ _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 = ( + 'http://localhost', + 'http://localhost:*', + 'http://127.0.0.1', + 'http://127.0.0.1:*', + 'http://[::1]', + 'http://[::1]:*', +) +"""``Origin`` values the HTTP endpoint accepts unless told otherwise.""" + class McpServer: """Serves a Genkit app's tools to MCP clients. @@ -119,6 +140,81 @@ 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. 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. + 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. + + Returns: + A Starlette app to serve, mount, or wrap in middleware. + """ + 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()] @@ -309,3 +405,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. + + A class rather than a function because Starlette reads a function endpoint + as a request handler, which never sees the GET and DELETE streamable HTTP + needs. It sits on a ``Route``, since a ``Mount`` redirects its own path to + one with a trailing slash that no client asks for. + """ + + 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) diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py new file mode 100644 index 000000000..2ad5f03db --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -0,0 +1,302 @@ +# 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 over streamable HTTP.""" + +import sys +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import httpx +import pytest +from genkit_mcp import create_mcp_server +from mcp import ClientSession +from mcp.client.streamable_http import streamable_http_client +from mcp.types import TextContent +from pydantic import BaseModel +from starlette.applications import Starlette +from starlette.routing import Mount +from starlette.types import ASGIApp + +from genkit import Genkit + +BASE_URL = 'http://localhost:8000' + +INITIALIZE = { + 'jsonrpc': '2.0', + 'id': 1, + 'method': 'initialize', + 'params': { + 'protocolVersion': '2025-06-18', + 'capabilities': {}, + 'clientInfo': {'name': 'test', 'version': '1.0.0'}, + }, +} + + +class Greeting(BaseModel): + name: str + + +def app_with_tools() -> Genkit: + ai = Genkit() + + @ai.tool() + async def greet(greeting: Greeting) -> str: + """Greet.""" + return f'hello {greeting.name}' + + @ai.tool() + async def ping() -> str: + """Answer.""" + return 'pong' + + return ai + + +def http_client(app: ASGIApp) -> httpx.AsyncClient: + """Speak to an ASGI app directly, so no port is bound and nothing is polled.""" + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url=BASE_URL) + + +async def initialize(app: Starlette, **headers: str) -> httpx.Response: + """POST one initialize request with extra headers, running the app's lifespan around it.""" + async with app.router.lifespan_context(app): + async with http_client(app) as http: + return await http.post( + '/mcp', + headers={'accept': 'application/json, text/event-stream', **headers}, + json=INITIALIZE, + ) + + +@asynccontextmanager +async def session_over(app: Starlette, url: str = f'{BASE_URL}/mcp') -> AsyncIterator[ClientSession]: + """Open an MCP session against an ASGI app, running its lifespan around it.""" + async with app.router.lifespan_context(app): + async with http_client(app) as http: + async with streamable_http_client(url, http_client=http) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + yield session + + +@pytest.mark.asyncio +async def test_a_stateful_app_lists_and_calls_the_apps_tools() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + + async with session_over(server.asgi_app()) as session: + listed = await session.list_tools() + result = await session.call_tool('greet', {'name': 'ada'}) + + assert sorted(tool.name for tool in listed.tools) == ['greet', 'ping'] + assert result.content == [TextContent(type='text', text='hello ada')] + + +@pytest.mark.asyncio +async def test_a_stateless_app_lists_and_calls_the_apps_tools() -> None: + """Every request gets its own transport, so nothing is carried between them.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + + async with session_over(server.asgi_app(stateless=True)) as session: + listed = await session.list_tools() + result = await session.call_tool('ping', {}) + + assert sorted(tool.name for tool in listed.tools) == ['greet', 'ping'] + assert result.content == [TextContent(type='text', text='pong')] + + +@pytest.mark.asyncio +async def test_a_stateful_app_hands_out_a_session_id_and_a_stateless_one_does_not() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + stateful = server.asgi_app() + stateless = server.asgi_app(stateless=True) + + ids = [] + for app in (stateful, stateless): + async with app.router.lifespan_context(app): + async with http_client(app) as http: + async with streamable_http_client(f'{BASE_URL}/mcp', http_client=http) as ( + read, + write, + get_session_id, + ): + async with ClientSession(read, write) as session: + await session.initialize() + ids.append(get_session_id()) + + assert ids[0] is not None + assert ids[1] is None + + +@pytest.mark.asyncio +async def test_a_json_response_app_answers_without_an_event_stream() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + app = server.asgi_app(json_response=True) + + response = await initialize(app) + + assert response.headers['content-type'].startswith('application/json') + assert response.json()['result']['serverInfo']['name'] == 'bookshop' + + +@pytest.mark.asyncio +async def test_the_path_is_configurable() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + + async with session_over(server.asgi_app('/tools'), f'{BASE_URL}/tools') as session: + listed = await session.list_tools() + + assert [tool.name for tool in listed.tools] == ['greet', 'ping'] + + +@pytest.mark.asyncio +async def test_the_app_mounts_into_a_host_app_that_chains_its_lifespan() -> None: + """Starlette runs no mounted app's lifespan, so the host has to chain it.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + mcp_app = server.asgi_app('/mcp') + + @asynccontextmanager + async def lifespan(app: Starlette) -> AsyncIterator[None]: + async with mcp_app.router.lifespan_context(app): + yield + + host = Starlette(routes=[Mount('/api', app=mcp_app)], lifespan=lifespan) + + async with session_over(host, f'{BASE_URL}/api/mcp') as session: + listed = await session.list_tools() + + assert [tool.name for tool in listed.tools] == ['greet', 'ping'] + + +@pytest.mark.asyncio +async def test_each_app_from_one_server_runs_its_own_lifespan() -> None: + """A session manager runs once, so every asgi_app call owns a fresh one and both serve.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + + for app in (server.asgi_app(), server.asgi_app()): + async with session_over(app) as session: + listed = await session.list_tools() + assert [tool.name for tool in listed.tools] == ['greet', 'ping'] + + +@pytest.mark.asyncio +async def test_serving_over_http_leaves_stdout_alone() -> None: + """Only stdio makes stdout the wire, so only start() moves this process's.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + before = sys.stdout + + async with session_over(server.asgi_app()) as session: + await session.list_tools() + + assert sys.stdout is before + + +@pytest.mark.asyncio +@pytest.mark.parametrize('host', ['localhost', 'localhost:3000', '127.0.0.1:8000', '[::1]:8000']) +async def test_a_local_host_is_served_on_any_port(host: str) -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + + response = await initialize(server.asgi_app(json_response=True), host=host) + + assert response.status_code == 200 + + +@pytest.mark.asyncio +async def test_a_host_outside_the_allowed_list_is_refused() -> None: + """A page that rebinds its own name to 127.0.0.1 still sends that name as Host.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + + response = await initialize(server.asgi_app(json_response=True), host='evil.example:8000') + + assert response.status_code == 421 + assert 'mcp-session-id' not in response.headers + + +@pytest.mark.asyncio +async def test_an_origin_outside_the_allowed_list_is_refused() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + + response = await initialize(server.asgi_app(json_response=True), origin='http://evil.example') + + assert response.status_code == 403 + assert 'mcp-session-id' not in response.headers + + +@pytest.mark.asyncio +async def test_a_local_origin_is_served() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + + response = await initialize(server.asgi_app(json_response=True), origin='http://localhost:5173') + + assert response.status_code == 200 + + +@pytest.mark.asyncio +async def test_allowed_hosts_and_origins_replace_the_local_defaults() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + + def app() -> Starlette: + return server.asgi_app( + json_response=True, + allowed_hosts=['tools.example.com'], + allowed_origins=['https://app.example.com'], + ) + + served = await initialize(app(), host='tools.example.com', origin='https://app.example.com') + local = await initialize(app(), host='localhost:8000') + + assert served.status_code == 200 + assert local.status_code == 421 + + +@pytest.mark.asyncio +async def test_a_trailing_slash_redirects_to_the_endpoint() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + app = server.asgi_app() + + async with app.router.lifespan_context(app): + async with http_client(app) as http: + response = await http.post('/mcp/', json=INITIALIZE) + + assert response.status_code == 307 + assert response.headers['location'] == f'{BASE_URL}/mcp' + + +@pytest.mark.asyncio +async def test_delete_ends_a_stateful_session() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + app = server.asgi_app(json_response=True) + accept = {'accept': 'application/json, text/event-stream'} + + async with app.router.lifespan_context(app): + async with http_client(app) as http: + opened = await http.post('/mcp', headers=accept, json=INITIALIZE) + session = {'mcp-session-id': opened.headers['mcp-session-id']} + deleted = await http.delete('/mcp', headers={**accept, **session}) + after = await http.post( + '/mcp', + headers={**accept, **session}, + json={'jsonrpc': '2.0', 'id': 2, 'method': 'tools/list'}, + ) + + assert deleted.status_code == 200 + assert after.status_code == 404 + + +@pytest.mark.asyncio +async def test_an_app_whose_lifespan_never_ran_fails_every_request() -> None: + """Mounting without chaining the lifespan fails loudly rather than hanging.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + app = server.asgi_app(json_response=True) + + async with http_client(app) as http: + with pytest.raises(RuntimeError, match='Task group is not initialized'): + await http.post('/mcp', headers={'accept': 'application/json, text/event-stream'}, json=INITIALIZE) diff --git a/uv.lock b/uv.lock index 81049fd0d..9015b5e5d 100644 --- a/uv.lock +++ b/uv.lock @@ -1842,6 +1842,7 @@ dependencies = [ { name = "genkit" }, { name = "mcp" }, { name = "pydantic" }, + { name = "starlette" }, ] [package.metadata] @@ -1851,6 +1852,7 @@ requires-dist = [ { name = "genkit", editable = "packages/genkit" }, { name = "mcp", specifier = ">=1.26.0,<2" }, { name = "pydantic", specifier = ">=2.10.5" }, + { name = "starlette", specifier = ">=0.46.1" }, ] [[package]] From f3ddcc72d3a8bfeb9fc17f8f22962ff5f892b3ad Mon Sep 17 00:00:00 2001 From: Jacob Cable Date: Fri, 23 Oct 2026 17:51:09 +0100 Subject: [PATCH 02/10] fix(py/plugins/mcp): refuse a single string as an asgi_app allow-list A str is a Sequence[str] of its characters, so allowed_hosts='example.com' type-checks and then refuses every request with 421, because no Host is one character long. asgi_app() raises TypeError for a str in either allow-list, rather than wrapping it, so the call reads the same way it is typed. Upstream-Commit: genkit-ai/genkit@f3b351bbb Upstream-PR: https://github.com/genkit-ai/genkit/pull/6883 --- packages/genkit-mcp/src/genkit_mcp/_server.py | 7 +++++++ packages/genkit-mcp/tests/mcp_http_test.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index a253923d8..59158b5b0 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -196,7 +196,14 @@ def asgi_app( 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. """ + 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}]') manager = self._session_manager( stateless=stateless, json_response=json_response, diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py index 2ad5f03db..2b684629b 100644 --- a/packages/genkit-mcp/tests/mcp_http_test.py +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -257,6 +257,21 @@ def app() -> Starlette: assert local.status_code == 421 +def test_a_single_string_for_allowed_hosts_is_refused() -> None: + """A str is a Sequence[str] of its characters, which would refuse every request.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + + with pytest.raises(TypeError, match='allowed_hosts'): + server.asgi_app(allowed_hosts='tools.example.com') + + +def test_a_single_string_for_allowed_origins_is_refused() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + + with pytest.raises(TypeError, match='allowed_origins'): + server.asgi_app(allowed_origins='https://app.example.com') + + @pytest.mark.asyncio async def test_a_trailing_slash_redirects_to_the_endpoint() -> None: server = create_mcp_server(app_with_tools(), 'bookshop') From 70ec04cebc76d85afbf2937067ef8ec4783d276b Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:22:34 +0100 Subject: [PATCH 03/10] fix(py/plugins/mcp): require an mcp that drops refused HTTP sessions mcp 1.26 opened a session for every request without a session id, refused or not, and never closed it. --- packages/genkit-mcp/README.md | 6 +++--- packages/genkit-mcp/pyproject.toml | 2 +- packages/genkit-mcp/tests/mcp_http_test.py | 19 +++++++++++++++++++ uv.lock | 8 ++++---- 4 files changed, 27 insertions(+), 8 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index c55dc49e4..d82853fa7 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -262,9 +262,9 @@ app = server.asgi_app( ) ``` -In the default stateful mode, each session stays open until its client sends `DELETE` or the process -ends, and the MCP SDK reads a whole request body before it parses it. Neither has a limit here. -`stateless=True` keeps no sessions. Limit body size and request rate at a reverse proxy. +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: diff --git a/packages/genkit-mcp/pyproject.toml b/packages/genkit-mcp/pyproject.toml index f0081eb2b..a9015f8dd 100644 --- a/packages/genkit-mcp/pyproject.toml +++ b/packages/genkit-mcp/pyproject.toml @@ -42,7 +42,7 @@ 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", ] diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py index 2b684629b..0705f6174 100644 --- a/packages/genkit-mcp/tests/mcp_http_test.py +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -230,6 +230,25 @@ async def test_an_origin_outside_the_allowed_list_is_refused() -> None: assert 'mcp-session-id' not in response.headers +@pytest.mark.asyncio +async def test_a_refused_request_leaves_no_session_behind() -> None: + """A page that cannot call tools must not be able to pile up sessions either.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + app = server.asgi_app(json_response=True) + accept = {'accept': 'application/json, text/event-stream'} + + async with app.router.lifespan_context(app): + async with http_client(app) as http: + statuses = [ + (await http.post('/mcp', headers={**accept, 'host': 'evil.example'}, json=INITIALIZE)).status_code, + (await http.post('/mcp', headers={**accept, 'origin': 'http://evil.example'}, json=INITIALIZE)).status_code, + ] + sessions = dict(app.routes[0].endpoint.manager._server_instances) + + assert statuses == [421, 403] + assert sessions == {} + + @pytest.mark.asyncio async def test_a_local_origin_is_served() -> None: server = create_mcp_server(app_with_tools(), 'bookshop') diff --git a/uv.lock b/uv.lock index 9015b5e5d..c5f833a05 100644 --- a/uv.lock +++ b/uv.lock @@ -1850,7 +1850,7 @@ requires-dist = [ { name = "anyio", specifier = ">=4.9.0" }, { name = "exceptiongroup", marker = "python_full_version < '3.11'", specifier = ">=1.2.0" }, { name = "genkit", editable = "packages/genkit" }, - { name = "mcp", specifier = ">=1.26.0,<2" }, + { name = "mcp", specifier = ">=1.30.0,<2" }, { name = "pydantic", specifier = ">=2.10.5" }, { name = "starlette", specifier = ">=0.46.1" }, ] @@ -3672,7 +3672,7 @@ wheels = [ [[package]] name = "mcp" -version = "1.26.0" +version = "1.30.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, @@ -3690,9 +3690,9 @@ dependencies = [ { name = "typing-inspection" }, { name = "uvicorn", marker = "sys_platform != 'emscripten'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fc/6d/62e76bbb8144d6ed86e202b5edd8a4cb631e7c8130f3f4893c3f90262b10/mcp-1.26.0.tar.gz", hash = "sha256:db6e2ef491eecc1a0d93711a76f28dec2e05999f93afd48795da1c1137142c66", size = 608005, upload-time = "2026-01-24T19:40:32.468Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/93/0142dc84a666daf8ad51a34268f34c12fd6fda4f3810c4be2504eecc8212/mcp-1.30.0.tar.gz", hash = "sha256:445414625fce5c295faa505bb11bacece661ab6f4028d57c935db57820b7a3e4", size = 680511, upload-time = "2026-09-07T14:34:15.845Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fd/d9/eaa1f80170d2b7c5ba23f3b59f766f3a0bb41155fbc32a69adfa1adaaef9/mcp-1.26.0-py3-none-any.whl", hash = "sha256:904a21c33c25aa98ddbeb47273033c435e595bbacfdb177f4bd87f6dceebe1ca", size = 233615, upload-time = "2026-01-24T19:40:30.652Z" }, + { url = "https://files.pythonhosted.org/packages/f5/f4/e58bc33317c92a0203664daaf00bf6f41166cc0149e5d6870a03f7cd004a/mcp-1.30.0-py3-none-any.whl", hash = "sha256:666edb5009503e1047c9d60346a756f94b261f05cc2625f23d41c728ffc484d0", size = 234581, upload-time = "2026-09-07T14:34:14.266Z" }, ] [[package]] From 1bdd7fed6eb23f442247bf114ba47df59d8e2146 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:23:13 +0100 Subject: [PATCH 04/10] fix(py/plugins/mcp): accept https localhost origins by default --- packages/genkit-mcp/README.md | 5 +++-- packages/genkit-mcp/src/genkit_mcp/_server.py | 9 +-------- packages/genkit-mcp/tests/mcp_http_test.py | 7 +++++-- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index d82853fa7..c18c653d7 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -251,8 +251,9 @@ it before you bind it to a public interface. Mounting it in an app that already 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 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 +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 what clients will send: ```python diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index 59158b5b0..a82b3482d 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -45,14 +45,7 @@ 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 = ( - 'http://localhost', - 'http://localhost:*', - 'http://127.0.0.1', - 'http://127.0.0.1:*', - 'http://[::1]', - 'http://[::1]:*', -) +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.""" diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py index 0705f6174..69024564c 100644 --- a/packages/genkit-mcp/tests/mcp_http_test.py +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -250,10 +250,13 @@ async def test_a_refused_request_leaves_no_session_behind() -> None: @pytest.mark.asyncio -async def test_a_local_origin_is_served() -> None: +@pytest.mark.parametrize( + 'origin', ['http://localhost', 'http://localhost:5173', 'https://localhost:3000', 'https://127.0.0.1'] +) +async def test_a_local_origin_is_served(origin: str) -> None: server = create_mcp_server(app_with_tools(), 'bookshop') - response = await initialize(server.asgi_app(json_response=True), origin='http://localhost:5173') + response = await initialize(server.asgi_app(json_response=True), origin=origin) assert response.status_code == 200 From cf37b9a997f462a5b0c83b8aaf6af0bfefd84144 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:23:47 +0100 Subject: [PATCH 05/10] fix(py/plugins/mcp): refuse an event store on a stateless asgi_app The SDK drops the store in stateless mode without a word. --- packages/genkit-mcp/README.md | 4 +-- packages/genkit-mcp/src/genkit_mcp/_server.py | 5 +++ packages/genkit-mcp/tests/mcp_http_test.py | 34 ++++++++++++++++++- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index c18c653d7..89a2ffa22 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -242,8 +242,8 @@ 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 `event_store=` to let a reconnecting client replay what -it missed. Nothing here touches stdout: only stdio makes stdout the wire. +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 diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index a82b3482d..7430ec608 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -180,6 +180,7 @@ def asgi_app( 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 @@ -193,10 +194,14 @@ def asgi_app( 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, diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py index 69024564c..0ba02dc12 100644 --- a/packages/genkit-mcp/tests/mcp_http_test.py +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -19,7 +19,8 @@ from genkit_mcp import create_mcp_server from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client -from mcp.types import TextContent +from mcp.server.streamable_http import EventCallback, EventId, EventStore, StreamId +from mcp.types import JSONRPCMessage, TextContent from pydantic import BaseModel from starlette.applications import Starlette from starlette.routing import Mount @@ -294,6 +295,37 @@ def test_a_single_string_for_allowed_origins_is_refused() -> None: server.asgi_app(allowed_origins='https://app.example.com') +class RecordingEventStore(EventStore): + def __init__(self) -> None: + self.stored: list[StreamId] = [] + + async def store_event(self, stream_id: StreamId, message: JSONRPCMessage | None) -> EventId: + self.stored.append(stream_id) + return str(len(self.stored)) + + async def replay_events_after(self, last_event_id: EventId, send_callback: EventCallback) -> StreamId | None: + return None + + +@pytest.mark.asyncio +async def test_a_stateful_app_records_events_in_the_given_store() -> None: + server = create_mcp_server(app_with_tools(), 'bookshop') + store = RecordingEventStore() + + async with session_over(server.asgi_app(event_store=store)) as session: + await session.call_tool('ping', {}) + + assert store.stored + + +def test_an_event_store_on_a_stateless_app_is_refused() -> None: + """A stateless app has no session to replay, so the store would never be used.""" + server = create_mcp_server(app_with_tools(), 'bookshop') + + with pytest.raises(ValueError, match='event_store'): + server.asgi_app(stateless=True, event_store=RecordingEventStore()) + + @pytest.mark.asyncio async def test_a_trailing_slash_redirects_to_the_endpoint() -> None: server = create_mcp_server(app_with_tools(), 'bookshop') From f130abf45a88e71185b8780eab4b2178596a037d Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:23:59 +0100 Subject: [PATCH 06/10] test(py/plugins/mcp): check allowed_origins replaces the local origins --- packages/genkit-mcp/tests/mcp_http_test.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py index 0ba02dc12..c0bfdc9a5 100644 --- a/packages/genkit-mcp/tests/mcp_http_test.py +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -274,10 +274,12 @@ def app() -> Starlette: ) served = await initialize(app(), host='tools.example.com', origin='https://app.example.com') - local = await initialize(app(), host='localhost:8000') + local_host = await initialize(app(), host='localhost:8000') + local_origin = await initialize(app(), host='tools.example.com', origin='http://localhost:5173') assert served.status_code == 200 - assert local.status_code == 421 + assert local_host.status_code == 421 + assert local_origin.status_code == 403 def test_a_single_string_for_allowed_hosts_is_refused() -> None: From fd9f1dd282ab732b05f4ee701b9a09d1a9e45cb2 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:24:30 +0100 Subject: [PATCH 07/10] docs(py/plugins/mcp): say an asgi_app starts once and how to test one --- packages/genkit-mcp/README.md | 4 ++++ packages/genkit-mcp/src/genkit_mcp/_server.py | 16 ++++++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 89a2ffa22..0d7854567 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -288,6 +288,10 @@ app = FastAPI(lifespan=lifespan) app.mount('/api', mcp_app) # the endpoint is then /api/mcp ``` +An app's lifespan runs only once, so each test that starts one needs its own `server.asgi_app()`. +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 diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index 7430ec608..f77c49c26 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -163,9 +163,10 @@ def asgi_app( """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. Starlette does not run a - mounted app's lifespan, so mounting this one means chaining its - ``router.lifespan_context`` into the host app's. + 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 @@ -186,7 +187,7 @@ def asgi_app( 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. + port, over http or https. Returns: A Starlette app to serve, mount, or wrap in middleware. @@ -415,10 +416,9 @@ def _move_stdio_off_the_wire() -> None: class _StreamableHttpEndpoint: """A streamable HTTP session manager as a plain ASGI app. - A class rather than a function because Starlette reads a function endpoint - as a request handler, which never sees the GET and DELETE streamable HTTP - needs. It sits on a ``Route``, since a ``Mount`` redirects its own path to - one with a trailing slash that no client asks for. + 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 exact path is served with no trailing-slash redirect. """ def __init__(self, manager: StreamableHTTPSessionManager) -> None: From b65e0ce726d37b6f46341929eef7331b6ae76633 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:32:15 +0100 Subject: [PATCH 08/10] test(py/plugins/mcp): type and wrap the refused-session test --- packages/genkit-mcp/tests/mcp_http_test.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py index c0bfdc9a5..2cc20aaf6 100644 --- a/packages/genkit-mcp/tests/mcp_http_test.py +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -17,13 +17,14 @@ import httpx import pytest from genkit_mcp import create_mcp_server +from genkit_mcp._server import _StreamableHttpEndpoint from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client from mcp.server.streamable_http import EventCallback, EventId, EventStore, StreamId from mcp.types import JSONRPCMessage, TextContent from pydantic import BaseModel from starlette.applications import Starlette -from starlette.routing import Mount +from starlette.routing import Mount, Route from starlette.types import ASGIApp from genkit import Genkit @@ -236,15 +237,17 @@ async def test_a_refused_request_leaves_no_session_behind() -> None: """A page that cannot call tools must not be able to pile up sessions either.""" server = create_mcp_server(app_with_tools(), 'bookshop') app = server.asgi_app(json_response=True) + route = app.routes[0] + assert isinstance(route, Route) and isinstance(route.endpoint, _StreamableHttpEndpoint) accept = {'accept': 'application/json, text/event-stream'} async with app.router.lifespan_context(app): async with http_client(app) as http: statuses = [ - (await http.post('/mcp', headers={**accept, 'host': 'evil.example'}, json=INITIALIZE)).status_code, - (await http.post('/mcp', headers={**accept, 'origin': 'http://evil.example'}, json=INITIALIZE)).status_code, + (await http.post('/mcp', headers={**accept, **refused}, json=INITIALIZE)).status_code + for refused in ({'host': 'evil.example'}, {'origin': 'http://evil.example'}) ] - sessions = dict(app.routes[0].endpoint.manager._server_instances) + sessions = dict(route.endpoint.manager._server_instances) assert statuses == [421, 403] assert sessions == {} From 6ef076e67c1463a80da9db8fe936c398012e4db3 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:44:32 +0100 Subject: [PATCH 09/10] test(py/plugins/mcp): tighten the session, origin and event store checks --- packages/genkit-mcp/tests/mcp_http_test.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/genkit-mcp/tests/mcp_http_test.py b/packages/genkit-mcp/tests/mcp_http_test.py index 2cc20aaf6..c1a49db84 100644 --- a/packages/genkit-mcp/tests/mcp_http_test.py +++ b/packages/genkit-mcp/tests/mcp_http_test.py @@ -244,18 +244,19 @@ async def test_a_refused_request_leaves_no_session_behind() -> None: async with app.router.lifespan_context(app): async with http_client(app) as http: statuses = [ - (await http.post('/mcp', headers={**accept, **refused}, json=INITIALIZE)).status_code - for refused in ({'host': 'evil.example'}, {'origin': 'http://evil.example'}) + (await http.post('/mcp', headers={**accept, **headers}, json=INITIALIZE)).status_code + for headers in ({}, {'host': 'evil.example'}, {'origin': 'http://evil.example'}) ] - sessions = dict(route.endpoint.manager._server_instances) + sessions = len(route.endpoint.manager._server_instances) - assert statuses == [421, 403] - assert sessions == {} + assert statuses == [200, 421, 403] + assert sessions == 1 @pytest.mark.asyncio @pytest.mark.parametrize( - 'origin', ['http://localhost', 'http://localhost:5173', 'https://localhost:3000', 'https://127.0.0.1'] + 'origin', + ['http://localhost', 'http://localhost:5173', 'https://localhost:3000', 'https://127.0.0.1', 'https://[::1]:8443'], ) async def test_a_local_origin_is_served(origin: str) -> None: server = create_mcp_server(app_with_tools(), 'bookshop') @@ -302,10 +303,11 @@ def test_a_single_string_for_allowed_origins_is_refused() -> None: class RecordingEventStore(EventStore): def __init__(self) -> None: - self.stored: list[StreamId] = [] + self.stored: list[str] = [] async def store_event(self, stream_id: StreamId, message: JSONRPCMessage | None) -> EventId: - self.stored.append(stream_id) + if message is not None: + self.stored.append(message.model_dump_json(exclude_none=True)) return str(len(self.stored)) async def replay_events_after(self, last_event_id: EventId, send_callback: EventCallback) -> StreamId | None: @@ -320,7 +322,7 @@ async def test_a_stateful_app_records_events_in_the_given_store() -> None: async with session_over(server.asgi_app(event_store=store)) as session: await session.call_tool('ping', {}) - assert store.stored + assert any('"text":"pong"' in message for message in store.stored) def test_an_event_store_on_a_stateless_app_is_refused() -> None: From e859fc30beed06dc0e092e221ba7009aa7b60479 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:46:33 +0100 Subject: [PATCH 10/10] docs(py/plugins/mcp): cover CORS and proxied Host for asgi_app --- packages/genkit-mcp/README.md | 22 ++++++++++++++++--- packages/genkit-mcp/src/genkit_mcp/_server.py | 5 +++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 0d7854567..a23e83654 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -253,8 +253,8 @@ 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 what clients will send: +`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( @@ -263,6 +263,21 @@ app = server.asgi_app( ) ``` +`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. @@ -288,7 +303,8 @@ app = FastAPI(lifespan=lifespan) app.mount('/api', mcp_app) # the endpoint is then /api/mcp ``` -An app's lifespan runs only once, so each test that starts one needs its own `server.asgi_app()`. +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'`. diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index f77c49c26..400c6dcf2 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -187,7 +187,7 @@ def asgi_app( 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. + port, over http or https. The app sends no CORS headers. Returns: A Starlette app to serve, mount, or wrap in middleware. @@ -418,7 +418,8 @@ class _StreamableHttpEndpoint: 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 exact path is served with no trailing-slash redirect. + ``Route`` the path itself is served, not redirected to one ending in a + slash. """ def __init__(self, manager: StreamableHTTPSessionManager) -> None: