Keep the live Context when a prompt or template annotates Context[T]
Merged
MA
2mo ago+97+97+01234567890123456789-30-30-01234567890123456789
Fixes #3235.
What was wrong
A prompt or resource-template function annotated ctx: Context[AppState] was handed an empty Context instead of the one for the request. The same annotation on a tool worked, and bare Context worked everywhere.
- Prompts and templates validate their call arguments with pydantic, and the injected context went through that validation too.
Context[AppState]is a separate class at runtime, so pydantic rebuilt the request's plainContextas a new instance, without the private attributes that hold the request.- Two symptoms:
ctx.request_context,ctx.request_idandctx.sessionraisedContext is not available outside of a request, which the client saw as an internal error.ctx.protocol_version,ctx.input_responsesandctx.request_stateread asNone. A multi-round-trip prompt or template never saw the answers and kept asking until the client raisedInputRequiredRoundsExceededError.
What changes
Contextgets a wrap-mode model validator that returns an existingContextinstance unchanged and leaves any other input to normal validation.- Prompts and templates are otherwise untouched: client arguments are cast and rejected exactly as before.
- No names, parameters or defaults change, and nothing changes on the wire.
- Docs: the "tool-only" warning on the Lifespan page and the matching paragraph in the migration guide are removed.
What users will notice
ctx: Context[AppState]now works on@mcp.prompt()and templated@mcp.resource()functions, sync or async, includingContext[AppState] | None.- Validating a live
ContextagainstContext[...]anywhere else, such as your own@validate_callhelper or a model field, now gives back the same object rather than an empty copy. - A function annotated with your own subclass of
Contextreceives the plainContexton prompts and templates, as it already does on tools. It used to fail validation there.
Not included
- Static resources still take no
Contextparameter; that is refused at decoration as before. - Translated docs pages are not regenerated here.
How it was checked
- New tests in
tests/server/mcpserver/test_server.py, both failing onmain:- a template, a sync prompt and an async prompt annotated
Context[AppState]read lifespan state and the protocol version through aClient - a multi-round-trip prompt annotated
Context[T]seesinput_responsesandrequest_stateon the retry
- a template, a sync prompt and an async prompt annotated
- The docs test that pinned the limitation now asserts the opposite.
- A small test covers
Context().request_contextraising outside a request, which only the pinning test used to reach. - The
mcpservertests also pass on pydantic 2.12.0 and 2.13.4. ./scripts/testpasses with 100% coverage; ruff and pyright are clean; the strict docs build reports no issues.