Skip to main content
The @contextcompany/claude package provides automatic observability for agents built with the Claude Agent SDK. It instruments the SDK’s query function to capture all LLM interactions, tool calls, and agent execution traces.

Installation

npm install @contextcompany/claude

Quick Start

Wrap your Claude Agent SDK instance with instrumentClaudeAgent to automatically capture traces:
import { Agent } from '@anthropic-ai/agent-sdk';
import { instrumentClaudeAgent } from '@contextcompany/claude';

const agent = new Agent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  model: 'claude-3-5-sonnet-20250219',
  tools: [/* your tools */],
});

// Wrap the agent to enable automatic tracing
const tracedAgent = instrumentClaudeAgent(agent);

// Use the agent normally - all interactions are automatically traced
for await (const message of tracedAgent.query({ 
  prompt: 'What is the weather in San Francisco?',
  tcc: {
    runId: 'custom-run-id',
    sessionId: 'session-123',
    metadata: { user: 'alice', env: 'production' },
    debug: true,
  },
})) {
  console.log(message);
}

API Reference

instrumentClaudeAgent

Instruments a Claude Agent SDK instance to automatically capture traces and send them to The Context Company.
function instrumentClaudeAgent<T extends object>(sdk: T): WrappedSDK<T>
sdk
T
required
The Claude Agent SDK instance to instrument.
WrappedSDK<T>
WrappedSDK<T>
The instrumented SDK with the same API, plus support for the tcc parameter in the query method.
Example:
const agent = new Agent({ /* config */ });
const tracedAgent = instrumentClaudeAgent(agent);

TCCConfig

Configuration object passed to the query method’s tcc parameter.
type TCCConfig = {
  runId?: string;
  sessionId?: string;
  metadata?: Record<string, unknown>;
  debug?: boolean;
}
runId
string
Custom run identifier. Defaults to a random UUID. Use this to correlate traces across different systems or to match with your own tracking IDs.
sessionId
string
Session identifier to group related runs together. Use this to track multi-turn conversations or user sessions.
metadata
Record<string, unknown>
Arbitrary key-value metadata to attach to the run. Useful for tagging runs with user IDs, environment info, feature flags, etc.
debug
boolean
Enable debug logging to console. Logs all captured messages and telemetry payloads.

WrappedSDK

The type of the wrapped SDK returned by instrumentClaudeAgent.
type WrappedSDK<T> = T extends { query: infer Q }
  ? Omit<T, 'query'> & {
      query: (params: {
        prompt: string;
        options?: QueryOptions;
        tcc?: TCCConfig;
      }) => ReturnType<Q>;
    }
  : T;
The wrapped SDK preserves all original SDK properties and methods, with the query method enhanced to accept an optional tcc parameter.

submitFeedback

Submit user feedback for a specific run.
function submitFeedback(params: {
  runId: string;
  score?: "thumbs_up" | "thumbs_down";
  text?: string;
}): Promise<Response | undefined>
params
object
required

Usage Patterns

Basic Usage

Simple instrumentation with automatic run ID generation:
import { Agent } from '@anthropic-ai/agent-sdk';
import { instrumentClaudeAgent } from '@contextcompany/claude';

const agent = instrumentClaudeAgent(new Agent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  model: 'claude-3-5-sonnet-20250219',
}));

for await (const message of agent.query({ 
  prompt: 'Explain quantum computing',
})) {
  console.log(message);
}

With Session Tracking

Track multi-turn conversations by using a consistent sessionId:
const sessionId = crypto.randomUUID();

// First turn
for await (const message of tracedAgent.query({ 
  prompt: 'What is machine learning?',
  tcc: { sessionId },
})) {
  // Process response...
}

// Second turn - same session
for await (const message of tracedAgent.query({ 
  prompt: 'Can you give an example?',
  tcc: { sessionId },
})) {
  // Process response...
}

With Custom Metadata

Attach contextual information to your runs:
for await (const message of tracedAgent.query({ 
  prompt: 'Analyze this code',
  tcc: {
    sessionId: userSessionId,
    metadata: {
      userId: 'user_123',
      environment: 'production',
      feature: 'code-analysis',
      version: '1.2.0',
    },
  },
})) {
  console.log(message);
}

With Debug Logging

Enable detailed logging for debugging:
for await (const message of tracedAgent.query({ 
  prompt: 'Test query',
  tcc: { debug: true },
})) {
  // Console will show:
  // [TCC Debug] Query wrapper called
  // [TCC Debug] runId: abc-123
  // [TCC Debug] sessionId: null
  // [TCC Debug] Collected message type: text, total: 1
  // [TCC Debug] Sending telemetry data...
  console.log(message);
}

With Tools

Tool calls are automatically captured and traced:
const agent = instrumentClaudeAgent(new Agent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  model: 'claude-3-5-sonnet-20250219',
  tools: [
    agent.tool({
      name: 'get_weather',
      description: 'Get weather for a city',
      handler: async (args) => {
        // Tool implementation...
        return { temp: 72, conditions: 'sunny' };
      },
    }),
  ],
}));

for await (const message of agent.query({ 
  prompt: 'What\'s the weather in SF?',
  tcc: { sessionId: 'session_123' },
})) {
  // Tool calls and results are automatically traced
  console.log(message);
}

How It Works

  1. Wrapping: instrumentClaudeAgent wraps the SDK’s query method and tool factory using JavaScript Proxies
  2. Message Collection: As the agent streams responses, each message is captured with timestamps and TCC metadata
  3. Transparent Pass-through: Messages are yielded immediately to your code without modification
  4. Batch Export: When the stream completes, all collected messages are sent to TCC’s ingestion endpoint in a single batch
  5. Error Handling: Even if the query fails, partial traces are still sent to capture what happened before the error

Environment Variables

TCC_API_KEY
string
required
Your Context Company API key. Get one from the dashboard.
TCC_URL
string
Custom ingestion endpoint URL. Overrides the default endpoint.
If TCC_API_KEY is not set, the instrumentation will skip sending telemetry and log a warning to the console.

Type Safety

The instrumentation preserves full TypeScript type safety:
import { Agent } from '@anthropic-ai/agent-sdk';
import type { TCCConfig, WrappedSDK } from '@contextcompany/claude';
import { instrumentClaudeAgent } from '@contextcompany/claude';

const agent = new Agent({ /* config */ });
const tracedAgent: WrappedSDK<typeof agent> = instrumentClaudeAgent(agent);

// TypeScript knows about the 'tcc' parameter
for await (const message of tracedAgent.query({
  prompt: 'test',
  tcc: { runId: '123' }, // Fully typed
})) {
  // message types are preserved
  console.log(message.type);
}

Next Steps

Claude Agent SDK

Learn more about the Claude Agent SDK

View Traces

View your traces in the dashboard

Build docs developers (and LLMs) love