Skip to main content
  1. Sign up — Create an account at platform.respan.ai
  2. Create an API key — Generate one on the API keys page
  3. Add credits or a provider key — Add credits on the Credits page or connect your own provider key on the Integrations page
Add the Docs MCP to your AI coding tool to get help building with Respan. No API key needed.
{
  "mcpServers": {
    "respan-docs": {
      "url": "https://respan.ai/docs/mcp"
    }
  }
}

What is Claude Agent SDK?

The Claude Agent SDK (claude-agent-sdk) is a framework for building agent workflows powered by Claude. It supports tool use, sub-agent delegation, and structured conversations. The Respan exporter hooks into the SDK’s lifecycle events to capture full trace data.

Setup

1

Install packages

pip install claude-agent-sdk respan-exporter-anthropic-agents python-dotenv
2

Set environment variables

export RESPAN_API_KEY="YOUR_RESPAN_API_KEY"
export ANTHROPIC_API_KEY="YOUR_ANTHROPIC_API_KEY"
RESPAN_API_KEY is used for trace export. ANTHROPIC_API_KEY is used by the Claude Agent SDK to call Anthropic directly.
You can skip ANTHROPIC_API_KEY by routing calls through the Respan gateway. The gateway uses your RESPAN_API_KEY for both the LLM call and trace export.
export RESPAN_API_KEY="YOUR_RESPAN_API_KEY"
# No ANTHROPIC_API_KEY needed
Pass the gateway URL and key via ClaudeAgentOptions.env:
options = ClaudeAgentOptions(
    permission_mode="bypassPermissions",
    max_turns=1,
    env={
        "ANTHROPIC_BASE_URL": "https://api.respan.ai/api/anthropic",
        "ANTHROPIC_AUTH_TOKEN": RESPAN_API_KEY,
        "ANTHROPIC_API_KEY": RESPAN_API_KEY,
    },
)
See the full gateway guide for more details.
3

Initialize and run

import os
from dotenv import load_dotenv

load_dotenv(override=True)

from claude_agent_sdk import ClaudeAgentOptions
from respan_exporter_anthropic_agents import RespanAnthropicAgentsExporter

exporter = RespanAnthropicAgentsExporter(
    api_key=os.getenv("RESPAN_API_KEY"),
    base_url=os.getenv("RESPAN_BASE_URL"),
)

async for message in exporter.query(
    prompt="What is 2 + 2? Reply in one word.",
    options=ClaudeAgentOptions(
        permission_mode="bypassPermissions",
        max_turns=1,
    ),
):
    print(type(message).__name__)
4

View your trace

Open the Traces page to see your agent trace.

Configuration

ParameterTypeDefaultDescription
api_keystrRESPAN_API_KEY env varRespan API key.
base_urlstrRESPAN_BASE_URL env varAPI base URL.
endpointstr | NoneNoneCustom ingest endpoint URL.
timeout_secondsint15HTTP timeout for trace export.
max_retriesint3Retry attempts for failed exports.
See the Python SDK reference for the full parameter list.

Examples

Wrapped query

The simplest integration pattern — exporter.query() handles tracing hooks automatically.
from claude_agent_sdk import ClaudeAgentOptions
from respan_exporter_anthropic_agents import RespanAnthropicAgentsExporter

exporter = RespanAnthropicAgentsExporter()

message_types = []
async for message in exporter.query(
    prompt="Name three primary colors.",
    options=ClaudeAgentOptions(
        permission_mode="bypassPermissions",
        max_turns=1,
    ),
):
    message_types.append(type(message).__name__)

print(" -> ".join(message_types))
# SystemMessage -> UserMessage -> AssistantMessage -> ResultMessage

Tool use

Tool calls are automatically captured as child spans with inputs and outputs. Specify allowed tools via ClaudeAgentOptions.
from claude_agent_sdk import ClaudeAgentOptions
from respan_exporter_anthropic_agents import RespanAnthropicAgentsExporter

exporter = RespanAnthropicAgentsExporter()

async for message in exporter.query(
    prompt="List the Python files in the current directory.",
    options=ClaudeAgentOptions(
        permission_mode="bypassPermissions",
        max_turns=3,
        allowed_tools=["Read", "Glob", "Grep"],
    ),
):
    print(type(message).__name__)
Each tool invocation creates a child span in the trace with the tool name, input arguments, and output.

Streaming

The exporter.query() method streams messages as they arrive. Handle each message type.
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage
from respan_exporter_anthropic_agents import RespanAnthropicAgentsExporter

exporter = RespanAnthropicAgentsExporter()

async for message in exporter.query(
    prompt="Write a haiku about programming.",
    options=ClaudeAgentOptions(
        permission_mode="bypassPermissions",
        max_turns=1,
    ),
):
    msg_type = type(message).__name__

    if msg_type == "AssistantMessage":
        for block in getattr(message, "content", []):
            if hasattr(block, "text"):
                print(block.text)
    elif isinstance(message, ResultMessage):
        print(f"Done: {message.subtype}, turns={message.num_turns}")
Message types: SystemMessage, UserMessage, AssistantMessage, ResultMessage, StreamEvent.

Attributes

The exporter automatically captures:
AttributeSourceDescription
session_idSystemMessageUnique session identifier
input_tokensAssistantMessage.usagePrompt token count
output_tokensAssistantMessage.usageCompletion token count
cache_creation_input_tokensAssistantMessage.usageCache creation tokens
cache_read_input_tokensAssistantMessage.usageCache read tokens
modelAssistantMessageModel name used

Traced events

The exporter hooks into five SDK lifecycle events:
EventSpan TypeDescription
UserPromptSubmittaskUser submits a prompt
PreToolUseTool invocation starts (paired with PostToolUse)
PostToolUsetoolTool completes with input/output
SubagentStoptaskSub-agent finishes execution
StopRoot agent terminates
Looking for gateway integration? See Gateway > Claude Agent SDK.