Skip to main content

07 - Debugging an MCP Server: Tracing Tool Calls and Telemetry

How to follow a call to an MCP tool: debugging in Claude Code, the stdout rule, traceparent in _meta and OpenTelemetry spans, tested on a server.

What do you think about this article?

07 - Debugging an MCP Server: Tracing Tool Calls and Telemetry
Claude Skills & MCPPhoto:Sanket MishraPexels

At a Glance

How to follow a call to an MCP tool: debugging in Claude Code, the stdout rule, traceparent in _meta and OpenTelemetry spans, tested on a server.

A call to an MCP tool fails, or takes thirty seconds, and from the outside all you see is that "the server does not respond". The possible causes sit in three different places: in the program that hosts the model (Claude Code, for example), in the messages travelling between the two, in the server. This article puts in order what to look at and with which tool, and shows with a real run how to get the identifier of a call from the client to the server, so that the logs of the two sides can be joined. The examples use the test warehouse server from the two previous articles, with no models and no open ports.

It comes after the distribution of skills with plugins: there you prepare what goes in, here you look at what runs. It assumes the MCP protocol in revision 2026-07-28, of which I only use the _meta fields here, and the TypeScript client with its timeouts. After observing the server, the last article covers automation around Claude Code events.

Where to look: three observation points

The Claude Code documentation on debugging your configuration starts from a simple fact: a server can be defined correctly and still provide no tools, and the /mcp command shows every configured server, its connection status and whether you have approved it for the project. A server that fails at startup appears as failed; relative paths in command or args are a frequent cause, because they are resolved against the folder you launched Claude Code from and not against the .mcp.json file. A server that is connected but has zero tools started the process without returning the list: the documentation suggests reconnecting from /mcp and, if that is not enough, starting claude --debug=mcp and reading the server's stderr in the debug log.

  • Host side: /mcp, the claude --debug=mcp log, the timeouts and the cap on response size.
  • On the wire: the JSON-RPC messages, which you read with a minimal client like the one in the third article.
  • Server side: stderr and traces, which can carry the identifier of whoever called.

It pays to proceed in this order, from the outermost to the innermost, because each level rules out a family of causes: if /mcp says "connected" the process starts; if a minimal client receives the right response the server works; only then is it worth looking inside the server. Jumping straight to the server code, when the problem is a timeout that is too short in the host, is the most common way to lose an hour.

The host's timeouts and limits

The Claude Code environment variables that concern MCP are documented with their default values, and knowing them avoids wrong diagnoses. I report them in a table, all from the environment variables page consulted on 13 November 2026.

VariableWhat it controlsValue if you do not set it
MCP_TIMEOUTWait for server startup, in milliseconds30000 (30 seconds)
MCP_TOOL_TIMEOUTWait for the execution of a tool, in milliseconds100000000 (about 28 hours); for HTTP and SSE servers and connectors each request times out after 60 seconds anyway, unless values greater than 60000
CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUTInterrupts a call if the server neither responds nor sends progress for this longper-transport values, according to the documentation (not reported here)
MAX_MCP_OUTPUT_TOKENSMaximum size of a tool response, in tokens25000, with a warning above 10000

The surprising figure is the second: the maximum execution time of a tool, if you do not set it, is about twenty-eight hours. A server stuck on a call therefore does not produce an error but a wait, and for an interface that has to answer a person it is indistinguishable from a failure. The remedy lies in two places: in the host, with an explicit MCP_TOOL_TIMEOUT value that reflects the slowest reasonable operation, and in the server, with a job that knows how to declare itself slow (this is why the protocol provides progress notifications). The cap on responses has a security side: a large response is also a way to bring a lot of untrusted text into the model's context.

Stdout belongs to the protocol: stderr is for logs

