Keep the live Context when a prompt or template annotates Context[T]

Merged
MA
2mo ago
+97-30

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 plain Context as a new instance, without the private attributes that hold the request.
  • Two symptoms:
    • ctx.request_context, ctx.request_id and ctx.session raised Context is not available outside of a request, which the client saw as an internal error.
    • ctx.protocol_version, ctx.input_responses and ctx.request_state read as None. A multi-round-trip prompt or template never saw the answers and kept asking until the client raised InputRequiredRoundsExceededError.

What changes

  • Context gets a wrap-mode model validator that returns an existing Context instance 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, including Context[AppState] | None.
  • Validating a live Context against Context[...] anywhere else, such as your own @validate_call helper or a model field, now gives back the same object rather than an empty copy.
  • A function annotated with your own subclass of Context receives the plain Context on prompts and templates, as it already does on tools. It used to fail validation there.

Not included

  • Static resources still take no Context parameter; 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 on main:
    • a template, a sync prompt and an async prompt annotated Context[AppState] read lifespan state and the protocol version through a Client
    • a multi-round-trip prompt annotated Context[T] sees input_responses and request_state on the retry
  • The docs test that pinned the limitation now asserts the opposite.
  • A small test covers Context().request_context raising outside a request, which only the pinning test used to reach.
  • The mcpserver tests also pass on pydantic 2.12.0 and 2.13.4.
  • ./scripts/test passes with 100% coverage; ruff and pyright are clean; the strict docs build reports no issues.

AI Disclaimer