AI Agent Observability with OpenTelemetry: Tracing LLM Calls, Tools and MCP
An agent that “worked” can still have called the wrong tool three times, burned 400k tokens and answered from a stale cache. Here is how to see that: one trace per agent run, built on the OpenTelemetry GenAI semantic conventions that just had their first standalone release, with MCP calls stitched into the same trace.
Dmytro Vavreniuk
Product Engineer
Short version: treat each agent run as one trace: an invoke_agent root span, a chat span per model call with token and cache counts, and an execute_tool span per tool call. For MCP, inject traceparent into params._meta so the server’s spans join the same trace. Keep prompt content off by default (OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT=NO_CONTENT), tail-sample so every failed, slow or huge run is kept, and compute cost per run from tokens and a price table you own. The conventions reached v0.1.0 on 21 November 2026 with breaking metric renames, so pin versions and check your dashboards.
Our post on debugging production with an AI agent was about agents reading your telemetry. This one is the other direction: the agent is the production system, and you need telemetry about it. The building blocks are the same ones we use for normal services in our structured logging guide and our end-to-end tracing guide: OpenTelemetry spans, shared attribute names and IDs that connect everything.
Why agent observability is suddenly everywhere
The pattern is clear: every observability vendor now has an “agent” product, and the thing that lets you avoid lock-in is a shared vocabulary. If your spans follow the GenAI conventions, the same traces can go to Grafana, Datadog, Langfuse, Snowflake or your own ClickHouse, and you can switch later without re-instrumenting.
What an agent trace looks like
Here is one run of a support agent that looks up an order through an MCP server and then answers. Every line is a span; the names and attributes come straight from the conventions.
invoke_agent support-agent INTERNAL gen_ai.operation.name=invoke_agent
│ gen_ai.agent.name=support-agent
│ gen_ai.conversation.id=conv_8f2c...
├── chat claude-sonnet-5-5 CLIENT gen_ai.usage.input_tokens=14210
│ gen_ai.usage.cache_read.input_tokens=12800
│ gen_ai.response.finish_reasons=[tool_use]
├── execute_tool lookup_order INTERNAL gen_ai.tool.name=lookup_order
│ └── tools/call lookup_order CLIENT mcp.method.name=tools/call mcp.session.id=191c...
│ └── tools/call lookup_order SERVER (orders MCP server, parent taken from params._meta)
│ └── SELECT orders CLIENT db.system.name=postgresql
├── chat claude-sonnet-5-5 CLIENT gen_ai.usage.output_tokens=412
└── (agent span ends: 2 inference calls, 1 tool call, 6.8 s)Three things make this useful. The root span gives you one row per run, so “how many runs failed today” is a simple query. The inference spans carry tokens, so cost is a sum, not a guess. And because the MCP server continued the trace, the slow Postgres query inside the tool shows up under the agent run that triggered it, not as an orphan trace in another service.
The span types you will use
| Operation | Span name | Kind | Use it for |
|---|---|---|---|
invoke_agent | invoke_agent {gen_ai.agent.name} | INTERNAL (in-process) or CLIENT (remote agent) | One agent run from user request to final answer. The root of your agent trace. |
chat / generate_content / text_completion | {gen_ai.operation.name} {gen_ai.request.model} | CLIENT | One model call. Carries model, tokens, cache usage, finish reasons. |
execute_tool | execute_tool {gen_ai.tool.name} | INTERNAL | One tool execution decided by the model, including agent-as-a-tool and skill loading. |
MCP client / server | {mcp.method.name} {target}, e.g. tools/call get-weather | CLIENT / SERVER | The JSON-RPC call to an MCP server. Merged into execute_tool when outer GenAI instrumentation already traces the tool. |
plan | plan {gen_ai.agent.name} | INTERNAL | Planning or task decomposition step (new in v0.1.0). |
create_agent | create_agent {gen_ai.agent.name} | CLIENT | Creating a remote agent (OpenAI Assistants, Bedrock Agents, Azure AI Foundry). |
retrieval / embeddings | retrieval, embeddings {model} | INTERNAL / CLIENT | RAG lookups and embedding calls. |
The attributes that matter
The full registry has hundreds of entries. These are the ones that answer real questions; get them right before anything else.
| Attribute | On | Why it matters |
|---|---|---|
gen_ai.operation.name | Every GenAI span | Lets you group by step type without parsing span names. |
gen_ai.provider.name | Inference spans | anthropic, openai, aws.bedrock, gcp.vertex_ai… Needed for cost lookups. No longer required on the internal invoke_agent span. |
gen_ai.request.model / gen_ai.response.model | Inference spans | The response model is what you were billed for (aliases resolve to dated versions). |
gen_ai.usage.input_tokens / output_tokens | Inference spans | input_tokens SHOULD include cached tokens and all modalities, so for providers that report cached tokens separately you add them up. |
gen_ai.usage.cache_read.input_tokens / cache_write.input_tokens | Inference spans | Cache reads are billed at a fraction of the input price, so cost is wrong without them. cache_write replaces cache_creation in v0.1.0. |
gen_ai.agent.name | Agent, tool and plan spans | Your main grouping key for dashboards. Marked sampling-relevant. |
gen_ai.conversation.id | Agent, inference and tool spans | Ties all runs of one conversation together. Use the real thread or session ID, not the trace ID. |
gen_ai.tool.name / gen_ai.tool.call.id | execute_tool, MCP spans | Which tool and which call. tool.call.id is required only when the provider supplied one. |
error.type | Any failed operation | Low-cardinality failure class: timeout, rate_limited, a JSON-RPC code, an exception type. |
One trap worth calling out: the spec says gen_ai.usage.input_tokens SHOULD include cached tokens, but some providers (Anthropic, for example) report uncached input, cache reads and cache writes as separate numbers. If you copy the provider’s input_tokens field as-is, your cost and cache-hit dashboards will be wrong in opposite directions.
What changed in v0.1.0 (21 November 2026)
The GenAI conventions were deprecated in the main semantic-conventions repo in mid-2026 and moved to open-telemetry/semantic-conventions-genai. Its first release lists every change since semantic-conventions v1.41.0. If you built dashboards on earlier names, these are the ones that will break:
| Before | In v0.1.0 |
|---|---|
gen_ai.client.token.usage + gen_ai.token.type | gen_ai.client.inference.operation.input_tokens and …output_tokens histograms, plus gen_ai.client.inference.usage.* counters |
gen_ai.client.operation.duration for everything | gen_ai.client.inference.duration, gen_ai.client.embeddings.duration, gen_ai.client.invoke_agent.duration, gen_ai.invoke_agent.duration, gen_ai.execute_tool.duration |
gen_ai.usage.cache_creation.input_tokens | gen_ai.usage.cache_write.input_tokens |
Separate invoke_workflow span with gen_ai.workflow.name | Internal invoke_agent span with gen_ai.agent.name; gen_ai.operation.name stays invoke_workflow |
rpc.response.status_code on MCP spans | rpc.status_code |
gen_ai.provider.name = mistral_ai | mistral |
JSON strings allowed for structured attributes on spans | Structured values required (no JSON-string fallback) |
OTEL_SEMCONV_STABILITY_OPT_IN transition guidance for v1.36.0 and earlier | Removed. Newer instrumentations emit the latest conventions; check each library’s docs |
The release also adds things you will want: a plan operation, gen_ai.invoke_agent.inference_calls and gen_ai.invoke_agent.tool_calls metrics (great for loop detection), gen_ai.conversation.compacted for context compaction, gen_ai.skill.* attributes for Agent Skills, memory operation spans, per-modality token counts, A2A protocol spans, and *_ref attributes that point to content stored outside your telemetry. Full list in the changelog.
Practical advice: libraries will adopt v0.1.0 at different speeds, so for a few months you will receive both old and new names. Write dashboard queries that accept both (for example, gen_ai.client.token.usage OR the new input/output histograms), and pin instrumentation versions so names do not change under you on a routine dependency bump.
Step 1: instrument the agent
Python: zero-code with the GenAI instrumentations
The OpenTelemetry Python GenAI instrumentations cover the major SDKs and several agent frameworks, and the spec repo keeps a conformance report per library showing which spans each one emits. For an app using the OpenAI SDK:
pip install opentelemetry-distro opentelemetry-exporter-otlp \
opentelemetry-instrumentation-openai-v2
export OTEL_SERVICE_NAME=support-agent
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# Content stays off by default. Turn it on only where you are allowed to store prompts.
export OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT=NO_CONTENT # or SPAN_ONLY / EVENT_ONLY / SPAN_AND_EVENT
opentelemetry-instrument python agent.pyAuto-instrumentation gives you inference spans. It usually does not know where an agent run starts and ends in your code, so you still add the invoke_agent span yourself, or use a framework (OpenAI Agents SDK, LangChain, Pydantic AI, Google ADK, CrewAI) whose instrumentation creates it.
TypeScript: a hand-rolled agent loop
If you wrote your own loop, manual spans are short and give you full control. This is a complete tool-use loop with the Anthropic SDK; the same shape works for any provider.
import Anthropic from '@anthropic-ai/sdk';
import { trace, SpanKind, SpanStatusCode, type Span } from '@opentelemetry/api';
const tracer = trace.getTracer('support-agent', '1.4.0');
const client = new Anthropic();
const MODEL = 'claude-sonnet-5-5';
const MAX_STEPS = 8;
function fail(span: Span, err: unknown, type: string) {
span.recordException(err as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
span.setAttribute('error.type', type);
}
export function runAgent(conversationId: string, userMessage: string) {
return tracer.startActiveSpan('invoke_agent support-agent', {
kind: SpanKind.INTERNAL,
attributes: {
'gen_ai.operation.name': 'invoke_agent',
'gen_ai.agent.name': 'support-agent',
'gen_ai.conversation.id': conversationId,
},
}, async (agentSpan) => {
try {
const messages: Anthropic.MessageParam[] = [{ role: 'user', content: userMessage }];
for (let step = 0; step < MAX_STEPS; step++) {
const res = await chat(messages);
messages.push({ role: 'assistant', content: res.content });
const calls = res.content.filter((b) => b.type === 'tool_use');
if (calls.length === 0) return res;
const results = await Promise.all(calls.map(executeTool));
messages.push({ role: 'user', content: results });
}
throw new Error('agent exceeded ' + MAX_STEPS + ' steps');
} catch (err) {
fail(agentSpan, err, 'max_steps_exceeded');
throw err;
} finally {
agentSpan.end();
}
});
}
function chat(messages: Anthropic.MessageParam[]) {
return tracer.startActiveSpan('chat ' + MODEL, {
kind: SpanKind.CLIENT,
attributes: {
'gen_ai.operation.name': 'chat',
'gen_ai.provider.name': 'anthropic',
'gen_ai.request.model': MODEL,
'gen_ai.request.max_tokens': 2048,
},
}, async (span) => {
try {
const res = await client.messages.create({ model: MODEL, max_tokens: 2048, messages, tools });
const u = res.usage;
const cacheRead = u.cache_read_input_tokens ?? 0;
const cacheWrite = u.cache_creation_input_tokens ?? 0;
span.setAttributes({
'gen_ai.response.id': res.id,
'gen_ai.response.model': res.model,
'gen_ai.response.finish_reasons': [res.stop_reason ?? 'unknown'],
// The convention counts cached tokens inside input_tokens; Anthropic reports them separately.
'gen_ai.usage.input_tokens': u.input_tokens + cacheRead + cacheWrite,
'gen_ai.usage.cache_read.input_tokens': cacheRead,
'gen_ai.usage.cache_write.input_tokens': cacheWrite,
'gen_ai.usage.output_tokens': u.output_tokens,
});
return res;
} catch (err) {
fail(span, err, (err as { status?: number }).status === 429 ? 'rate_limited' : 'provider_error');
throw err;
} finally {
span.end();
}
});
}
function executeTool(call: Anthropic.ToolUseBlock) {
return tracer.startActiveSpan('execute_tool ' + call.name, {
kind: SpanKind.INTERNAL,
attributes: {
'gen_ai.operation.name': 'execute_tool',
'gen_ai.tool.name': call.name,
'gen_ai.tool.call.id': call.id,
'gen_ai.tool.type': 'function',
},
}, async (span): Promise<Anthropic.ToolResultBlockParam> => {
try {
const output = await callMcpTool(call.name, call.input as Record<string, unknown>);
return { type: 'tool_result', tool_use_id: call.id, content: JSON.stringify(output) };
} catch (err) {
fail(span, err, 'tool_error');
return { type: 'tool_result', tool_use_id: call.id, content: String(err), is_error: true };
} finally {
span.end();
}
});
}Note the two places errors are recorded. A tool that throws marks its execute_tool span as failed but still returns an error result to the model, because that is what the model sees. An agent that hits MAX_STEPS fails the root span. Those are the two failure modes you most want to count separately.
Step 2: trace MCP calls end to end
HTTP trace headers are not enough for MCP. One Streamable HTTP connection can carry many MCP requests, stdio has no headers at all, and a retried request can span several HTTP calls. The MCP conventions therefore put the W3C trace context inside the message itself, in the params._meta property bag, with unprefixed traceparent, tracestate and baggage keys (as defined by MCP’s SEP-414). The server uses it as the parent and links the transport context if there is one.
import { context, propagation } from '@opentelemetry/api';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
// Client side: put W3C trace context into params._meta (keys unprefixed, per SEP-414)
export async function callMcpTool(name: string, args: Record<string, unknown>) {
const meta: Record<string, string> = {};
propagation.inject(context.active(), meta); // adds traceparent, tracestate, baggage
return mcp.callTool({ name, arguments: args, _meta: meta });
}import { context, propagation, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
const tracer = trace.getTracer('orders-mcp-server');
// Server side: continue the caller's trace instead of starting a new one
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
const parent = propagation.extract(context.active(), req.params._meta ?? {});
return context.with(parent, () =>
tracer.startActiveSpan('tools/call ' + req.params.name, {
kind: SpanKind.SERVER,
attributes: {
'mcp.method.name': 'tools/call',
'gen_ai.operation.name': 'execute_tool',
'gen_ai.tool.name': req.params.name,
'jsonrpc.request.id': String(extra.requestId),
'mcp.session.id': extra.sessionId ?? '',
'mcp.protocol.version': '2025-11-25',
'network.transport': 'tcp', // 'pipe' for stdio servers
},
}, async (span) => {
try {
const result = await tools[req.params.name](req.params.arguments ?? {});
if (result.isError) span.setAttribute('error.type', 'tool_error');
return result;
} catch (err) {
span.recordException(err as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
throw err;
} finally {
span.end();
}
}));
});Two rules from the spec keep traces clean. If your agent framework already creates an execute_tool span for the call, the MCP client instrumentation should add its mcp.* attributes to that span rather than nest a duplicate. And the MCP server should only report its own failures as errors; a client sending bad arguments is a client-side error, while the client span reports every JSON-RPC error code. That split tells you whether to fix the agent’s prompt or the server.
The same trace context also makes MCP servers auditable: every database query or API call a tool makes is now attributable to an agent run and a conversation. If you expose your own product data over MCP, as in our MCP server for session data post, add this from day one.
Step 3: decide what content you are allowed to keep
Prompts, completions, system instructions, tool arguments and tool results are the most useful data in an agent trace and the most dangerous. They routinely contain customer names, emails, order details and whatever a user pasted in. The conventions handle this explicitly: content attributes are opt-in, and any environment variable controlling them must be called OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT with NO_CONTENT (default), SPAN_ONLY, EVENT_ONLY or SPAN_AND_EVENT.
- Development and staging:
SPAN_ONLYis fine and makes debugging much faster. - Production: keep
NO_CONTENT, and strip content attributes in the collector as a second line of defence (config below), because one misconfigured service is enough to leak. - If you need content in production (evaluations, replaying bad answers): use an upload hook to store it in a separate bucket with its own access rules and retention, and keep only
gen_ai.input.messages_ref/gen_ai.output.messages_refon the span.
This is the same discipline as masking in session replay, covered in our session replay and GDPR guide: record structure and timing by default, record content only where you have a reason and a retention rule.
Step 4: a collector pipeline for agent traces
Agent traces are large (dozens of spans per run) and long (seconds to minutes), so head sampling at 10% throws away exactly the runs you need. Tail sampling decides after the run has finished: keep every failure, every slow run and every run with an enormous prompt, and a sample of the rest.
# OpenTelemetry Collector: keep the agent traces that matter, strip content in production
receivers:
otlp:
protocols:
http: { endpoint: 0.0.0.0:4318 }
grpc: { endpoint: 0.0.0.0:4317 }
processors:
memory_limiter: { check_interval: 1s, limit_percentage: 80, spike_limit_percentage: 20 }
# 1. Belt and braces: even if an app turns content capture on, prompts never leave prod
transform/strip-genai-content:
error_mode: ignore
trace_statements:
- context: span
conditions:
- resource.attributes["deployment.environment.name"] == "production"
statements:
- delete_key(attributes, "gen_ai.input.messages")
- delete_key(attributes, "gen_ai.output.messages")
- delete_key(attributes, "gen_ai.system_instructions")
- delete_key(attributes, "gen_ai.tool.call.arguments")
- delete_key(attributes, "gen_ai.tool.call.result")
# 2. Tail sampling: every failed or expensive agent run, 10% of the rest
tail_sampling:
decision_wait: 60s # agent runs are long; raise this if runs take minutes
num_traces: 50000
policies:
- name: errors
type: status_code
status_code: { status_codes: [ERROR] }
- name: slow-runs
type: latency
latency: { threshold_ms: 30000 }
- name: big-prompts
type: numeric_attribute
numeric_attribute: { key: gen_ai.usage.input_tokens, min_value: 100000 }
- name: baseline
type: probabilistic
probabilistic: { sampling_percentage: 10 }
batch: {}
exporters:
otlphttp:
endpoint: https://otlp.your-backend.example
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, transform/strip-genai-content, tail_sampling, batch]
exporters: [otlphttp]Set decision_wait longer than your typical run, or long runs will be split into partial traces. If you run more than one collector, put a load-balancing exporter in front so all spans of a trace reach the same tail-sampling instance. The same pipeline ideas apply to logs; our Kubernetes logging cost guide shows the filter and deduplication side.
Step 5: the questions your traces should answer
| Question | From spans | From metrics |
|---|---|---|
| What did this run cost? | Sum of inference-span tokens × your price table, grouped by trace | gen_ai.client.inference.usage.* counters by gen_ai.agent.name |
| Is the agent looping? | Count of chat spans under one invoke_agent span; finish_reasons stuck on tool_use | gen_ai.invoke_agent.inference_calls histogram |
| Which tool breaks most? | execute_tool and MCP spans with error.type, grouped by gen_ai.tool.name | gen_ai.execute_tool.duration with error.type |
| Is caching working? | cache_read / input_tokens per run; a sudden drop means the prompt prefix changed | gen_ai.client.inference.usage.cache_read.input_tokens |
| Where does the time go? | Critical path through chat vs execute_tool spans | gen_ai.client.inference.duration vs gen_ai.execute_tool.duration |
| Which MCP server is slow or flaky? | MCP server spans by tool, rpc.status_code | mcp.server.operation.duration |
Cost per agent run
The conventions intentionally have no cost attribute: prices change monthly and differ per contract. Store tokens on spans, keep prices in a table you control, and join at query time. With traces in ClickHouse (the default schema of the OpenTelemetry ClickHouse exporter), it looks like this:
-- Cost per agent run from inference spans (ClickHouse-style SQL over an OTel traces table).
-- The spec has no cost attribute on purpose: prices change, so join a price table you own.
WITH inference AS (
SELECT
TraceId,
SpanAttributes['gen_ai.response.model'] AS model,
toUInt64OrZero(SpanAttributes['gen_ai.usage.input_tokens']) AS input_total,
toUInt64OrZero(SpanAttributes['gen_ai.usage.cache_read.input_tokens']) AS cache_read,
toUInt64OrZero(SpanAttributes['gen_ai.usage.cache_write.input_tokens']) AS cache_write,
toUInt64OrZero(SpanAttributes['gen_ai.usage.output_tokens']) AS output
FROM otel_traces
WHERE SpanAttributes['gen_ai.operation.name'] IN ('chat', 'generate_content', 'text_completion')
AND Timestamp >= now() - INTERVAL 1 DAY
),
agents AS (
SELECT TraceId, SpanAttributes['gen_ai.agent.name'] AS agent
FROM otel_traces
WHERE SpanAttributes['gen_ai.operation.name'] = 'invoke_agent'
)
SELECT
a.agent,
count(DISTINCT i.TraceId) AS runs,
round(sum(
(i.input_total - i.cache_read - i.cache_write) * p.input_per_mtok
+ i.cache_read * p.cache_read_per_mtok
+ i.cache_write * p.cache_write_per_mtok
+ i.output * p.output_per_mtok) / 1e6, 2) AS usd,
round(usd / runs, 4) AS usd_per_run
FROM inference i
JOIN agents a USING (TraceId)
JOIN model_prices p ON p.model = i.model -- your own table, updated when prices change
GROUP BY a.agent
ORDER BY usd DESC;Watch usd_per_run, not total spend. Total spend grows with usage, which is fine; cost per run growing means the agent started looping, a prompt prefix change broke caching, or someone switched to a bigger model. Our guide to reducing AI agent costs covers what to do once you see it.
Finding bad runs in Tempo
# Grafana Tempo (TraceQL): agent runs where a tool failed
{ span.gen_ai.operation.name = "invoke_agent" } >> { span.gen_ai.operation.name = "execute_tool" && status = error }
# Runs that looped: more than 6 model calls under one agent span
{ span.gen_ai.operation.name = "invoke_agent" } > { span.gen_ai.operation.name = "chat" } | count() > 6
# Slow MCP servers, grouped by tool
{ span.mcp.method.name = "tools/call" && kind = server && duration > 2s } | by(span.gen_ai.tool.name)Connect the agent trace to the user
Agent traces tell you what the agent did. They do not tell you what the user saw, typed or gave up on. When the agent runs behind a chat widget or a copilot panel in your app, pass the browser’s session.id along with the request (as baggage, the way our session.id tracing guide shows) and use your chat thread ID as gen_ai.conversation.id. Then a failed invoke_agent span leads straight to the session replay of the user who hit it: did they retry the question three times, rage-click the send button, or close the tab while the agent was still calling tools? That context is often what separates “the model was wrong” from “the tool was slow and the UI showed nothing for 20 seconds”.
AI agent observability checklist
| Item | Done when |
|---|---|
| Root span | Every agent run has one invoke_agent span with gen_ai.agent.name and a real gen_ai.conversation.id |
| Inference | Every model call is a CLIENT span with provider, response model, input/output tokens and cache read/write tokens |
| Tools | Every tool call is an execute_tool span with tool name, call id and error.type on failure, including tool results the model sees as errors |
| MCP | traceparent travels in params._meta; MCP server spans join the agent trace instead of starting new ones |
| Content | OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT is NO_CONTENT in production, and the collector strips content attributes anyway |
| Sampling | Tail sampling keeps all failed, slow and large-prompt runs; decision_wait covers your longest normal run |
| Cost | A price table you own, joined to token counts per agent and per run, with an alert on cost per run |
| Version | Instrumentation versions pinned; dashboards read both old and new metric names until every service is on v0.1.0 names |
Frequently asked questions
What is AI agent observability?
It is the ability to see what an AI agent did on each run: which model calls it made, with how many tokens, which tools it called and with what result, how long each step took, what it cost and where it failed. In practice it means distributed tracing where one agent run is one trace, with spans for model calls, tool executions and MCP requests, plus metrics for tokens, duration and errors.
What are the OpenTelemetry GenAI semantic conventions?
They are the shared names for spans, attributes, metrics and events that describe generative AI operations, such as invoke_agent, chat and execute_tool spans and attributes like gen_ai.usage.input_tokens and gen_ai.tool.name. Since mid-2026 they live in their own repository, open-telemetry/semantic-conventions-genai, whose first standalone release, v0.1.0, was tagged on 21 November 2026. All GenAI-specific entries are still at Development stability.
How do you trace MCP tool calls with OpenTelemetry?
Create a CLIENT span named after the method and target, for example "tools/call get-weather", with mcp.method.name, gen_ai.tool.name, mcp.session.id and jsonrpc.request.id. Inject the W3C trace context into the request’s params._meta property bag (unprefixed traceparent, tracestate and baggage keys), and on the server extract it and use it as the parent of a SERVER span. If your agent framework already creates an execute_tool span, add the MCP attributes to that span instead of creating a second one.
Should I record prompts and completions in traces?
Not by default. The conventions make content opt-in: instrumentations that read OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT default to NO_CONTENT, and the values SPAN_ONLY, EVENT_ONLY and SPAN_AND_EVENT turn it on. Prompts often contain personal data, so many teams capture content only in development, or upload it to separate storage with access controls and keep a reference attribute such as gen_ai.input.messages_ref on the span.
How do I calculate LLM cost per agent run from traces?
Sum the token attributes on the inference spans in each trace (input, cache read, cache write and output tokens), multiply each by the matching price for the response model, and group by gen_ai.agent.name. The conventions deliberately have no cost attribute because prices change; keep the price table in your own database and update it when providers change pricing.
Which tools support the OpenTelemetry GenAI conventions?
On the emitting side, the OpenTelemetry Python GenAI instrumentations cover OpenAI, Anthropic, Bedrock, Google GenAI, LangChain and several agent frameworks, and the spec repo publishes a conformance report per library. Frameworks such as Pydantic AI, the Vercel AI SDK, Google ADK and Mastra emit gen_ai.* spans too. On the receiving side, any OTLP backend stores them, and LLM-focused tools such as Langfuse, Arize Phoenix, Datadog LLM Observability, Grafana Cloud and Snowflake’s Agent Observability read them. Version support differs, so check which convention version each tool expects.
Further reading
- Debugging production issues with an AI agent
- An MCP server for session data: giving AI agents user context
- How to reduce AI coding agent costs
- End-to-end tracing with the OpenTelemetry session.id
- Structured logging best practices for Node, Python and Go
- LogNroll product overview
Your agent’s trace shows what it did; the session shows what your user lived through. Try LogNroll for free and see both side by side.