Back to Community & Earn Hub

OpenTelemetry for Multi-Agent Systems: Distributed Trace Propagation Across Async Tool Calls, Sub-Agents, and MCP Servers

@siddharth_rao15 hours ago·2 min read 1855 views
OpenTelemetry for Multi-Agent Systems: Distributed Trace Propagation Across Async Tool Calls, Sub-Agents, and MCP Servers

Why Single-LLM Logging Breaks in Multi-Agent Architectures

In a simple RAG chatbot, logging one prompt and one completion is enough to debug failures.

In a production multi-agent architecture, a single user request fans out across multiple processes:

  • Coordinator Agent plans a 4-step workflow.
  • 2 Sub-Agents run concurrently in isolated worker queues.
  • 3 MCP Servers execute database queries, Git diffs, and Redis lookups over stdio or HTTP/SSE.

When latency spikes to 14 seconds or a sub-agent silently drops a tool error, disconnected log lines make root-cause analysis nearly impossible. You need end-to-end distributed tracing.


Propagating W3C traceparent Over MCP JSON-RPC _meta

HTTP frameworks propagate OpenTelemetry context automatically via the traceparent header. However, local stdio MCP servers and async task queues do not share HTTP headers.

The Model Context Protocol specification reserves a _meta object on JSON-RPC params specifically for out-of-band metadata. Injecting W3C trace context into params._meta bridges parent agent spans directly into downstream MCP tool spans:

text
[Coordinator Span: trace_id=9f2a...]
   ├── [LLM Planner Span: gen_ai.usage.input_tokens=4120]
   ├── [Sub-Agent A Span] ──(JSON-RPC _meta.traceparent)──► [MCP Postgres Server Span]
   └── [Sub-Agent B Span] ──(JSON-RPC _meta.traceparent)──► [MCP GitHub Server Span]

Python OpenTelemetry Instrumentation Pattern

Here is how to inject trace context on the MCP client side and extract it inside an async Python MCP tool handler:

python
from opentelemetry import trace
from opentelemetry.propagate import inject, extract
from opentelemetry.trace import SpanKind

tracer = trace.get_tracer("aistorehub.agent.runtime")

# 1. Client-side: Inject W3C traceparent into MCP JSON-RPC _meta
async def call_mcp_tool_traced(mcp_client, tool_name: str, arguments: dict):
    with tracer.start_as_current_span(
        f"mcp.tool.call {tool_name}",
        kind=SpanKind.CLIENT,
        attributes={
            "gen_ai.tool.name": tool_name,
            "mcp.transport": "stdio",
        },
    ) as span:
        carrier: dict[str, str] = {}
        inject(carrier)  # Populates {'traceparent': '00-...'}

        payload = {
            "name": tool_name,
            "arguments": arguments,
            "_meta": carrier,
        }
        result = await mcp_client.request("tools/call", payload)
        span.set_attribute("mcp.tool.is_error", bool(result.get("isError")))
        return result


# 2. Server-side: Extract parent context inside the MCP Server
async def handle_mcp_tool_request(params: dict):
    meta_carrier = params.get("_meta", {})
    parent_ctx = extract(meta_carrier)

    with tracer.start_as_current_span(
        f"mcp.server.exec {params['name']}",
        context=parent_ctx,
        kind=SpanKind.SERVER,
    ) as span:
        span.set_attribute("gen_ai.tool.name", params["name"])
        return await execute_tool_logic(params["arguments"])

Adopting OpenTelemetry GenAI Semantic Conventions

To keep traces compatible with Jaeger, Grafana Tempo, Datadog, and Arize Phoenix without vendor lock-in, standardize on the official gen_ai.* attributes:

  • gen_ai.system: "anthropic" | "openai" | "vllm"
  • gen_ai.request.model: "claude-3-5-sonnet"
  • gen_ai.usage.input_tokens / gen_ai.usage.output_tokens
  • gen_ai.usage.cache_read_input_tokens (essential for tracking prompt-cache hit rates per trace!)

With unified trace propagation, every token spent and every millisecond waited across sub-agents and MCP tools appears in a single flamegraph.

2 Comments

Discussion

@priya_sharma15 hours ago

Injecting traceparent into MCP's _meta field is so clean. Before we added that, our Jaeger traces stopped dead at the FastAPI gateway boundary and all downstream MCP server tool executions showed up as orphaned root spans.

@rohan_mehta15 hours ago

Tracking gen_ai.usage.cache_read_input_tokens directly on the OpenTelemetry span is also a lifesaver for spotting prompt-cache regressions after deployments.

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.