49b9bb6724
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
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
# 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.pymain— opens withClient(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 thelookupresults are the only proof the yielded state was wired through.app_lifespaninserver.py— thetry / yield / finallyshape is the startup/shutdown contract; thefinallyblock runs once on process exit, not per request.ctx.request_context.lifespan_context.dbin thelookuptool — the interim 3-hop access path onMCPServer'sContext.server_lowlevel.pyreaches the same state viactx.lifespan_context.db— one hop, because lowlevel handlers receiveServerRequestContextdirectly.
Caveats
ctx.request_context.lifespan_contextis the interim path; a later release will shorten this toctx.state.*. The lowlevelctx.lifespan_contextpath is unaffected.- v1 → v2 scope change — in v1.x,
lifespanwas entered once perServer.run()call: once per session for stateful streamable HTTP and once per request understateless_http=True(stdio was already per-process). In v2 it is entered once per process regardless of transport. Seedocs/migration.md("Streamable HTTP: lifespan now entered once at manager startup").
Spec
See also
stickynotes/ (lifespan-held mutable state with change notifications),
serve_one/ (threading lifespan_state into the kernel by hand).