mcp: nested async with Client leaks the session span context
Problem
fastmcp's Client is reentrant (nested async with client reuses the session via a nesting counter). The MCP instrumentation doesn't account for that. Every __aenter__ starts a new mcp.client.session span and overwrites _tracing_session_context_manager / _tracing_session_span on the instance, so the exits don't line up with the enters.
client = Client(server)
async with client:
async with client:
await client.call_tool("fast", {})
trace.get_current_span().name # still "mcp.client.session"
After the outer block exits, a session span is still attached as the current context, so later spans in that task get parented to it.
Expected
One session span per actual session: start it on the outermost enter and end it on the matching exit. Alternatively, keep a stack of spans per client so each exit ends the span its enter started.
Found while reviewing #4517.
I'd like to work on this issue. I reproduced the leaked session-span context on
current main and have a local fix that:
- keeps one
mcp.client.sessionspan for a reentrant FastMCP session; - tracks OpenTelemetry context tokens per asyncio task;
- ends the span only after the final active entry exits; and
- balances failed, cancelled, nested, and concurrent entries.
The fix also requires lifecycle exceptions from the wrapped FastMCP call to
propagate instead of being swallowed by @dont_throw, so it overlaps with
#4520. Would you prefer a self-contained PR against current main, or should I
wait for #4520 and rebase the session-lifecycle changes on top of it?