# Trace the Claude TypeScript SDK in Sentry with OpenTelemetry

> Export OpenTelemetry traces from the Claude TypeScript SDK to Sentry. See each model call, tool call, and token of your agent under your own application spans.

**URL:** https://sentry.io/cookbook/trace-claude-typescript-sdk-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.

**Time:** 10-15 minutes | **Difficulty:** Beginner

## What You'll Learn

- 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

**Topics:** Tracing, AI Observability, Agent Tracing

**SDKs:** Node.js

## Before you start

**SDKs & packages**

- Node.js 20.6 or later

- The latest [Claude TypeScript SDK](https://platform.claude.com/docs/en/manage-claude/opentelemetry/sdk#install-the-sdk) (`@anthropic-ai/sdk`)

**Accounts & access**

- [Sentry account](https://sentry.io/signup/) with a project for your agent

- A [Claude API key](https://platform.claude.com/settings/keys)

**Knowledge**

- Basic familiarity with the Claude Messages API and tool use

## Steps

### 1. Find your Sentry OTLP endpoint

Sentry accepts OpenTelemetry Protocol (OTLP) traces directly. Go to [Settings → Projects](https://sentry.io/orgredirect/organizations/:orgslug/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](https://docs.sentry.io/concepts/otlp/direct/traces/)

### 2. Install the packages

Install the latest [Claude TypeScript SDK](https://platform.claude.com/docs/en/manage-claude/opentelemetry/sdk#install-the-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.

```bash
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.

```typescript
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();
```

[Claude SDK OpenTelemetry options](https://platform.claude.com/docs/en/manage-claude/opentelemetry/sdk#configure-the-sdk)

### 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.

```bash
node --env-file=.env --import tsx agent.mts
```

### 5. Explore the conversation in Sentry

Open [Agents](https://sentry.io/orgredirect/organizations/:orgslug/explore/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](https://docs.sentry.io/product/agents/)

## Summary

**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.

## 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](/cookbook/trace-claude-platform-with-opentelemetry/).

- 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=<public 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`.

## FAQ

**Do I need the Sentry SDK for this?**

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

**Which languages does this work with?**

This recipe uses TypeScript. For Python, see [Trace the Claude Python SDK in Sentry with OpenTelemetry](/cookbook/trace-claude-python-sdk-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.

**Are prompts and responses sent to Sentry?**

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.

**I already use the Sentry Anthropic integration. Do I need both?**

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.

**How much does it cost?**

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.

## Next Steps

- [Add Claude Platform spans](/cookbook/trace-claude-platform-with-opentelemetry/): See model requests and server tools from the Claude Platform in the same trace, with no code.

- [Trace the Claude Python SDK](/cookbook/trace-claude-python-sdk-with-opentelemetry/): Use the same OpenTelemetry setup to trace Claude SDK calls and tools in a Python app.

- [Read the Claude span reference](https://platform.claude.com/docs/en/api/opentelemetry/spans): See every span and attribute that the Claude SDK and the Claude Platform emit.

- [Monitor your AI agents](https://docs.sentry.io/product/agents/): Track agent runs, tool calls, and token usage across all your AI features.

---

*Source: [sentry.io/cookbook/trace-claude-typescript-sdk-with-opentelemetry/](https://sentry.io/cookbook/trace-claude-typescript-sdk-with-opentelemetry/)*
