← Back to Cookbook

Trace the Claude TypeScript 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 the latest Claude TypeScript SDK, then add the OpenTelemetry SDK, an OTLP exporter, and Zod for the tool schema. 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
npm install @anthropic-ai/sdk@latest @opentelemetry/api @opentelemetry/sdk-trace-node \
  @opentelemetry/exporter-trace-otlp-proto @opentelemetry/resources \
  @opentelemetry/semantic-conventions zod tsx

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. The .mts extension runs the file as an ES module, so top-level await works in any project. Run the tool runner inside one of your own spans, so the SDK spans nest under it. Set traces.contentMode to "content" to include prompts and responses in the spans, and set a conversationId to group the calls of one task into a conversation in Sentry.

Claude SDK OpenTelemetry options
agent.mts
import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { BatchSpanProcessor, NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import { trace } from "@opentelemetry/api";
import { z } from "zod";

// 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>
const provider = new NodeTracerProvider({
  resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: "weather-agent" }),
  spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter())],
});
provider.register();

const client = new Anthropic({ openTelemetry: { traces: { contentMode: "content" } } });
const tracer = trace.getTracer("weather-agent");

const getWeather = betaZodTool({
  name: "get_weather",
  description: "Get the current weather for a city",
  inputSchema: z.object({ city: z.string() }),
  run: async ({ city }) => {
    const geo = await fetch(
      `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1`,
    ).then((r) => r.json());
    const { latitude, longitude } = geo.results[0];
    const weather = await fetch(
      `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m,wind_speed_10m`,
    ).then((r) => r.json());
    return JSON.stringify(weather.current);
  },
});

await tracer.startActiveSpan("answer_question", async (span) => {
  const finalMessage = await client.beta.messages.toolRunner(
    {
      model: "claude-opus-5",
      max_tokens: 1024,
      tools: [getWeather],
      messages: [{ role: "user", content: "What's the weather in Vienna right now?" }],
    },
    { openTelemetry: { conversationId: `weather-${Date.now()}` } },
  );
  console.log(finalMessage.content);
  console.log("trace id:", span.spanContext().traceId);
  span.end();
});

await 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
node --env-file=.env --import tsx agent.mts
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 conversationId. 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 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 conversationId 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 TypeScript. For Python, see Trace the Claude Python 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.contentMode to "content" in the openTelemetry option, or set ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content for a client that has no openTelemetry 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.