openllmetry icon indicating copy to clipboard operation
openllmetry copied to clipboard

mcp: nested async with Client leaks the session span context

Open doronkopit5 opened this issue 2 months ago • 1 comments

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.

doronkopit5 avatar Sep 27 '26 12:09 doronkopit5

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.session span 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?

aarongdeng avatar Oct 09 '26 03:10 aarongdeng