Articles

MCP Tracing with OpenTelemetry: Setup and Troubleshooting

MCP tracing that survives the process boundary: give client and server their own providers, carry traceparent in _meta, and fix split traces and stdio env loss.

· 15 min read
mcp opentelemetry distributed-tracing llm-observability ai-agents python troubleshooting
MCP tracing shown as interlocked chain links joined by traceparent in params._meta, above a broken chain split into two trace ids.

A customer says the booking agent refused to book their flight. The agent’s trace shows the tools/call client span to the travel MCP server at status UNSET, a clean-looking call. The server span holding the error sits in another trace, or never arrived.

MCP tracing breaks at the process boundary. It follows one tool call from the agent into the Model Context Protocol (MCP) server, two processes with separate tracer providers, and only trace context inside the JSON-RPC request joins their spans. The customer scene is illustrative, built from run D.

The fix starts with why the split happens, then how context crosses in params._meta, what the MCP Python SDK 2.3.0 already does, a two-process setup tested end to end, and a troubleshooting matrix backed by six printed runs, all on synthetic tool data.

TL;DR

  • MCP tracing needs trace context to cross the transport: the server’s span joins the agent’s trace only when the request carries traceparent in params._meta.
  • The official Python SDK, mcp 2.3.0, creates client and server spans and propagates context itself; mcp 1.x has none, and TypeScript’s built-in tracing is unreleased as of 2026-11-25.
  • Each process needs its own TracerProvider and exporter, and a stdio server must keep spans off stdout, which carries the protocol.
  • On stdio, stdio_client starts the server with a short environment allowlist, so OTEL_* variables arrive only through StdioServerParameters env.
  • An isError result leaves the SDK client span UNSET while the server span is ERROR with error.type tool_error, so mark the agent’s tool span yourself.

MCP tracing splits into two traces at the process boundary

MCP tracing splits because the agent and the MCP server are separate processes, each with its own tracer provider. A server span gets no parent unless trace context travels inside the request. Without it, a stdio server with no current span starts a fresh trace per message, and the tool call cannot be followed end to end.

The agent exports through the client’s provider and the server through its own. Each mints its own trace ids, and the client’s context never leaves its process unless written into the request. Span basics live in what LLM tracing is.

What a client without trace context produces

Run A is a hand-written JSON-RPC client. It starts server.py over stdio and, inside an agent.run span, sends initialize, notifications/initialized and a tools/call for get_weather with no params._meta. The server and shared setup appear in the setup section.

"""A hand-written JSON-RPC stdio client, the kind that breaks traces.

Run A (no flag): tools/call goes out with no params._meta, so the server span
starts its own trace. Run B (--inject): opentelemetry.propagate.inject writes
traceparent (and tracestate or baggage, if present) into params._meta, which is
what the mcp 2.x client does for you, so the server span joins the agent trace.
Usage: client_raw.py SPANS_FILE [--inject]
"""

import json
import os
import subprocess
import sys

from opentelemetry import propagate, trace

from otel_setup import setup_tracing

HERE = os.path.dirname(os.path.abspath(__file__))


def rpc(proc, msg, inject=False):
    if inject and "id" in msg:  # requests only, as the mcp 2.3.0 client does
        carrier = {}
        propagate.inject(carrier)
        msg["params"]["_meta"] = carrier
        print(f"{msg['method']} params._meta:", carrier)
    proc.stdin.write(json.dumps(msg) + "\n")
    proc.stdin.flush()
    if "id" not in msg:
        return None
    while True:  # skip notifications until our response arrives
        reply = json.loads(proc.stdout.readline())
        if reply.get("id") == msg["id"]:
            return reply


