chore: import upstream snapshot with attribution
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run

This commit is contained in:
wehub-resource-sync
2026-07-13 12:10:27 +08:00
commit 49b9bb6724
992 changed files with 161690 additions and 0 deletions
@@ -0,0 +1,58 @@
# starlette-mount
Embed an MCP server inside an existing Starlette (or FastAPI) app at a
sub-path, next to your own routes. `mcp.streamable_http_app()` returns a
mountable ASGI app; the two things to get right are the **path** (the default
`streamable_http_path="/mcp"` stacks under your mount prefix) and the
**lifespan** (Starlette does not run a mounted sub-app's lifespan, so the
parent must enter `mcp.session_manager.run()`).
## Run it
```bash
# HTTP — the client self-hosts the mounted app on a free port at /api/, runs,
# then tears it down
uv run python -m stories.starlette_mount.client --http
# against a server you run yourself (real uvicorn on :8000)
uv run python -m stories.starlette_mount.server --port 8000 &
SERVER_PID=$!
curl http://127.0.0.1:8000/health # → {"status":"ok"}
uv run python -m stories.starlette_mount.client --http http://127.0.0.1:8000/api/
kill "$SERVER_PID"
```
## What to look at
- `client.py` `main` — opens with `async with Client(target, mode=mode) as
client:`. Nothing on the client side knows about the mount: the `/api/` URL
handed in as `target` is just another streamable-HTTP endpoint.
- `server.py` `streamable_http_path="/"` — without this the endpoint would be
`/api/mcp`; with it, `Mount("/api", ...)` serves MCP at `/api/` (trailing
slash required — Starlette's `Mount` forwards `/api` as an empty path that
the inner `/` route won't match).
- `server.py` `lifespan` — `mcp.session_manager.run()` **must** be entered by
the parent app. Forget it and every MCP request fails immediately with a 500
(`RuntimeError: Task group is not initialized. Make sure to use run().`) —
the sub-app's own lifespan never fires under `Mount`.
- `server.py` `Route("/health", ...)` — non-MCP routes live alongside the
mount; FastAPI users do the same with `app.mount("/api", mcp_app)`.
## Caveats
- DNS-rebinding protection is on by default; the example passes
`transport_security=NO_DNS_REBIND` because the in-process test client sends
no `Origin` header. Remove it (or configure allowed hosts) for a real
deployment.
- The parent-lifespan dance is a known SDK ergonomics gap (other SDKs mount
with no extra ceremony); tracked for the beta reshape. The recipe shown here
is what works today.
## Spec
[Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#streamable-http)
## See also
`stateless_legacy/` (the one-liner `mcp.streamable_http_app()` without a parent
app), `json_response/`, `legacy_routing/`. TS-SDK equivalent: `examples/hono/`.
@@ -0,0 +1,23 @@
"""Connect to the sub-mounted MCP endpoint at /api/, list tools and call greet. HTTP-only: the mount is the story."""
from mcp_types import TextContent
from mcp.client import Client
from stories._harness import Target, run_client
async def main(target: Target, *, mode: str = "auto") -> None:
async with Client(target, mode=mode) as client:
listed = await client.list_tools()
assert [t.name for t in listed.tools] == ["greet"]
result = await client.call_tool("greet", {"name": "Starlette"})
assert not result.is_error
first = result.content[0]
assert isinstance(first, TextContent)
assert "Hello, Starlette!" in first.text, result
assert result.structured_content == {"result": "Hello, Starlette! (served from a Starlette sub-mount)"}
if __name__ == "__main__":
run_client(main)
@@ -0,0 +1,47 @@
"""Mount an MCPServer in an existing Starlette app at a sub-path, alongside non-MCP routes; exports `build_app()`."""
import contextlib
from collections.abc import AsyncIterator
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route
from mcp.server.mcpserver import MCPServer
from stories._hosting import NO_DNS_REBIND, run_app_from_args
def build_app() -> Starlette:
mcp = MCPServer("starlette-mount-example")
@mcp.tool()
def greet(name: str) -> str:
"""Return a greeting."""
return f"Hello, {name}! (served from a Starlette sub-mount)"
# streamable_http_path="/" so Mount("/api", ...) serves the MCP endpoint at
# /api itself, not /api/mcp. The returned sub-app has its own lifespan, but
# Starlette does not run nested lifespans under Mount — the parent app below
# must enter mcp.session_manager.run() itself.
mcp_app = mcp.streamable_http_app(streamable_http_path="/", transport_security=NO_DNS_REBIND)
async def health(_request: Request) -> JSONResponse:
return JSONResponse({"status": "ok"})
@contextlib.asynccontextmanager
async def lifespan(_app: Starlette) -> AsyncIterator[None]:
async with mcp.session_manager.run():
yield
return Starlette(
routes=[
Route("/health", health),
Mount("/api", app=mcp_app),
],
lifespan=lifespan,
)
if __name__ == "__main__":
run_app_from_args(build_app)