Let `MCPToolset` take `auth` and `headers` as functions of the run context, so each run connects as its own user
- Related to #6411
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_runreturnsself, 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:orasync with agent:) does nothing. Calling a direct method likelist_tools()on it raises aUserErrorthat points toawait toolset.for_run(ctx), which now returnsSelf, so the result is a typedMCPToolset. - What the copy keeps: it's a
copy.copy, so it keeps the subclass type and settings changed after__init__, such asmax_retriesandset_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 raisesValueError, and a pre-builtfastmcp.Clienthits the existing "configure these on the Client" error. - An
authfunction returning'oauth'raisesUserError: an interactive browser sign-in per run doesn't make sense, and the Harness integrations'authfunctions have the same rule.
- A function only works with a URL
- New public type aliases:
MCPAuthFuncandMCPHeadersFunc, 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 theMCPServerToolwith the resolved credentials, instead of a fixed instance.NativeOrLocalToolalready supported a callablenative; its_default_native()return type is widened toAgentNativeToolso a subclass can return one. - Local: the
MCPToolsetgets aheadersfunction that merges the resolved token into the resolved headers, so each run gets its own session through theMCPToolsetchange above. - Unchanged: fixed credentials still produce a plain
MCPServerTooland a fixed-headersMCPToolset.from_speckeeps accepting only serializable values. None: a function returningNonesends noAuthorizationheader, matchingauthorization_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-unitlifecycle (Prefect, DBOS), the run now holdsawait wrapped.for_run(ctx)rather thanwrapped. For a static toolset that's the same object. - Outside a durable context,
for_runnow always resolves the wrapped toolset's per-run copy, whatever the lifecycle. Before, Temporal'senter-outside-durablereturnedselfthere, so a run outside a workflow would have called the template._mcp_toolsetnow reads throughwrapped, so a copy that_with_wrappedinstalls 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
Authorizationheader and session identity it saw. Each run sees its own token, in three distinct sessions. - An async
headersfunction 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.
MCPcapability: a functionauthorization_token(with fixedheaders) and an asyncheadersfunction each resolve per run on both the native tool and the local toolset;Nonesends 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