Let `MCPToolset` take `auth` and `headers` as functions of the run context, so each run connects as its own user

Merged
DO
1mo ago
+633-84

In a multi-user app, each user has their own credentials for an MCP server, so they can't be fixed when the MCPToolset is created. Until now the recommended pattern was to build a whole toolset per run with @agent.toolset(per_run_step=False). The more obvious approach, one shared toolset whose httpx.Auth reads the user from a ContextVar, sends overlapping runs' requests with the first run's token on FastMCP 3 (#6411).

This PR lets auth and headers be a function of the run context:

toolset = MCPToolset('https://mcp.example.com/mcp', auth=lambda ctx: ctx.deps.mcp_token)
agent = Agent('...', deps_type=UserDeps, toolsets=[toolset])

MCPToolset.for_run calls the function at the start of each run and returns a copy of the toolset that connects with the result. Each run therefore gets an MCP session of its own, opened with its own user's credentials, on both FastMCP 3 and 4.

Behavior

  • Static toolsets are unchanged. for_run returns self, and the existing session sharing applies. There's no new cost for anyone not using a function.
  • The template never connects. Each run enters its own copy, so entering the toolset itself (async with toolset: or async with agent:) does nothing. Calling a direct method like list_tools() on it raises a UserError that points to await toolset.for_run(ctx), which now returns Self, so the result is a typed MCPToolset.
  • What the copy keeps: it's a copy.copy, so it keeps the subclass type and settings changed after __init__, such as max_retries and set_sampling_model. It gets a fresh client, message handler and enter lock.
  • Validation:
    • A function only works with a URL client. A transport, a script path or an in-process server raises ValueError, and a pre-built fastmcp.Client hits the existing "configure these on the Client" error.
    • An auth function returning 'oauth' raises UserError: an interactive browser sign-in per run doesn't make sense, and the Harness integrations' auth functions have the same rule.
  • New public type aliases: MCPAuthFunc and MCPHeadersFunc, both generic in the deps type.

The MCP capability

MCP(authorization_token=..., headers=...) accepts the same kind of function, and uses the value it returns for that run on both sides:

agent = Agent('...', deps_type=Deps, capabilities=[MCP('https://mcp.example.com/api', authorization_token=lambda ctx: f'Bearer {ctx.deps.token}')])
  • Native: with native=True, _default_native() returns a per-run factory that builds the MCPServerTool with the resolved credentials, instead of a fixed instance. NativeOrLocalTool already supported a callable native; its _default_native() return type is widened to AgentNativeTool so a subclass can return one.
  • Local: the MCPToolset gets a headers function that merges the resolved token into the resolved headers, so each run gets its own session through the MCPToolset change above.
  • Unchanged: fixed credentials still produce a plain MCPServerTool and a fixed-headers MCPToolset. from_spec keeps accepting only serializable values.
  • None: a function returning None sends no Authorization header, matching authorization_token=None.

Durable execution

DurableMCPToolset needed two changes so the run uses the per-run copy rather than the template:

  • With the enter-in-durable-unit lifecycle (Prefect, DBOS), the run now holds await wrapped.for_run(ctx) rather than wrapped. For a static toolset that's the same object.
  • Outside a durable context, for_run now always resolves the wrapped toolset's per-run copy, whatever the lifecycle. Before, Temporal's enter-outside-durable returned self there, so a run outside a workflow would have called the template. _mcp_toolset now reads through wrapped, so a copy that _with_wrapped installs is the one that gets called.

Inside a Temporal workflow, activities already build the toolset through toolset_for_unit → toolset.for_run(ctx). With serialized deps they now get a per-activity copy with the right credentials.

Docs

The per-user authentication section now leads with auth=<function>. It explains why each user needs a session of their own, citing the MCP spec's rule that servers should bind session IDs to a user. It keeps the FastMCP 3 vs 4 detail from #10654, which this replaces, and keeps @agent.toolset for when users need more than their own credentials, such as a URL each.

Tests

  • Three concurrent agent runs on one toolset against an in-process HTTP server. The tool holds each call until all three are in flight, then returns the Authorization header and session identity it saw. Each run sees its own token, in three distinct sessions.
  • An async headers function resolved into the copy, with settings changed after __init__ carried over.
  • Template behavior, 'oauth' rejection, and URL-only validation.
  • Prefect: two runs in one flow, each holding its own per-run copy with its own credentials. The attached toolset never connects.
  • MCP capability: a function authorization_token (with fixed headers) and an async headers function each resolve per run on both the native tool and the local toolset; None sends no auth.

I smoke-tested the concurrent-runs scenario by hand on both fastmcp 3.4.7 / mcp 1.30.0, where a shared toolset leaks, and fastmcp 4.0.10 / mcp 2.3.0.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.

šŸ¤– Generated with Claude Code