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
+56
View File
@@ -0,0 +1,56 @@
# middleware
Register a single `async (ctx, call_next) -> result` function on
`Server.middleware` to observe or alter every request and notification the
server receives, across both protocol eras and any transport. Middleware sits
*outside* method lookup and params validation, so it sees `initialize`,
`server/discover`, `notifications/*`, and unknown methods too. The chain runs
outermost-first.
## Run it
```bash
# stdio (default — the client spawns the server as a subprocess)
uv run python -m stories.middleware.client
# HTTP — the client self-hosts the server on a free port, runs, then tears it down
uv run python -m stories.middleware.client --http
```
## What to look at
- `client.py` `main` — opens with `async with Client(target, mode=mode)`. The
story owns that construction; the harness only picks the target and era.
Middleware is invisible from this side — only the `audit_log` result proves
the wrap happened.
- `server.py``server.middleware.append(record_calls)` is the public
registration point on `mcp.server.lowlevel.Server`.
- `client.py` — the asserted log ends at `"tools/call"` without a `:done`
suffix: `audit_log` runs *inside* `call_next(ctx)`, so the `finally` hasn't
fired yet. That's the wrap.
## Caveats
- **Lowlevel-only.** `Server.middleware` on `mcp.server.lowlevel.Server` is the
one public hook; `MCPServer` has no public accessor for it yet (a
`MCPServer.middleware` accessor is planned before beta).
- The middleware signature is **provisional** (see the TODO in
`src/mcp/server/lowlevel/server.py`): it tightens to a covariant `Context[L]`
and gains an outbound seam before v2 final.
- `ServerMiddleware` / `CallNext` / `HandlerResult` are imported from
`mcp.server.context` (helper tier); not re-exported at `mcp.server.lowlevel`.
- Do **not** `await ctx.session.send_request(...)` while wrapping `initialize`
`initialize` is dispatched inline and the outbound channel isn't open yet.
- To rewrite `ctx.method` / `ctx.params` before the handler runs, pass an
adjusted context through: `await call_next(dataclasses.replace(ctx, ...))`.
`docs/migration.md` shows the full recipe.
## Spec
Middleware is SDK architecture, not an MCP spec feature.
## See also
`custom_methods/` (a vendor `acme/search` handler registered with
`add_request_handler` — middleware wraps it like any spec method),
`src/mcp/server/_otel.py` (`OpenTelemetryMiddleware`, the SDK's own consumer).
+27
View File
@@ -0,0 +1,27 @@
"""Prove the middleware wrapped both `tools/list` and the in-flight `tools/call`."""
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] == ["audit_log"]
result = await client.call_tool("audit_log", {})
assert not result.is_error
assert result.structured_content is not None, result
# Era-neutral: legacy adds initialize + notifications/initialized; modern HTTP
# adds server/discover; modern in-memory adds nothing. Filter to the methods
# this client drove.
seen = [m for m in result.structured_content["result"] if m.startswith("tools/")]
# The tail ends at tools/call with no :done — the handler ran inside the
# middleware frame. Assert the tail (not the whole list) so a re-run against
# a long-lived server, whose log accumulates across clients, still passes.
assert seen[-3:] == ["tools/list", "tools/list:done", "tools/call"], seen
if __name__ == "__main__":
run_client(main)
+54
View File
@@ -0,0 +1,54 @@
"""Dispatch-layer middleware: `Server.middleware` is the public hook.
A lowlevel-only story: `MCPServer` has no public middleware accessor yet, so the
one supported registration point is the `middleware` list on `lowlevel.Server`.
"""
import json
from typing import Any
import mcp_types as types
from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
from mcp.server.lowlevel import Server
from stories._hosting import run_server_from_args
def build_server() -> Server[Any]:
log: list[str] = []
async def record_calls(ctx: ServerRequestContext[Any], call_next: CallNext) -> HandlerResult:
log.append(ctx.method)
try:
return await call_next(ctx)
finally:
log.append(f"{ctx.method}:done")
async def list_tools(
ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
) -> types.ListToolsResult:
return types.ListToolsResult(
tools=[
types.Tool(
name="audit_log",
description="Return every method the middleware has observed so far.",
input_schema={"type": "object"},
)
]
)
async def call_tool(ctx: ServerRequestContext[Any], params: types.CallToolRequestParams) -> types.CallToolResult:
assert params.name == "audit_log"
snapshot = list(log)
return types.CallToolResult(
content=[types.TextContent(text=json.dumps(snapshot))],
structured_content={"result": snapshot},
)
server = Server("middleware-example", on_list_tools=list_tools, on_call_tool=call_tool)
server.middleware.append(record_calls)
return server
if __name__ == "__main__":
run_server_from_args(build_server)