On the stdio transport the server writes protocol messages to stdout, one per line, and the specification is clear: the server must not write anything to stdout that is not a valid MCP message; it may write UTF-8 strings to stderr for any logging purpose, and the client should not assume that stderr indicates an error. A forgotten debug print on stdout is therefore a protocol failure, and it has a trait that makes it insidious: it depends on the buffer. The following server is the warehouse one with a single print, in three variants.

"""Same server, with a debug print on stdout: what you must not do on stdio."""
import sys

from mcp.server.mcpserver import MCPServer

MODO = sys.argv[1] if sys.argv[1:] else "buffer"
if MODO in ("buffer", "subito"):  # print before startup: "subito" flushes it, "buffer" does not
    print("starting the magazzino server", flush=(MODO == "subito"))

mcp = MCPServer("magazzino")


@mcp.tool()
def giacenza(sku: str) -> int:
    """Fictitious stock level."""
    if MODO == "dentro":  # print after startup, inside the tool
        print(f"looking up {sku}", flush=True)
    return 7


mcp.run("stdio")

The MODO variable chooses where the print falls. In the first two variants the text comes out before the server starts, in the first without flushing Python's buffer and in the second with flush=True; in the third the print sits inside the tool, so it runs during a call. The test script starts each variant, sends the requests one at a time and reads all of stdout, saying for each line whether it is a JSON-RPC message.

"""Reads the whole stdout of the server and says, line by line, whether it is a JSON-RPC message."""
import json
import subprocess
import sys

META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientInfo": {"name": "test", "version": "0"},
        "io.modelcontextprotocol/clientCapabilities": {}}
