mcp: nested async with Client leaks the session span context

Author: doronkopit5Created Sep 27, 2026Updated Sep 27, 2026

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.

python
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.