Document per-user MCP authentication: build `MCPToolset` per run via `@agent.toolset`

Merged
DO
5mo ago
+50-1

A shared MCPToolset instance maintains a single MCP session for all concurrent agent runs, created under whichever run enters it first. As reported in #6411 (against the since-removed MCPServerStreamableHTTP, but verified to still apply to MCPToolset through FastMCP's Client and the MCP SDK's streamable HTTP transport), this means per-request credentials derived from a ContextVar inside an httpx.Auth silently send overlapping runs' requests under the first caller's identity.

The underlying context propagation gap lives in the MCP Python SDK's transport layer (modelcontextprotocol/python-sdk#1969). It was fixed by modelcontextprotocol/python-sdk#2298, but that fix only shipped on the mcp 2.0 line (currently in beta) and was not backported to stable 1.x — and FastMCP pins mcp<2.0, so the leak is present throughout the currently supported stack (verified live on mcp 1.25.0 and 1.28.1; verified fixed at the raw-SDK level on mcp 2.0.0b1). It can't be fixed from Pydantic AI's layer, and a shared MCP session is arguably a single identity at the protocol level anyway, so this PR documents the footgun and the supported pattern:

  • New HTTP authentication → Per-user authentication section in docs/mcp/client.md with a warning about shared instances being a single identity, and a tested example building a fresh MCPToolset per run via @agent.toolset(per_run_step=False) with the user's token from ctx.deps.
  • Cross-links from the toolset-sharing paragraph in docs/mcp/client.md and the dynamic-toolsets section in docs/toolsets.md.

The example and both patterns (deps-based and ContextVar-based auth via a dynamic toolset) were verified end-to-end against a live streamable HTTP FastMCP server that echoes the Authorization header it receives: the shared-instance repro leaks (bob authenticated as alice), the dynamic-toolset pattern authenticates each concurrent run correctly.

Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy.
  • PR title is fit for the release changelog.