DISCOVER = {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": META}}
CHIAMATA = {"jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {"name": "giacenza", "arguments": {"sku": "VITE-M4"}, "_meta": META}}

PROVE = (("print before startup, buffered", ["server_rotto.py", "buffer"], [DISCOVER]),
         ("print before startup, with flush", ["server_rotto.py", "subito"], [DISCOVER]),
         ("print inside the tool", ["server_rotto.py", "dentro"], [DISCOVER, CHIAMATA]),
         ("server_traccia.py", ["server_traccia.py"], [DISCOVER]))



def classifica(numero, riga):
    try:
        json.loads(riga)
        return f"  line {numero}: valid JSON-RPC"
    except json.JSONDecodeError:
        return f"  line {numero}: NOT JSON: {riga.rstrip()!r}"


for etichetta, comando, richieste in PROVE:
    p = subprocess.Popen([sys.executable, *comando], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, text=True)
    righe = []
    for r in richieste:  # one request at a time: read until the response with the same id arrives
        p.stdin.write(json.dumps(r) + "\n")
        p.stdin.flush()
        while True:
            riga = p.stdout.readline()
            righe.append(riga)
            try:
                if json.loads(riga).get("id") == r["id"]:
                    break
            except json.JSONDecodeError:
                pass
    p.stdin.close()
    righe += p.stdout.read().splitlines(keepends=True)  # whatever arrives at close
    errore = p.stderr.read()
    p.wait(10)
    print(f"{etichetta}:")
    for numero, riga in enumerate(righe, start=1):
        print(classifica(numero, riga))
    if "looking up" in errore:
        print("  (the print text ended up on stderr)")

The central loop reads lines until the response with the same identifier as the request arrives: it is needed because the stray line can arrive before the response, and because whatever arrives afterwards, when the input is closed, still has to be counted. For each server the script prints, line by line, whether the content is valid JSON, and reports whether the print text ended up on stderr.

$ python prova_rotto.py
# Output:
# print before startup, buffered:
#   line 1: valid JSON-RPC
#   line 2: NOT JSON: 'starting the magazzino server'
# print before startup, with flush:
#   line 1: NOT JSON: 'starting the magazzino server'
#   line 2: valid JSON-RPC
# print inside the tool:
#   line 1: valid JSON-RPC
#   line 2: valid JSON-RPC
#   (the print text ended up on stderr)
# server_traccia.py:
#   line 1: valid JSON-RPC

The three cases are read together. With the buffer, the stray line arrives after the response: a client that reads one line at a time first receives the right message and then a read error, perhaps at close. With the flush it arrives first, and the connection fails immediately. In both cases the server is identical; only when the system empties the buffer changes, and so the symptom appears "sometimes". The print inside the tool, instead, breaks nothing: the text ends up on stderr.

The reason is in the source of the mcp 2.3.0 package (mcp/server/stdio.py): when the stdio server starts, the _claim_fd function moves descriptor 1 (stdout) onto stderr and serves the protocol from a private duplicate. Everything the program prints after startup is therefore safe; what it prints before, for example at module level, ends up on the protocol channel. This protection is a choice of that SDK version and not of the specification, which only prescribes that stdout contain valid messages: with another SDK or another version the result may be different. The last server, the one with traces, writes only valid messages.

Bringing the call identifier inside the server

The client's log and the server's log tell the story of the same call with different identifiers, and matching them by hand is slow. The specification in revision 2026-07-28 reserves for this purpose three keys of a request's _meta field: traceparent, tracestate and baggage, without the prefix that the other keys require, to remain compatible with existing implementations. When present, their values must follow the W3C Trace Context and W3C Baggage formats. The specification includes a non-normative example, which I use as is: a traceparent is made of version, trace identifier (32 hexadecimal digits), identifier of the caller's span (16 digits) and flags.

The OpenTelemetry semantic conventions for MCP, which have "Development" status (evolving, therefore not stable), ask whoever receives the request to extract the context from params._meta and use it as the remote parent of a span of kind SERVER, named {method} {target}, for example tools/call giacenza. The tool name goes in the span name and in the gen_ai.tool.name attribute; the arguments and the result are optional (opt-in) attributes, because they can contain sensitive data. If the response is a result with isError true, the error.type attribute must be tool_error.

The official Python SDK does all of this by itself: the source of mcp/server/_otel.py contains a middleware that wraps every message in a SERVER span, extracts the context from _meta and fills in the attributes just listed, and the base server enables it by default; it stays inert until you configure an OpenTelemetry exporter. To see it in action you only need the following versions, installed in a virtual environment outside the repository.

$ pip list | grep -E '^(mcp|opentelemetry-api|opentelemetry-sdk) '
# Output:
# mcp                                2.3.0
# opentelemetry-api                  1.45.2
# opentelemetry-sdk                  1.45.2

The test server configures an exporter that writes the spans to stderr as JSON lines, with two devices that exist only to make the article reproducible: progressive identifiers instead of random ones and no timestamps in the output. In production you would use the OTLP exporter of your collection system and random identifiers; I did not try that path.

"""Test MCP server with OpenTelemetry traces written to stderr (never to stdout)."""
import json
import sys

from mcp.server.mcpserver import Context, MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from opentelemetry.sdk.trace.id_generator import IdGenerator


class IdProgressivi(IdGenerator):
    """Predictable identifiers, only to make the output of the article reproducible."""

    def __init__(self):
        self._n = 0

    def generate_span_id(self):
        self._n += 1
        return 0xB000 + self._n

    def generate_trace_id(self):
        return 0xAAAA0000000000000000000000000001


class EsportatoreStderr(SpanExporter):
    def export(self, spans):
        for s in spans:
            riga = {
                "span": s.name,
                "kind": s.kind.name,
                "trace": format(s.context.trace_id, "032x"),
                "id": format(s.context.span_id, "016x"),
                "parent": format(s.parent.span_id, "016x") if s.parent else None,
                "status": s.status.status_code.name,
                "attributes": dict(sorted((s.attributes or {}).items())),
            }
            print(json.dumps(riga, ensure_ascii=False), file=sys.stderr, flush=True)
        return SpanExportResult.SUCCESS


provider = TracerProvider(id_generator=IdProgressivi())
provider.add_span_processor(SimpleSpanProcessor(EsportatoreStderr()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("magazzino")

GIACENZE = {"VITE-M4": 120, "DADO-M4": 0, "RONDELLA-M4": 560}
mcp = MCPServer("magazzino", instructions="Stock levels of a fasteners warehouse (test data).")


@mcp.tool()
def giacenza(sku: str) -> dict:
    """Returns the units available for an item code (sku)."""
    with tracer.start_as_current_span("stock lookup", attributes={"magazzino.sku": sku}):
        if sku not in GIACENZE:
            raise ToolError(f"unknown sku: {sku}")
        return {"sku": sku, "available": GIACENZE[sku]}


@mcp.tool()
async def con_log(sku: str, ctx: Context) -> str:
    """Tool that writes a log message for the request in progress."""
    await ctx.info(f"checking {sku}")
    return "done"


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

Three lines carry the weight. TracerProvider(id_generator=...) and trace.set_tracer_provider install the trace provider: from here on the SDK's middleware stops being inert. Inside giacenza, tracer.start_as_current_span("stock lookup") adds a manual child span, useful to see where the time goes inside the tool. The exporter writes to sys.stderr, never to stdout: the rule of the previous section. The con_log tool is for the per-request log level test, further down.

"""Client without an SDK: sends tools/call with traceparent in _meta and shows the traces the server writes to stderr."""
import json
import subprocess
import sys

VERSIONE = "2026-07-28"
META = {
    "io.modelcontextprotocol/protocolVersion": VERSIONE,
    "io.modelcontextprotocol/clientInfo": {"name": "test-client", "version": "0.1"},
    "io.modelcontextprotocol/clientCapabilities": {},
}
# non-normative example from the specification: trace id 0af7..., client span f067...
TRACEPARENT = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01"

PROVE = [
    ("with traceparent", "giacenza", {"sku": "VITE-M4"}, {"traceparent": TRACEPARENT}),
    ("with traceparent, error", "giacenza", {"sku": "XX"}, {"traceparent": TRACEPARENT}),
    ("without traceparent", "giacenza", {"sku": "DADO-M4"}, {}),
    ("malformed traceparent", "giacenza", {"sku": "DADO-M4"}, {"traceparent": "non-valido"}),
    ("without logLevel", "con_log", {"sku": "VITE-M4"}, {}),
    ("with logLevel debug", "con_log", {"sku": "VITE-M4"}, {"io.modelcontextprotocol/logLevel": "debug"}),
]

server = subprocess.Popen([sys.executable, "server_traccia.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE, text=True)
for numero, (etichetta, strumento, argomenti, extra) in enumerate(PROVE, start=1):
    richiesta = {"jsonrpc": "2.0", "id": numero, "method": "tools/call",
                 "params": {"name": strumento, "arguments": argomenti, "_meta": {**META, **extra}}}
    server.stdin.write(json.dumps(richiesta) + "\n")
    server.stdin.flush()
    messaggi = []
    while True:  # reads until the response with the same id: notifications may arrive first
        m = json.loads(server.stdout.readline())
        messaggi.append(m)
        if m.get("id") == numero:
            break
    notifiche = [m["params"]["data"] for m in messaggi if m.get("method") == "notifications/message"]
    esito = messaggi[-1].get("result", messaggi[-1].get("error"))
    print(f"{etichetta}: isError={esito.get('isError')} log notifications={notifiche}")
server.stdin.close()
server.wait(10)
print("--- traces written by the server on stderr ---")
server_stderr = server.stderr.read().splitlines()
for riga in server_stderr:
    if not riga.startswith("{"):  # library logs also end up on stderr: only the traces are needed here
        continue
    s = json.loads(riga)
    print(f"{s['span']:<28} {s['kind']:<8} trace={s['trace'][:8]} id={s['id'][-4:]} parent={(s['parent'] or '-')[-4:]} {s['status']}"
          + (f" error.type={s['attributes']['error.type']}" if "error.type" in s["attributes"] else ""))
primo = next(json.loads(r) for r in server_stderr if r.startswith("{") and '"kind": "SERVER"' in r)
print("attributes of the first SERVER span:", json.dumps(primo["attributes"], ensure_ascii=False))

The client is the raw one from the third article, without an SDK, with the addition of six tests: two calls with traceparent (one successful, one with an error), one without, one with a malformed value, and two calls to the tool that writes a message, with and without io.modelcontextprotocol/logLevel. The client reads the responses until it meets the one with its own identifier, because any log notifications arrive before the response. At the end it reads the server's stderr, keeping only the JSON lines: library messages end up there too, and the specification warns that stderr is not an error channel.

$ python client_traccia.py
# Output:
# with traceparent: isError=False log notifications=[]
# with traceparent, error: isError=True log notifications=[]
# without traceparent: isError=False log notifications=[]
# malformed traceparent: isError=False log notifications=[]
# without logLevel: isError=False log notifications=[]
# with logLevel debug: isError=False log notifications=['checking VITE-M4']
# --- traces written by the server on stderr ---
# stock lookup                 INTERNAL trace=0af76519 id=b002 parent=b001 UNSET
# tools/call giacenza          SERVER   trace=0af76519 id=b001 parent=02b7 UNSET
# stock lookup                 INTERNAL trace=0af76519 id=b004 parent=b003 ERROR
# tools/call giacenza          SERVER   trace=0af76519 id=b003 parent=02b7 ERROR error.type=tool_error
# stock lookup                 INTERNAL trace=aaaa0000 id=b006 parent=b005 UNSET
# tools/call giacenza          SERVER   trace=aaaa0000 id=b005 parent=- UNSET
# stock lookup                 INTERNAL trace=aaaa0000 id=b008 parent=b007 UNSET
# tools/call giacenza          SERVER   trace=aaaa0000 id=b007 parent=- UNSET
# tools/call con_log           SERVER   trace=aaaa0000 id=b009 parent=- UNSET
# tools/call con_log           SERVER   trace=aaaa0000 id=b00a parent=- UNSET
# attributes of the first SERVER span: {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "giacenza", "jsonrpc.request.id": "1", "mcp.method.name": "tools/call", "mcp.protocol.version": "2026-07-28"}

The result shows five things. First, propagation works: the spans of the first two calls carry the trace identifier the client sent (0af76519...), and the SERVER span has the client's span as its parent (02b7 are the last digits of its identifier). Second, the manual span stock lookup is a child of the SERVER span (b002 under b001): the hierarchy arises on its own. Third, the tool error marks the SERVER span as ERROR with error.type=tool_error, exactly as the convention describes. Fourth, without traceparent, or with a malformed value, the server does not fail: it opens a new trace, with no parent, and the call succeeds. Fifth, the log notification arrives only when the request carries the level: in the "without logLevel" test the list is empty, in the one with debug it contains the message, as the specification prescribes.

The last line of the output lists the attributes of the first SERVER span: mcp.method.name, mcp.protocol.version, jsonrpc.request.id, gen_ai.operation.name and gen_ai.tool.name. The arguments of the call (the SKU) are not there, and that is fine: the SKU of a warehouse is not a secret, but a customer identifier or free text could be, and the convention makes them optional precisely for this reason.

Per-request logging is deprecated

The part of the protocol that served logging, namely the notifications/message notifications with syslog-style levels, is declared deprecated in revision 2026-07-28: the specification says that new work should not adopt it and that existing work should migrate to stderr logging for stdio, or to OpenTelemetry for structured observability. It stays in the specification for at least twelve months after the revision before it can be removed. Whoever uses it still has a precise rule: the level is requested on every request with io.modelcontextprotocol/logLevel in _meta, and the server must not emit notifications for requests that do not carry it. The global level-setting command, which existed before, has been removed.

Claude Code's traces, and what I do not know

Claude Code exposes a trace of its own, in beta, that links every user request to the model calls and the tool executions. It is enabled with two variables together, CLAUDE_CODE_ENABLE_TELEMETRY=1 and CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1, plus OTEL_TRACES_EXPORTER to choose where to send the spans. By default the spans hide the request text, the tool details and the content, and you can include them by setting OTEL_LOG_USER_PROMPTS, OTEL_LOG_TOOL_DETAILS and OTEL_LOG_TOOL_CONTENT. When traces are active, HTTP requests to an MCP server carry the traceparent header, unless ANTHROPIC_BASE_URL points to an address other than Anthropic's (the documentation indicates CLAUDE_CODE_PROPAGATE_TRACEPARENT=1 to force it).

For a server on stdio, instead, I did not find a sentence in the documentation saying that Claude Code inserts traceparent into _meta: I do not assert it, and if you need it, verify it with your version, for example by reading what the server receives with an exporter like the one above. I also do not know how much time trace collection costs: I did not measure it, and for that reason I give no figures.

# SCHEMA TO ADAPT, NOT RUN: requires Claude Code installed and an MCP server configured

# 1. inside a session: status of each server (connected, failed, blocked by policy)
/mcp

# 2. start a session with the MCP server debug log; the server's stderr ends up in the log
claude --debug=mcp
#    the log is in ~/.claude/debug/<session-id>.txt

# 3. timeouts (milliseconds): server startup and execution of a tool
export MCP_TIMEOUT=60000
export MCP_TOOL_TIMEOUT=120000

# 4. Claude Code traces (beta): both variables are required
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1
export OTEL_TRACES_EXPORTER=console

The block gathers, in order of increasing cost, what I verified in the documentation and could not run. /mcp and --debug=mcp cost nothing and should be tried first; the two timeouts should be set before real use for the reasons in the table; the trace variables are for when you want to correlate several systems.

Symptoms and causes, from the sources

SymptomWhere to lookSource
The server shows as failed at startupRelative paths in command or args; MCP_TIMEOUT if startup is slowDebug your configuration; environment variables
Connected, but zero toolsReconnect from /mcp; then claude --debug=mcp and the stderr in the logDebug your configuration
The server has vanished from /mcpAn organization policy may have blocked it without signalingMCP management for organizations
The client gets intermittent read errorsSomething writes to the server's stdout outside the protocol, before startupSpecification, stdio transport; test in this article
The call seems never to finishMCP_TOOL_TIMEOUT (default about 28 hours) and, for remote servers, the per-request limitEnvironment variables

The table is not a list of everything that can go wrong: these are the cases for which I have a source or a test. For any other symptom the sequence of the three observation points, from the outside in, remains the method.

Frequently asked questions

Do I need OpenTelemetry or are stderr logs enough?

For a stdio server running on your machine, stderr is enough to begin with, and it is exactly what the specification indicates as the alternative to protocol logging. OpenTelemetry is needed when you have to link what happens across several processes, for example the client, the server and a service the server calls: the traceparent is what lets you join the pieces.

How do I avoid putting sensitive data in traces?

Do not record tool arguments and results by default: the conventions define them as optional for this reason, and the logging specification forbids credentials, personal data and internal details an attacker could exploit. If you need an attribute for debugging, turn it on for as long as necessary and turn it off.

Can the server trust the traceparent it receives?

Like any other incoming data: no. A malicious caller can send an identifier of their choosing, and in your collection systems the trace would appear attached to another one. To attribute an abuse you need authentication and access control, not the trace identifier, which is for correlation.

What you can do now

You can choose where to start when an MCP call goes wrong, you know the host's timeouts and limits with their default values, you know why the server's stdout is reserved for the protocol and how a print breaks it, and you have seen with a real run how a trace identifier passes from _meta to the server, when the status becomes an error and why the log level has to be requested on every request. In the next article, which closes the series, I move on to Claude Code hooks, the part that runs commands in response to events.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects