OpenTelemetry Tracing for a Claude Agent Loop: A Span for Every Request and Tool Call, and the Switch for Each Surface
A log line that says 'calls 3' can't tell you which request used the tokens. Trace a SupportDesk agent loop so ticket T-103 becomes one trace with a span per request and tool call (705 tokens in, summed from 140, 235 and 330), then learn which switch turns tracing on for the Messages API, the Claude API itself, the Agent SDK and Claude Code.
What you will learn
- Build one trace per agent run: a run span you open, a request span the SDK makes, and a tool span you open
- Nest spans correctly by registering the tracer provider first and calling the SDK inside the run span
- Tell SDK tracing, API tracing and the Claude Code / Agent SDK environment variables apart, and know which switch each surface needs
- Read token usage from request spans, keep content off by default, and count each token from one source only
Before you start
- Claude tool use: tool_use and tool_result
- Observability and tracing for LLM apps
A SupportDesk agent has just finished ticket T-103. The customer says it was slow, and the bill is up. The only record you have is a log line that says the agent made three calls.
Which request used the tokens? Which tool call was slow? Which turn went wrong? The log line can't say. It counts the calls, not the steps. In this article we give every model request and every tool call its own span, so one run becomes one trace. Then we look at the official tracing Claude ships (in beta) and the switch that turns it on for each way you run Claude.
If spans and traces are new to you, start with observability and tracing for LLM apps. This article is the Claude-specific part: the agent loop, the SDK's own spans, and the Claude Code and Agent SDK telemetry.
A parcel with a tracking number
Think of a parcel. One tracking number ties every scan to the same journey: that's a trace. Each scan, at the depot, on the van, at the door, has a start, an end and some notes: that's a span. And scans sit inside scans. The van trip sits inside the whole journey, so a child span belongs to a parent.
One run of the agent is one journey. Follow it, and you see every stop.
Who makes which span
- The SDK makes the request spans. For each model request it opens a span named
anthropic.messages.create. You write no code for that, once a tracer provider is registered. - You make the rest. One span for the whole run, and one for each tool call. The SDK can't see a tool that your own loop runs.
- The request carries the trace in a
traceparentheader, so the API's own span can join the same trace.
The project runs on a stand-in model (the Anthropic SDK on an httpx mock transport), so no API key is needed, the replies are test replies, and the token counts are made up for the demo.
tracing.py: register the provider first
"""Tracing setup: where finished spans go. Here: in memory.
In production, swap in an OTLP exporter that sends them to
your trace backend."""
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter)
import report
EXPORTER = InMemorySpanExporter()
REQUEST = "anthropic.messages.create"
def setup():
"""Register the provider before the first model call."""
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(EXPORTER))
trace.set_tracer_provider(provider)
def show(spans):
"""Print a trace as a tree, each span under its parent."""
spans = sorted(spans, key=lambda s: s.start_time)
requests = [s for s in spans if s.name == REQUEST]
depth = {}
for s in spans:
parent = s.parent.span_id if s.parent else None
d = depth[s.context.span_id] = depth.get(parent, -1) + 1
pad, text = 34 - 2 * d, report.detail(s, requests)
print(f'{" " * d}{s.name:<{pad}}{text}')
The tracer provider creates spans, and finished spans go to an exporter. Here that's memory; in production it's an exporter that sends them to your trace backend. The order matters: register the provider before the first model call, or the SDK makes no spans at all.
agent.py: a run span and a tool span
This is the same tool-use loop you already know, with two with blocks added. An excerpt:
tracer = trace.get_tracer("supportdesk")
def run(ticket_id, question, client):
messages = [{"role": "user", "content": question}]
tools_used = []
name = "invoke_agent supportdesk"
with tracer.start_as_current_span(name) as span:
span.set_attribute("gen_ai.operation.name", "invoke_agent")
span.set_attribute("supportdesk.ticket.id", ticket_id)
for call in range(1, MAX_CALLS + 1):
response = client.messages.create(
model=MODEL, max_tokens=512, system=SYSTEM,
tools=TOOLS, messages=messages)
if response.stop_reason != "tool_use":
text = "".join(b.text for b in response.content
if b.type == "text")
return {"text": text, "tools_used": tools_used,
"calls": call}
messages.append({"role": "assistant",
"content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
output = run_tool(block)
tools_used.append(block.name)
results.append({"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(output)})
messages.append({"role": "user", "content": results})
raise RuntimeError("the agent used up its calls")
def run_tool(block):
"""One span around one tool call."""
name = f"execute_tool {block.name}"
with tracer.start_as_current_span(name) as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", block.name)
span.set_attribute("gen_ai.tool.call.id", block.id)
return RUNNERS[block.name](**block.input)
- One run span goes around the whole loop and carries our own ticket id.
client.messages.createis called inside it, so the SDK's request span nests under the run.- Each tool call gets its own tool span, with the tool name and the call id from the model's
tool_useblock.
Three tickets, three traces
T-101 looks up a customer, T-102 searches the help centre, and T-103 looks up a customer and then sends an email. Here is what python run_all.py printed:
T-101 | tools: lookup_customer | calls 2
invoke_agent supportdesk ticket T-101 | in 375 out 66
anthropic.messages.create tool_use | in 140 out 40
execute_tool lookup_customer call toolu_test_1
anthropic.messages.create end_turn | in 235 out 26
T-102 | tools: search_help | calls 2
invoke_agent supportdesk ticket T-102 | in 375 out 66
anthropic.messages.create tool_use | in 140 out 40
execute_tool search_help call toolu_test_1
anthropic.messages.create end_turn | in 235 out 26
T-103 | tools: lookup_customer, send_email | calls 3
invoke_agent supportdesk ticket T-103 | in 705 out 106
anthropic.messages.create tool_use | in 140 out 40
execute_tool lookup_customer call toolu_test_1
anthropic.messages.create tool_use | in 235 out 40
execute_tool send_email call toolu_test_2
anthropic.messages.create end_turn | in 330 out 26
outbox: 1 email to carla@example.com
Read T-103. The input tokens grow every turn, 140, 235, 330, because the tool results go back in with each request. The run's 705 tokens in is just the sum of its three requests, and now you can see which request spent the most: the last one. The tool spans sit between the requests, so a slow lookup would show up as its own line instead of hiding inside a model number.
What a span carries
| Span | Made by | Carries |
|---|---|---|
Run, invoke_agent supportdesk | You | Your ticket id. No usage of its own: add up the requests below it. |
Request, anthropic.messages.create | The SDK | Stop reason, input and output tokens |
Tool, execute_tool <name> | You | Tool name and call id |
By default the SDK leaves prompts and replies out of its spans. That setting is called metadata only. The numbers tell you where the tokens went; content stays off until you switch it on.
When spans stand alone
- Register the provider after the first call, and the SDK makes no spans at all.
- Call the model outside any span, and the request span has no parent, so it floats in its own trace.
The fix for both: register the provider first, and call the SDK inside the run span. A span nests only when it's opened while its parent is current.
The official tracing, surface by surface
Claude now has official OpenTelemetry tracing. It's in beta, and it covers more than one product, so the on-call engineer's real question is: which switch turns tracing on, for which surface? SupportDesk runs Claude three ways:
| How you run Claude | Who runs the loop | Switch |
|---|---|---|
| A Messages API app | Your code | SDK tracing, plus API tracing |
| The Agent SDK and Claude Code | The Claude Code CLI | Environment variables |
| A Managed Agents session | The API | API tracing (plus SDK tracing for your own calls) |
Two cameras, one parcel
Picture two cameras watching the same parcel. One sits in your own depot and sees the parcel leave: that's the SDK span, kind CLIENT. The other sits at the courier's hub and sees it arrive: that's the API span, kind SERVER. The tracking number riding on the parcel is the traceparent header, and it puts both views on one timeline.
SDK tracing on the tool runner
The second project runs the same agent on the SDK's tool runner, with the console exporter. Tools go through the runner, so the SDK traces them too. We set one conversation id per ticket, and add one span of our own around the whole ticket. An excerpt from agent.py:
def run(ticket_id, question, client):
# one conversation id for every span of this ticket
traced = client.with_options(open_telemetry={
**client.open_telemetry, "conversation_id": ticket_id})
tools_used, calls, text = [], 0, ""
with tracer.start_as_current_span("answer_ticket"):
runner = traced.beta.messages.tool_runner(
model=MODEL, max_tokens=512, system=SYSTEM,
tools=[lookup_customer, send_email, search_help],
messages=[{"role": "user", "content": question}])
for message in runner:
calls += 1
tools_used += [b.name for b in message.content
if b.type == "tool_use"]
text = "".join(b.text for b in message.content
if b.type == "text")
return {"text": text, "tools_used": tools_used, "calls": calls}
The console exporter prints each span as it ends, so children come first and parents print last:
SDK tracing, console exporter, ticket T-103
anthropic.messages.create CLIENT in 140 out 40
anthropic.custom_tool_use lookup_customer INTERNAL toolu_test_1
anthropic.messages.create CLIENT in 235 out 40
anthropic.custom_tool_use send_email INTERNAL toolu_test_2
anthropic.messages.create CLIENT in 330 out 26
anthropic.messages.tool_runner INTERNAL
answer_ticket INTERNAL
-- T-103 | tools: lookup_customer, send_email | calls 3
content mode: metadata_only
Seven spans this time. Each model request is a CLIENT span with its usage, each tool use has its own span named for the tool, then the tool runner span, then our answer_ticket. The content mode is metadata_only, the default, so no prompts are in these spans.
The Agent SDK and Claude Code: the environment is the switch
The Agent SDK runs the Claude Code command line tool as a child process, and that tool exports the telemetry. So you don't register a provider; you pass an environment. From agent_sdk_env.py:
from urllib.parse import quote
def otel_env(service, tenant, exporter="otlp"):
if exporter == "console":
# console writes to stdout, which the SDK uses for its messages
raise ValueError("use otlp with the Agent SDK, not console")
return {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"CLAUDE_CODE_ENHANCED_TELEMETRY_BETA": "1", # traces are beta
"OTEL_TRACES_EXPORTER": exporter,
"OTEL_METRICS_EXPORTER": exporter,
"OTEL_LOGS_EXPORTER": exporter,
"OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf",
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4318",
"OTEL_SERVICE_NAME": service,
"OTEL_RESOURCE_ATTRIBUTES":
f"deployment.environment=production,tenant.id={quote(tenant)}",
}
Agent SDK and Claude Code environment
CLAUDE_CODE_ENABLE_TELEMETRY=1
CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1
OTEL_TRACES_EXPORTER=otlp
OTEL_METRICS_EXPORTER=otlp
OTEL_LOGS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.example.com:4318
OTEL_SERVICE_NAME=supportdesk-agent
OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production,tenant.id=acme
rejected: use otlp with the Agent SDK, not console
Nothing runs here; this part only prints the configuration. Telemetry stays off until CLAUDE_CODE_ENABLE_TELEMETRY is 1. Traces are beta, so they need the extra CLAUDE_CODE_ENHANCED_TELEMETRY_BETA flag; metrics and log events don't. There's one exporter per signal, and a service name so you can filter by agent. The console exporter is refused on purpose: standard output is the SDK's message channel.
Span names on the other surfaces
- Claude Code and the Agent SDK use a
claude_codeprefix:claude_code.interactionwraps one turn, withclaude_code.llm_requestandclaude_code.toolunder it. A tool span has two children,claude_code.tool.blocked_on_user(waiting for you) andclaude_code.tool.execution. - A Managed Agents session has an
anthropic.session.turnspan per agent turn, withanthropic.model_requestand the tools the API runs (for exampleanthropic.tool_use bash) inside it. - A session can span several traces, so group by
anthropic.session.id, or bygen_ai.conversation.idfor one thread. - Count each token once. Sum one source only, the client spans or the API spans, never both.
Content modes
Metadata only is the default: ids, timing, status, token counts, and the names of your tools and agents. Full content adds the prompts and responses in gen_ai.input.messages and gen_ai.output.messages; in the SDK you set it with traces.content_mode. A conversation id goes out in both modes, so keep personal data out of it, and a user id travels as baggage, so use an opaque id, never an email address. With zero data retention, the API holds content in memory only until delivery.
Common mistakes
- Logging one token total per run. It hides which request used the tokens.
- A timing line in each component. Nothing links the lines into one run.
- Capturing every prompt in every span. A privacy cost, and still no structure.
- Registering the provider late, or calling the SDK outside the run span. No spans, or spans with no parent.
- Expecting full content to add the model runs. It adds prompts. If a Messages API app shows its own SDK spans but the model runs are missing, the switch is API tracing in the Console, next to SDK tracing.
- Summing client and API spans together. Every token gets counted twice.
- Forgetting it's beta. Names and attributes can change between releases, so pin your versions.
Quick recap
| Piece | Where it comes from |
|---|---|
| Run span | You open it around the loop |
| Request span | The SDK, once a tracer provider is registered |
| Tool span | You open it around each tool call (the tool runner does it for you) |
| Model runs, server tools, Managed Agents turns | API tracing, a Console destination, admin permission |
| Claude Code and the Agent SDK | Environment variables, OTLP exporter, beta flag for traces |
| Content | Off by default (metadata only); opt in with traces.content_mode |
Try it yourself
Move tracing.setup() in run_all.py below the first ticket and run again. How many spans does T-101 get now? Then call client.messages.create once outside the run span and look at where its span lands in the printed tree.
Related course on Udemy
Claude Certified Developer - Professional (CCDV-P) Exam Prep
Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
