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) Has been cancelled

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
+53
View File
@@ -0,0 +1,53 @@
# lifespan
Process-scoped dependency injection. Pass an `@asynccontextmanager` as
`lifespan=` to acquire resources (a database pool, an HTTP client) once at
startup and release them at shutdown; tool bodies read the yielded state via
the injected `Context` — no module-level globals.
## Run it
```bash
# stdio (default — the client spawns the server as a subprocess)
uv run python -m stories.lifespan.client
# HTTP — the client self-hosts the server on a free port, runs, then tears it down
uv run python -m stories.lifespan.client --http
# same, against the lowlevel-API server variant
uv run python -m stories.lifespan.client --http --server server_lowlevel
```
## What to look at
- `client.py` `main` — opens with `Client(target, mode=mode)`; the story owns
the construction, the harness only chooses the target and era. Lifespan is
invisible from here: the client speaks plain MCP, and the `lookup` results
are the only proof the yielded state was wired through.
- `app_lifespan` in `server.py` — the `try / yield / finally` shape is the
startup/shutdown contract; the `finally` block runs once on process exit, not
per request.
- `ctx.request_context.lifespan_context.db` in the `lookup` tool — the interim
3-hop access path on `MCPServer`'s `Context`.
- `server_lowlevel.py` reaches the same state via `ctx.lifespan_context.db`
one hop, because lowlevel handlers receive `ServerRequestContext` directly.
## Caveats
- `ctx.request_context.lifespan_context` is the interim path; a later release
will shorten this to `ctx.state.*`. The lowlevel `ctx.lifespan_context` path
is unaffected.
- **v1 → v2 scope change** — in v1.x, `lifespan` was entered once per
`Server.run()` call: once per *session* for stateful streamable HTTP and once
per *request* under `stateless_http=True` (stdio was already per-process). In
v2 it is entered once per process regardless of transport. See
`docs/migration.md` ("Streamable HTTP: lifespan now entered once at manager
startup").
## Spec
[Lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle)
## See also
`stickynotes/` (lifespan-held mutable state with change notifications),
`serve_one/` (threading `lifespan_state` into the kernel by hand).
+22
View File
@@ -0,0 +1,22 @@
"""Prove the lifespan-yielded state is reachable from a tool call."""
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] == ["lookup"]
result = await client.call_tool("lookup", {"key": "alpha"})
assert isinstance(result.content[0], TextContent) and result.content[0].text == "one", result
result = await client.call_tool("lookup", {"key": "beta"})
assert isinstance(result.content[0], TextContent) and result.content[0].text == "two", result
if __name__ == "__main__":
run_client(main)
+39
View File
@@ -0,0 +1,39 @@
"""Process-scoped dependency injection via `MCPServer(lifespan=...)`."""
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Any
from mcp.server.mcpserver import Context, MCPServer
from stories._hosting import run_server_from_args
@dataclass
class AppState:
db: dict[str, str]
@asynccontextmanager
async def app_lifespan(server: MCPServer[AppState]) -> AsyncIterator[AppState]:
"""Acquire process-scoped resources at startup; release them at shutdown."""
db = {"alpha": "one", "beta": "two"} # e.g. `await pool.connect()`
try:
yield AppState(db=db)
finally:
db.clear() # e.g. `await pool.disconnect()`
def build_server() -> MCPServer[AppState]:
mcp = MCPServer[AppState]("lifespan-example", lifespan=app_lifespan)
@mcp.tool(description="Look up a key in the process-scoped store.")
def lookup(key: str, ctx: Context[AppState, Any]) -> str:
# Interim 3-hop path; shortens to `ctx.state.db` in a later release.
return ctx.request_context.lifespan_context.db[key]
return mcp
if __name__ == "__main__":
run_server_from_args(build_server)
@@ -0,0 +1,66 @@
"""Process-scoped dependency injection via lowlevel `Server(lifespan=...)`."""
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Any
import mcp_types as types
from mcp.server.context import ServerRequestContext
from mcp.server.lowlevel import Server
from stories._hosting import run_server_from_args
@dataclass
class AppState:
db: dict[str, str]
@asynccontextmanager
async def app_lifespan(server: Server[AppState]) -> AsyncIterator[AppState]:
db = {"alpha": "one", "beta": "two"}
try:
yield AppState(db=db)
finally:
db.clear()
LOOKUP_INPUT_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {"key": {"type": "string"}},
"required": ["key"],
}
def build_server() -> Server[AppState]:
async def list_tools(
ctx: ServerRequestContext[AppState], params: types.PaginatedRequestParams | None
) -> types.ListToolsResult:
return types.ListToolsResult(
tools=[
types.Tool(
name="lookup",
description="Look up a key in the process-scoped store.",
input_schema=LOOKUP_INPUT_SCHEMA,
)
]
)
async def call_tool(
ctx: ServerRequestContext[AppState], params: types.CallToolRequestParams
) -> types.CallToolResult:
assert params.name == "lookup" and params.arguments is not None
value = ctx.lifespan_context.db[params.arguments["key"]]
return types.CallToolResult(content=[types.TextContent(text=value)])
return Server[AppState](
"lifespan-example",
lifespan=app_lifespan,
on_list_tools=list_tools,
on_call_tool=call_tool,
)
if __name__ == "__main__":
run_server_from_args(build_server)