← Back to Cookbook

Trace the Claude Python SDK in Sentry with OpenTelemetry

The Claude SDK emits OpenTelemetry (OTel) spans for each request and for each tool that the tool runner runs. Point an OTLP exporter at Sentry and see your agent's model calls, tool calls, and tokens under your own application spans.

SDKs
Category Monitoring, Debugging
Time
10-15 minutes
Complexity
Beginner
Steps
5 steps

Before you start

SDKs & packages
Accounts & access
Knowledge
  • Basic familiarity with the Claude Messages API and tool use

1
Find your Sentry OTLP endpoint

Sentry accepts OpenTelemetry Protocol (OTLP) traces directly. Go to Settings → Projects, select your project, and open Client Keys (DSN). Copy the OTLP Traces Endpoint and the Public Key.

Send OTLP traces directly to Sentry

2
Install the packages

Install or upgrade to the latest Claude Python SDK, then add the OpenTelemetry SDK, an OTLP exporter, and python-dotenv to load the .env file. Add your Claude API key and the Sentry values from step 1 to your .env file. The script in step 3 lists the variables in a comment.

Terminal
pip install --upgrade anthropic opentelemetry-sdk opentelemetry-exporter-otlp-proto-http python-dotenv

3
Register a tracer provider and run a tool

The Claude SDK uses the tracer provider that your application registers, so your SDK calls stay the same. Register it before the first call. Run the tool runner inside one of your own spans, so the SDK spans nest under it. Set traces.content_mode to "content" to include prompts and responses in the spans. To group the calls of one task into a conversation in Sentry, set a conversation_id on a copy of the client with with_options(), starting from client.open_telemetry so the copy keeps the content mode.

Claude SDK OpenTelemetry options
agent.py
import json
import time
from urllib.parse import urlencode
from urllib.request import urlopen

from anthropic import Anthropic, beta_tool
from dotenv import load_dotenv
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

load_dotenv()

# Set these in .env. The exporter reads the OTEL_EXPORTER_OTLP_TRACES_* variables.
#   ANTHROPIC_API_KEY=<your Claude API key>
#   OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=<your OTLP traces endpoint>
#   OTEL_EXPORTER_OTLP_TRACES_HEADERS=x-sentry-auth=sentry sentry_key=<your public key>
provider = TracerProvider(resource=Resource.create({SERVICE_NAME: "weather-agent"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)

client = Anthropic(open_telemetry={"traces": {"content_mode": "content"}})
tracer = trace.get_tracer("weather-agent")


@beta_tool
def get_weather(city: str) -> str:
    """Get the current weather for a city.

    Args:
        city: The name of the city.
    """
    query = urlencode({"name": city, "count": 1})
    with urlopen(f"https://geocoding-api.open-meteo.com/v1/search?{query}") as res:
        place = json.load(res)["results"][0]
    query = urlencode({
        "latitude": place["latitude"],
        "longitude": place["longitude"],
        "current": "temperature_2m,wind_speed_10m",
    })
    with urlopen(f"https://api.open-meteo.com/v1/forecast?{query}") as res:
        weather = json.load(res)
    return json.dumps(weather["current"])


with tracer.start_as_current_span("answer_question") as span:
    # with_options() replaces the whole option, so start from client.open_telemetry.
    conversation = client.with_options(
        open_telemetry={**client.open_telemetry, "conversation_id": f"weather-{int(time.time())}"}
    )
    runner = conversation.beta.messages.tool_runner(
        model="claude-opus-5",
        max_tokens=1024,
        tools=[get_weather],
        messages=[{"role": "user", "content": "What's the weather in Vienna right now?"}],
    )
    final_message = runner.until_done()
    print(final_message.content)
    print("trace id:", format(span.get_span_context().trace_id, "032x"))

provider.shutdown()

4
Run the agent

Run the script. Claude calls get_weather, the tool runner runs it and sends the result back, and Claude answers. The script prints the trace ID. The trace shows in Sentry after about a minute. In the trace, your answer_question span holds the tool runner span, and the tool runner span holds the two model calls and the get_weather tool call.

Terminal
python agent.py
Sentry trace waterfall with the answer_question span as the parent of an invoke_agent span, two chat spans for claude-opus-5, and an execute_tool span for get_weather

5
Explore the conversation in Sentry

Open Agents under Explore in Sentry. On the Conversations tab, select the conversation with your conversation_id. The Timeline tab shows the tool runner, each anthropic.messages.create call with its tokens and cost, and the get_weather tool call with its input. Select a model call to see its prompt and response.

AI Agents monitoring docs
Sentry conversation timeline for a Claude Python SDK tool runner, with two claude-opus-5 calls and a get_weather tool call, and a detail panel with the token count, cost, and response of the second model call

That's it.

Your code, your tools, and every Claude call. In one trace.

The Claude SDK traces each request and each tool that your code runs for Claude. Send the spans to the same Sentry project as your errors and backend spans, and debug a failed agent run without a new tool.

  • Found your project's OTLP endpoint and public key in Sentry
  • Exported Claude SDK spans to Sentry with an OTLP exporter
  • Nested Claude SDK spans under your own application spans
  • Grouped the calls of one task into a conversation in Sentry
  • Read model calls, tool calls, and token usage in Sentry

Pro tips

  • 💡 Set the same conversation_id on every call of a multi-step task, so Sentry shows the calls as one conversation.
  • 💡 Add Sentry as a destination in the Claude Console too. The SDK passes the trace context to the API, so the spans from the Claude Platform join the same trace. See Trace Claude Managed Agents and the Messages API in Sentry.
  • 💡 Already run an OpenTelemetry Collector? Point the exporter at the Collector and add Sentry as an OTLP exporter there, so all your services use one export path.

Common pitfalls

  • ⚠️ Exiting before spans are sent. Call provider.shutdown() at the end of a short script, or the last spans can be lost.
  • ⚠️ Using the full DSN as the header value. The x-sentry-auth header takes only the public key, in the form sentry sentry_key=.
  • ⚠️ Counting tokens twice. With SDK tracing and a Claude Console destination both on, each request has a client span from the SDK and a server span from the API, both named anthropic.messages.create. To sum tokens, use only the spans where service.name is claude-platform.

Frequently asked questions

No. The Claude SDK emits standard OpenTelemetry spans, and Sentry ingests them at its OTLP endpoint.

This recipe uses Python. For TypeScript, see Trace the Claude TypeScript SDK in Sentry with OpenTelemetry. Anthropic's docs list the other Claude SDKs with OpenTelemetry support. Sentry accepts OTLP traces from any of them. SDK tracing also works with Claude on Amazon Bedrock, Google Cloud, and Microsoft Foundry, in beta. Claude OpenTelemetry export and Sentry's OTLP ingestion are both in public beta, so span names and attributes can change.

Only if you set traces.content_mode to "content" in the open_telemetry option, or set ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content for a client that has no open_telemetry option. The default is metadata only: names, timing, status, and token counts. Sentry stores what it receives under your project's retention and data scrubbing settings.

No. If the Sentry SDK integration and the Claude SDK both trace the same calls, you get duplicate spans. Keep one: turn off the Sentry Anthropic integration, or set ANTHROPIC_OPEN_TELEMETRY=false to turn off Claude SDK spans.

Spans are billed by volume, the same as other Sentry tracing data. Sentry's free plan includes a span quota that is enough to try this out.

Fix it, don't observe it.

Get started with the only application monitoring platform that empowers developers to fix application problems without compromising on velocity.