def main():
    spans_file, inject = sys.argv[1], "--inject" in sys.argv
    setup_tracing("agent-raw-client", spans_file)
    tracer = trace.get_tracer("demo-agent")

    env = {"PATH": os.environ["PATH"], "OTEL_SPANS_FILE": spans_file}
    proc = subprocess.Popen([sys.executable, os.path.join(HERE, "server.py")], stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE, text=True, env=env)
    with tracer.start_as_current_span("agent.run") as root:
        rpc(proc, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
            "protocolVersion": "2025-11-25", "capabilities": {},
            "clientInfo": {"name": "raw-client", "version": "0.0.1"}}}, inject)
        rpc(proc, {"jsonrpc": "2.0", "method": "notifications/initialized"})

        params = {"name": "get_weather", "arguments": {"city": "Lisbon"}}  # SYNTHETIC input
        reply = rpc(proc, {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": params}, inject)
        print("agent trace id:", format(root.get_span_context().trace_id, "032x"))
        print("tools/call result:", json.dumps(reply["result"]))
    proc.stdin.close()
    proc.wait(timeout=10)


if __name__ == "__main__":
    main()
================ RUN A: client_raw.py
$ : > spans_A.jsonl
$ python client_raw.py spans_A.jsonl
agent trace id: bba3b6a06ccaa3714b92261e60905503
tools/call result: {"content": [{"text": "Lisbon: 18 C, light rain (synthetic demo data)", "type": "text"}], "isError": false, "structuredContent": {"result": "Lisbon: 18 C, light rain (synthetic demo data)"}}
--- exit 0
$ python join.py spans_A.jsonl --joined
4 spans in 4 trace(s)
trace cd58c52a125182e4cd25008fb739831d
  initialize  [SERVER, travel-mcp-server] status=UNSET
trace 36ae396cc771a3444c346695a9359f6b
  notifications/initialized  [SERVER, travel-mcp-server] status=UNSET
trace dc41b01f9ef9116ec8566f1b5b75dc17
  tools/call get_weather  [SERVER, travel-mcp-server] status=UNSET
trace bba3b6a06ccaa3714b92261e60905503
  agent.run  [INTERNAL, agent-raw-client] status=UNSET
AssertionError: agent.run and tools/call server spans sit in 2 different trace ids
--- exit 1

join.py printed “4 spans in 4 trace(s)”: each of the three server messages started its own trace, agent.run sat alone and the join check failed. The tool call itself returned “isError”: false, so nothing errors and the split goes unnoticed.

How trace context crosses the MCP transport

Trace context crosses the MCP transport inside the request’s params._meta field. The client writes the W3C traceparent there, plus tracestate or baggage when its propagators produce them, and the server reads it back as the parent of its own span. The MCP 2026-07-28 spec reserves those keys through SEP-414.

On the client, opentelemetry.propagate.inject(carrier) fills a dict from the current span through OpenTelemetry Python’s default tracecontext and baggage propagators, and the server extracts it. Since _meta lives in the JSON-RPC message, this works over stdio, SSE and streamable HTTP.

See the MCP 2026-07-28 Basic specification, SEP-414 and W3C Trace Context; what MCP Inspector cannot show you quotes the spec text and semantic-convention tiers.

The agent process writes traceparent into params._meta with propagate.inject, so the MCP server's tools/call get_weather span joins agent.run in one trace; run A printed 4 spans in 4 traces and run B printed 4 spans in 2

What propagate.inject wrote in run B

Run B adds —inject, so the rpc() helper in client_raw.py writes the carrier into params._meta on requests only, as the mcp 2.3.0 client does internally. The same helper is the client-side fix for mcp 1.x, hand-written clients, custom transports and other languages:

def rpc(proc, msg, inject=False):
    if inject and "id" in msg:  # requests only, as the mcp 2.3.0 client does
        carrier = {}
        propagate.inject(carrier)
        msg["params"]["_meta"] = carrier
        print(f"{msg['method']} params._meta:", carrier)
$ : > spans_B.jsonl
$ python client_raw.py spans_B.jsonl --inject
initialize params._meta: {'traceparent': '00-68332a96b2ae5e2dcadf24713a8b2368-71c2ebfbf38c460b-03'}
tools/call params._meta: {'traceparent': '00-68332a96b2ae5e2dcadf24713a8b2368-71c2ebfbf38c460b-03'}
agent trace id: 68332a96b2ae5e2dcadf24713a8b2368
tools/call result: {"content": [{"text": "Lisbon: 18 C, light rain (synthetic demo data)", "type": "text"}], "isError": false, "structuredContent": {"result": "Lisbon: 18 C, light rain (synthetic demo data)"}}
--- exit 0
$ python join.py spans_B.jsonl --joined
4 spans in 2 trace(s)
trace 68332a96b2ae5e2dcadf24713a8b2368
  agent.run  [INTERNAL, agent-raw-client] status=UNSET
    initialize  [SERVER, travel-mcp-server] status=UNSET
    tools/call get_weather  [SERVER, travel-mcp-server] status=UNSET
trace d78382ef5199d39dbdfb4e1c3192f011
  notifications/initialized  [SERVER, travel-mcp-server] status=UNSET
OK: agent.run and every tools/call server span share one trace id
--- exit 0

Only traceparent appeared, since no tracestate or baggage was set, and initialize and tools/call get_weather now sit under agent.run. The flags byte 03 is sampled (0x01) plus random-trace-id (0x02), the TraceFlags bits opentelemetry-api 1.45.2 defines, not the spec example’s 01.

What the MCP Python SDK 2.3.0 already traces

The official Python SDK, mcp 2.3.0, traces both sides of a request with no extra package. The server wraps every inbound message in a SERVER span, the client wraps every outbound request in a CLIENT span, and the client injects trace context into params._meta that the server extracts, so two SDK processes join on their own.

The SDK depends only on opentelemetry-api: “With no SDK and no exporter installed, creating a span is a no-op.” Its tracer is the global get_tracer("mcp-python-sdk"), so each process sets its provider globally, and the underscored middleware import is documented as provisional.

The dependency and provisional import are in the SDK’s OpenTelemetry guide at v2.3.0.

Server spans per inbound message

Each inbound message gets one SERVER span named {method} {target}, such as tools/call get_weather, with mcp.method.name, mcp.protocol.version and, on requests, jsonrpc.request.id; tools/call adds gen_ai.operation.name, plus gen_ai.tool.name for a named tool. Missing or malformed _meta falls back to ambient parenting; an isError result sets error.type tool_error and ERROR.

The client span and automatic propagation

Run SDK swaps in the official ClientSession over stdio_client, inside agent.run and the agent’s own execute_tool span. With no propagation code in the client, join.py printed “9 spans in 2 trace(s)”, each client span above the server span it caused:

$ : > spans_SDK.jsonl
$ python client_sdk.py spans_SDK.jsonl
agent trace id: 59866dafd116d623baafdf9369567a4d sampled=True
get_weather: is_error=False content='Lisbon: 18 C, light rain (synthetic demo data)'
--- exit 0
$ python join.py spans_SDK.jsonl --joined
9 spans in 2 trace(s)
trace 59866dafd116d623baafdf9369567a4d
  agent.run  [INTERNAL, agent-sdk-client] status=UNSET
    MCP send initialize  [CLIENT, agent-sdk-client] status=UNSET
      initialize  [SERVER, travel-mcp-server] status=UNSET
    execute_tool get_weather  [INTERNAL, agent-sdk-client] status=UNSET
      MCP send tools/call get_weather  [CLIENT, agent-sdk-client] status=UNSET
        tools/call get_weather  [SERVER, travel-mcp-server] status=UNSET
      MCP send tools/list  [CLIENT, agent-sdk-client] status=UNSET
        tools/list  [SERVER, travel-mcp-server] status=UNSET
trace a572fdac93a97fc82d3b00b2786878aa
  notifications/initialized  [SERVER, travel-mcp-server] status=UNSET
OK: agent.run and every tools/call server span share one trace id
--- exit 0

The extra tools/list is the SDK’s own call: in 2.3.0, call_tool validates a successful result against the tool’s output schema and fetches the schema when uncached, so it follows get_weather and not the isError calls in run D.

The client span is kind CLIENT with mcp.method.name and jsonrpc.request.id. The client injects context while that span is current, so the server span hangs off it, and an empty _meta is dropped, not sent. notifications/initialized sits in its own trace.

mcp 1.x and the TypeScript SDK

mcp 1.30.0, the newest 1.x release (2026-09-07), has no tracing code and needs no OpenTelemetry package. On 1.x both processes need an instrumentation that carries context, plus your own tracing to create spans; the Future AGI section names one route.

The TypeScript SDK’s tracing pull request merged on main on 2026-10-31, but the latest npm releases, @modelcontextprotocol/client and server 2.4.0 and @modelcontextprotocol/sdk 1.32.2, date from 2026-10-23. As of 2026-11-25 it is unreleased and its docs call it Experimental, so check npm first.

Where 2.3.0 differs from the MCP semantic conventions

As observed in 2.3.0, the client span is named “MCP send tools/call get_weather”, while the Development-status conventions say it SHOULD be {mcp.method.name} {target}. And 2.3.0 writes rpc.response.status_code, the old name that the semantic-conventions registry at v1.45.0 marks deprecated in favour of rpc.status_code.

Error status deviates on the server span only. In run D the SERVER span is ERROR on -32601 and -32602, which the server section says “SHOULD NOT be considered errors”. The CLIENT span is ERROR too, which the client section allows: “All JSON-RPC error codes SHOULD be considered errors.”

Read OpenTelemetry semantic conventions for MCP and the OpenTelemetry RPC attribute registry at v1.45.0; python-sdk issue 3811 asks to change the client span.

The SDK sets no mcp.session.id, and separately the 2026-07-28 spec removed protocol-level sessions, so skip dashboards on it. Every SERVER span in runs A, B, SDK, D and E shows mcp.protocol.version 2025-11-25, the negotiated stdio version; the client span omits it.

Setting up OpenTelemetry MCP instrumentation in both processes

An MCP OpenTelemetry setup needs one TracerProvider and one exporter in every process, each set as the global provider, because the SDK’s spans use the global tracer. On a stdio server, stdout is the protocol channel, so spans go to a file, stderr or an OTLP endpoint, never to a console exporter on stdout.

Pin what these runs used. The code writes spans to a small JSONL file exporter so both processes join offline; an OTLP exporter sends the same spans to a backend (not part of these runs), and the OpenTelemetry Collector for LLM traces covers routing and redaction.

pip install mcp==2.3.0 opentelemetry-sdk==1.45.2
# add opentelemetry-exporter-otlp-proto-http==1.45.2 when spans go to a backend

The server process on stdio

The exporter appends, so start each run with an empty output file. Clear it once in the invoking shell before starting either process, never in the shared exporter constructor.

Both processes call setup_tracing from otel_setup.py: a TracerProvider with a service.name resource, a SimpleSpanProcessor and a 20-line JsonlFileExporter, set as the global provider. Both files are tested end to end with mcp 2.3.0 and opentelemetry-sdk 1.45.2 on Python 3.12.13.

"""OpenTelemetry setup shared by the MCP client and server examples.

Spans go to a JSONL file, never to stdout: on a stdio MCP server, stdout is the
protocol channel, so a console exporter there would corrupt JSON-RPC traffic.
Swap JsonlFileExporter for an OTLP exporter to send the same spans to a backend.
"""

import json

from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult


class JsonlFileExporter(SpanExporter):
    """Appends one JSON line per finished span (O_APPEND keeps both processes' lines whole)."""

    def __init__(self, path: str):
        self.path = path

    def export(self, spans):
        with open(self.path, "a", encoding="utf-8") as f:
            for s in spans:
                f.write(json.dumps({
                    "service": s.resource.attributes.get("service.name"),
                    "name": s.name,
                    "kind": s.kind.name,
                    "trace_id": format(s.context.trace_id, "032x"),
                    "span_id": format(s.context.span_id, "016x"),
                    "parent_id": format(s.parent.span_id, "016x") if s.parent else None,
                    "status": s.status.status_code.name,
                    "attributes": dict(s.attributes or {}),
                }) + "\n")
        return SpanExportResult.SUCCESS


def setup_tracing(service_name: str, spans_file: str, sampler=None) -> TracerProvider:
    """One provider per process, set as the global provider (the MCP SDK uses the global tracer)."""
    kwargs = {"sampler": sampler} if sampler is not None else {}
    provider = TracerProvider(resource=Resource.create({"service.name": service_name}), **kwargs)
    provider.add_span_processor(SimpleSpanProcessor(JsonlFileExporter(spans_file)))
    trace.set_tracer_provider(provider)
    return provider

server.py runs an MCPServer named travel-demo with two synthetic tools: get_weather succeeds, and book_flight returns is_error=True for a past date. The SDK already wraps every message, so the file adds a provider only when OTEL_SPANS_FILE is set.

"""A small stdio MCP server with one tool that succeeds and one that fails.

mcp 2.x already wraps every inbound message in a SERVER span; this file only
gives the process a provider and an exporter. It configures them only when
OTEL_SPANS_FILE is set, which is exactly the variable stdio_client drops unless
the client passes it in StdioServerParameters(env=...).
Tool outputs are SYNTHETIC demo data: no weather API or booking system is called.
"""

import datetime
import os

from mcp.server.mcpserver import MCPServer
from mcp.types import CallToolResult, TextContent

if os.environ.get("OTEL_SPANS_FILE"):
    from otel_setup import setup_tracing

    setup_tracing("travel-mcp-server", os.environ["OTEL_SPANS_FILE"])

mcp = MCPServer("travel-demo")


@mcp.tool()
def get_weather(city: str) -> str:
    """Return the weather for a city (SYNTHETIC fixed reply)."""
    return f"{city}: 18 C, light rain (synthetic demo data)"


@mcp.tool()
def book_flight(destination: str, date: str) -> CallToolResult:
    """Book a flight; a past date comes back as a tool error (isError true), not an exception."""
    if datetime.date.fromisoformat(date) < datetime.date.today():
        return CallToolResult(
            content=[TextContent(type="text", text=f"Cannot book {date}: the date is in the past")],
            is_error=True,
        )
    return CallToolResult(content=[TextContent(type="text", text=f"Booked {destination} on {date} (synthetic, nothing booked)")])


if __name__ == "__main__":
    mcp.run("stdio")

The client process and the join check

client_sdk.py gives the agent its own provider, an agent.run span and an execute_tool span around session.call_tool, and passes OTEL_SPANS_FILE through StdioServerParameters env. Its flags reproduce runs C, D and E, all with synthetic tool inputs.

"""The official mcp 2.3.0 client: trace context crosses stdio on its own.

Usage: client_sdk.py SPANS_FILE [--no-env | --fail | --unsampled]
  (no flag)    get_weather; the SDK opens "MCP send tools/call get_weather" and injects _meta
  --no-env     omit OTEL_SPANS_FILE from StdioServerParameters env (run C: zero server spans)
  --fail       book_flight with a past date, an unknown tool, then two JSON-RPC protocol errors (run D)
  --unsampled  agent root sampled out with ParentBased(ALWAYS_OFF) (run E: the server child follows the flag)
All tool inputs are SYNTHETIC demo values.
"""

import asyncio
import os
import sys

from mcp import ClientSession, MCPError, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from opentelemetry import trace
from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ParentBased
from opentelemetry.trace import StatusCode

from otel_setup import setup_tracing

HERE = os.path.dirname(os.path.abspath(__file__))
tracer = trace.get_tracer("demo-agent")


async def call_tool_traced(session, name, arguments):
    """The agent's own tool span. isError true is a normal result, so mark it here."""
    with tracer.start_as_current_span(f"execute_tool {name}") as span:
        result = await session.call_tool(name, arguments)
        if result.is_error:  # the 3-line client-side helper
            span.set_attribute("error.type", "tool_error")
            span.set_status(StatusCode.ERROR)
        print(f"{name}: is_error={result.is_error} content={result.content[0].text!r}")
        return result


async def protocol_error(session, method, params):
    """Send a raw request and print the JSON-RPC error code that comes back."""
    try:
        await session.send_request(types.Request(method=method, params=params), types.EmptyResult)
        print(f"{method} {params}: no error")
    except MCPError as e:
        print(f"{method} {params}: JSON-RPC error code={e.error.code} message={e.error.message!r}")


async def main():
    spans_file = sys.argv[1]
    no_env, fail, unsampled = ("--no-env" in sys.argv, "--fail" in sys.argv, "--unsampled" in sys.argv)
    setup_tracing("agent-sdk-client", spans_file, ParentBased(ALWAYS_OFF) if unsampled else None)

    # stdio_client passes only HOME, LOGNAME, PATH, SHELL, TERM and USER (non-Windows) plus this env.
    env = None if no_env else {"OTEL_SPANS_FILE": spans_file}
    server = StdioServerParameters(command=sys.executable, args=[os.path.join(HERE, "server.py")], env=env)

    with tracer.start_as_current_span("agent.run") as root:
        ctx = root.get_span_context()
        print(f"agent trace id: {ctx.trace_id:032x} sampled={ctx.trace_flags.sampled}")
        async with stdio_client(server) as (read, write):
            async with ClientSession(read, write) as session:
                await session.initialize()
                if not fail:
                    await call_tool_traced(session, "get_weather", {"city": "Lisbon"})
                    return
                await call_tool_traced(session, "book_flight", {"destination": "Lisbon", "date": "2024-01-15"})
                await call_tool_traced(session, "cancel_flight", {"booking_id": "X1"})  # not a tool on this server
                await protocol_error(session, "flights/cancel", None)  # unknown method
                await protocol_error(session, "tools/call", {"arguments": {}})  # malformed: no tool name


if __name__ == "__main__":
    asyncio.run(main())

join.py, standard library only, groups the JSONL by trace id and prints each tree with name, kind, status and error.type. With —joined it asserts that agent.run and every tools/call server span share one trace id; read parent links from the printed tree.

"""Group a spans JSONL file by trace id and print each trace as a tree (stdlib only).

Usage: join.py SPANS_FILE [--joined]
--joined asserts that agent.run and every tools/call SERVER span share one trace id.
(notifications carry no _meta in mcp 2.3.0, so a notification's server span starts its own trace;
the check is scoped to the tool calls the agent makes.)
"""

import json
import sys
from collections import defaultdict


def main():
    path, joined = sys.argv[1], "--joined" in sys.argv
    try:
        with open(path, encoding="utf-8") as f:
            spans = [json.loads(line) for line in f if line.strip()]
    except FileNotFoundError:
        spans = []

    traces = defaultdict(list)
    for s in spans:
        traces[s["trace_id"]].append(s)
    print(f"{len(spans)} spans in {len(traces)} trace(s)")

    for trace_id, members in traces.items():
        print(f"trace {trace_id}")
        ids = {s["span_id"] for s in members}
        children = defaultdict(list)
        for s in members:
            # a parent outside this trace's spans (or none) makes the span a root here
            children[s["parent_id"] if s["parent_id"] in ids else None].append(s)

        def show(span, depth):
            err = span["attributes"].get("error.type")
            print(f"{'  ' * (depth + 1)}{span['name']}  [{span['kind']}, {span['service']}] "
                  f"status={span['status']}" + (f" error.type={err}" if err else ""))
            for child in children[span["span_id"]]:
                show(child, depth + 1)

        for root in children[None]:
            show(root, 0)

    if joined:
        agent = {s["trace_id"] for s in spans if s["name"] == "agent.run"}
        tools = {s["trace_id"] for s in spans if s["kind"] == "SERVER" and s["name"].startswith("tools/call")}
        assert agent and tools, f"missing spans: {len(agent)} agent.run trace(s), {len(tools)} tools/call server trace(s)"
        assert agent == tools, f"agent.run and tools/call server spans sit in {len(agent | tools)} different trace ids"
        print("OK: agent.run and every tools/call server span share one trace id")


if __name__ == "__main__":
    main()
: > spans_SDK.jsonl
python client_sdk.py spans_SDK.jsonl
python join.py spans_SDK.jsonl --joined

Table 1 lists six runs on mcp 2.3.0, opentelemetry-sdk 1.45.2 and stdio, tested end to end with synthetic data. On their 2025-11-25 handshake, notifications/initialized is its own root trace in every run with server spans (2026-07-28 drops that handshake).

RunClientWhat changedjoin.py summary linetools/call server span under agent.run
AHand-writtenNo params._meta sent4 spans in 4 trace(s)No
BHand-written—inject writes traceparent into _meta4 spans in 2 trace(s)Yes
SDKOfficial ClientSessionNothing, the SDK propagates9 spans in 2 trace(s)Yes
COfficial ClientSessionOTEL_SPANS_FILE left out of server env5 spans in 1 trace(s)No server span
DOfficial ClientSessionisError, unknown tool, unknown method, bad params14 spans in 2 trace(s)Yes
EOfficial ClientSessionRoot unsampled, ParentBased(ALWAYS_OFF)1 spans in 1 trace(s)No span recorded

Troubleshooting MCP tracing symptom by symptom

This matrix covers six MCP tracing symptoms: server spans in a separate trace, no server spans on stdio, tool errors that look like success, protocol errors mixed up with tool errors, a trace or server child dropped by sampling, and a second instrumentation stacked on mcp 2.x. Each row below names the cause, the check and the fix.

Start with one request: run join.py or your backend’s trace view, read the trace count and the client and server span status, then find the row. This MCP tracing troubleshooting matrix was observed with mcp 2.3.0 unless a row says source.

SymptomCauseCheckFix
Server spans in a separate traceClient sends no _metaParentless server span; join.py —joined failsUse the 2.x client or inject traceparent
Zero server spans on stdiostdio_client drops OTEL_* variablesClient spans only, tool call succeeds (run C)Pass them in StdioServerParameters env
Tool error looks like successisError true leaves client span UNSETServer span ERROR, error.type tool_error (run D)Mark the agent’s tool span on is_error
Protocol error vs tool errorUnknown tool is isError; bad requests are JSON-RPC errorstool_error vs a numeric code like -32601Alert on both; read error.type first
Trace or server child missing under samplingUnsampled root, or a non-parent-based server samplerRun E recorded no request spansRecord at the root; tail-sample in a collector
Third-party MCP instrumentation on mcp 2.xmcp 2.3.0 already creates and propagates spansSource: traceAI docs; Traceloop’s package tests mcp below 2Keep it for 1.x only

Running join.py on one request leads to five MCP tracing symptoms, each shown with its cause and the run that showed it, from a server span in another trace in run A to no request spans recorded in run E

Server spans in a separate trace

Runs A and B are the evidence: 4 traces without _meta, 2 with it. With no _meta and no current span, the server span is valid but parentless. Run B’s helper fixes hand-written clients and custom transports; on mcp 1.x, add a propagation instrumentation plus your own tracing.

Older 2.x clients sent an empty _meta that strict servers rejected (python-sdk issue 3473, closed). The 2.3.0 Python client drops an empty one instead, so upgrade the client before you blame a strict server for rejecting requests that carry one.

Zero server spans on stdio

Run C left OTEL_SPANS_FILE out of the env and printed “5 spans in 1 trace(s)”: client and agent spans only, no travel-mcp-server span, while get_weather still returned is_error=False. The server never saw the variable, so it recorded nothing.

$ : > spans_C.jsonl
$ python client_sdk.py spans_C.jsonl --no-env
$ python join.py spans_C.jsonl --joined
5 spans in 1 trace(s)
trace cd3feaaf940967dc9b0d19da50cb6a64
  agent.run  [INTERNAL, agent-sdk-client] status=UNSET
    MCP send initialize  [CLIENT, agent-sdk-client] status=UNSET
    execute_tool get_weather  [INTERNAL, agent-sdk-client] status=UNSET
      MCP send tools/call get_weather  [CLIENT, agent-sdk-client] status=UNSET
      MCP send tools/list  [CLIENT, agent-sdk-client] status=UNSET
AssertionError: missing spans: 1 agent.run trace(s), 0 tools/call server trace(s)
--- exit 1

On macOS and Linux, stdio_client’s default environment is HOME, LOGNAME, PATH, SHELL, TERM and USER, with your env merged over it; Windows has its own list of twelve (from source). OTEL_TRACES_SAMPLER and OTEL_EXPORTER_OTLP_* in the client’s shell are dropped too.

Tool errors that look like success

In run D, book_flight with a past date printed “book_flight: is_error=True content=‘Cannot book 2024-01-15: the date is in the past’”. The client span “MCP send tools/call book_flight” stayed UNSET; the server span was ERROR with error.type tool_error:

$ : > spans_D.jsonl
$ python client_sdk.py spans_D.jsonl --fail
Tool 'cancel_flight' failed: 'Unknown tool: cancel_flight'
agent trace id: 4ac66ecf528f4699a27d8d29ceb630ac sampled=True
book_flight: is_error=True content='Cannot book 2024-01-15: the date is in the past'
cancel_flight: is_error=True content='Unknown tool: cancel_flight'
flights/cancel None: JSON-RPC error code=-32601 message='Method not found'
tools/call {'arguments': {}}: JSON-RPC error code=-32602 message='Invalid request parameters'
--- exit 0
$ python join.py spans_D.jsonl --joined
14 spans in 2 trace(s)
trace 4ac66ecf528f4699a27d8d29ceb630ac
  agent.run  [INTERNAL, agent-sdk-client] status=UNSET
    MCP send initialize  [CLIENT, agent-sdk-client] status=UNSET
      initialize  [SERVER, travel-mcp-server] status=UNSET
    execute_tool book_flight  [INTERNAL, agent-sdk-client] status=ERROR error.type=tool_error
      MCP send tools/call book_flight  [CLIENT, agent-sdk-client] status=UNSET
        tools/call book_flight  [SERVER, travel-mcp-server] status=ERROR error.type=tool_error
    execute_tool cancel_flight  [INTERNAL, agent-sdk-client] status=ERROR error.type=tool_error
      MCP send tools/call cancel_flight  [CLIENT, agent-sdk-client] status=UNSET
        tools/call cancel_flight  [SERVER, travel-mcp-server] status=ERROR error.type=tool_error
    MCP send flights/cancel  [CLIENT, agent-sdk-client] status=ERROR error.type=-32601
      flights/cancel  [SERVER, travel-mcp-server] status=ERROR error.type=-32601
    MCP send tools/call  [CLIENT, agent-sdk-client] status=ERROR error.type=-32602
      tools/call  [SERVER, travel-mcp-server] status=ERROR error.type=-32602
trace a0fa1a0b4e5fa6fb0daf3c1e783a8de3
  notifications/initialized  [SERVER, travel-mcp-server] status=UNSET
OK: agent.run and every tools/call server span share one trace id
--- exit 0

The agent’s “execute_tool book_flight” span is ERROR only because of the 3-line helper below. The spec says clients SHOULD pass tool execution errors to the model for self-correction, so the result is right; only the span status needs help.

async def call_tool_traced(session, name, arguments):
    """The agent's own tool span. isError true is a normal result, so mark it here."""
    with tracer.start_as_current_span(f"execute_tool {name}") as span:
        result = await session.call_tool(name, arguments)
        if result.is_error:  # the 3-line client-side helper
            span.set_attribute("error.type", "tool_error")
            span.set_status(StatusCode.ERROR)
        print(f"{name}: is_error={result.is_error} content={result.content[0].text!r}")
        return result

Protocol errors versus tool execution errors

The spec lists an unknown tool as a protocol error, but as observed in 2.3.0, cancel_flight returned “is_error=True content=‘Unknown tool: cancel_flight’” and the server logged “Tool ‘cancel_flight’ failed” to stderr, with the server span ERROR tool_error and the client span UNSET.

The rule is in the MCP tools specification; python-sdk issue 3659, open as of 2026-11-25, tracks the gap.

async def protocol_error(session, method, params):
    """Send a raw request and print the JSON-RPC error code that comes back."""
    try:
        await session.send_request(types.Request(method=method, params=params), types.EmptyResult)
        print(f"{method} {params}: no error")
    except MCPError as e:
        print(f"{method} {params}: JSON-RPC error code={e.error.code} message={e.error.message!r}")

An unknown method returned “JSON-RPC error code=-32601 message=‘Method not found’”, and tools/call with no name returned “JSON-RPC error code=-32602 message=‘Invalid request parameters’”. Both the client and server spans were ERROR, with error.type and rpc.response.status_code set to the code.

Sampling that drops the server child

OpenTelemetry Python’s default sampler, parentbased_always_on, follows the parent. Run E made the client root ParentBased(ALWAYS_OFF) (“sampled=False”), and join.py found “1 spans in 1 trace(s)”, the parentless notifications/initialized, though the tool call succeeded: the server obeyed the flag.

$ : > spans_E.jsonl
$ python client_sdk.py spans_E.jsonl --unsampled
$ python join.py spans_E.jsonl --joined
1 spans in 1 trace(s)
trace e300e3cb3a101aefff6683cfe55b2ff6
  notifications/initialized  [SERVER, travel-mcp-server] status=UNSET
AssertionError: missing spans: 0 agent.run trace(s), 0 tools/call server trace(s)
--- exit 1

A server sampler that is not parent-based decides alone and can drop the child under a recorded parent (from source, not run). Record at the root with parent-based always-on in both processes, and move keep-or-drop to tail sampling in a collector, which decides on the spans received by decision_wait.

A second MCP instrumentation on mcp 2.x

mcp 2.3.0 already creates spans and propagates context. The traceAI docs say not to enable MCPInstrumentor on the 2.3 and newer native route, and Traceloop’s opentelemetry-instrumentation-mcp 0.63.1 tests only mcp below 2. No run here stacked one; keep such packages for 1.x.

Sending MCP traces to Future AGI with traceAI

On mcp 2.3 or newer, Future AGI uses MCP’s native spans. Each process exports them with a standard OpenTelemetry TracerProvider and an OTLP/HTTP exporter pointed at the Future AGI trace endpoint, so the agent’s LLM spans and the server’s tools/call spans land in one Future AGI project and one trace per request.

Each process sets resource attributes project_name and project_type “observe” (“service.name alone does not select a Future AGI project”), adds a BatchSpanProcessor with an OTLPSpanExporter posting to api.futureagi.com/tracer/v1/traces, with X-Api-Key and X-Secret-Key from FI_API_KEY and FI_SECRET_KEY, and calls trace.set_tracer_provider(provider). Our own pinned install line:

pip install mcp==2.3.0 opentelemetry-sdk==1.45.2 opentelemetry-exporter-otlp-proto-http==1.45.2

Native MCP spans are not model instrumentation, so “Instrument the model SDK separately”; LLM spans started while the agent span is current nest under it beside the MCP client span. On stdio, the docs client passes FI_API_KEY, FI_SECRET_KEY and OTEL_EXPORTER_OTLP_TRACES_ENDPOINT through StdioServerParameters env.

The docs say: “For a remote MCP server, configure tracing in the server process too. A client cannot export a server’s spans on its behalf.” The server span’s gen_ai.operation.name and gen_ai.tool.name let Future AGI classify the tool operation. Successful tool calls carry no arguments or results by default.

On this route, leave MCPInstrumentor off. FI_HIDE_INPUTS, FI_HIDE_OUTPUTS and FI_HIDE_ERROR_DETAILS do not control native MCP telemetry, so apply your Collector’s redaction policy to error details before export, as traceAI setup for MCP 2.x in Python explains.

mcp 1.x and TypeScript with traceAI-mcp

On mcp 1.x, traceAI-mcp 0.1.4 (MCPInstrumentor), and on the v1 TypeScript package @modelcontextprotocol/sdk, @traceai/mcp 0.1.3 (MCPInstrumentation.manuallyInstrument), carry W3C trace context in the request’s _meta across stdio, SSE and streamable HTTP. In Python, enable it in each process before importing the transport functions.

pip install traceAI-mcp==0.1.4 mcp==1.30.0
npm install @traceai/mcp@0.1.3

traceAI-mcp requires mcp>=1.30.0, so pin both to stay on 1.x. Neither package creates spans or configures a provider, so each process keeps its own provider and exporter, agent spans come from your framework’s instrumentation, and “A server needs its own tracing setup to produce server-side spans.”

See traceAI MCP context propagation for 1.x and TypeScript and traceAI on GitHub.

Following the failed booking from agent span to tool span

The failed booking from the opening becomes one readable trace once both processes export and the request carries its context. The agent’s execute_tool span shows ERROR with error.type tool_error, the server’s tools/call span sits two levels below it with the same error.type, and the complaint maps to one trace instead of two log searches.

    execute_tool book_flight  [INTERNAL, agent-sdk-client] status=ERROR error.type=tool_error
      MCP send tools/call book_flight  [CLIENT, agent-sdk-client] status=UNSET
        tools/call book_flight  [SERVER, travel-mcp-server] status=ERROR error.type=tool_error
  1. Copy otel_setup.py, server.py, client_sdk.py and join.py.
  2. Point client_sdk.py at your server command and rename the tools it calls.
  3. Use a fresh spans file for each CI run, then run join.py —joined to check that tool calls stay in the agent’s trace.

Then read how to evaluate MCP-connected agents in production for what to score.

Frequently Asked Questions

What is MCP tracing?

MCP tracing records each Model Context Protocol request as OpenTelemetry spans in both the agent and the MCP server, then links them with trace context. With mcp 2.3.0 in Python, a tool call appears as a client span in the agent and a server span in the tool process, inside the same trace.

Why do MCP client and server operations produce separate traces?

They run in separate processes with separate tracer providers, so the server joins the client's trace only when the request carries trace context in params._meta. A hand-written client, an mcp 1.x client without an instrumentation, or a missing _meta field makes each server span the root of a new trace.

How does trace context get from an MCP client to the server?

The client writes the W3C traceparent, plus tracestate or baggage when set, into the request's params._meta field, and the server extracts it as its span's parent. The MCP 2026-07-28 spec reserves those keys, and the Python SDK 2.3.0 injects and extracts them between two SDK processes.

Which OpenTelemetry instrumentation for MCP works in Python?

On mcp 2.3.0 you need no MCP instrumentation, because the SDK creates client and server spans and propagates context itself; install opentelemetry-sdk and an exporter. On mcp 1.x, add a propagation instrumentation such as traceAI-mcp, and create spans with your agent and server tracing in each process.

How do I set up MCP tracing in Python?

Give the client and the server their own TracerProvider and exporter, set each as the global provider, and pass the server's OpenTelemetry variables through StdioServerParameters env on stdio. Send server spans to a file, stderr or OTLP, because stdout carries the protocol, then check that tool calls share the agent's trace id.
Related Articles
View all