Skip to content

feat: add OpenTelemetry tracing support#530

Draft
wingding12 wants to merge 1 commit intoanthropics:mainfrom
wingding12:feat/opentelemetry-tracing-452
Draft

feat: add OpenTelemetry tracing support#530
wingding12 wants to merge 1 commit intoanthropics:mainfrom
wingding12:feat/opentelemetry-tracing-452

Conversation

@wingding12
Copy link

Summary

Add opt-in OpenTelemetry tracing support via the tracer parameter in ClaudeAgentOptions. This enables observability for applications using the Claude SDK.

Changes

  • types.py: Add tracer parameter to ClaudeAgentOptions
  • _internal/tracing.py (new): Create tracing helper module with TracingContext class and span utilities
  • _internal/query.py: Add tracing for control protocol requests, permission checks, hooks, and MCP calls
  • _internal/client.py: Add tracing for query processing with span attributes for results
  • client.py: Add session-level tracing for ClaudeSDKClient
  • pyproject.toml: Add telemetry optional dependency (opentelemetry-api>=1.20.0)
  • tests/test_tracing.py (new): Add comprehensive unit tests

Span Names

When tracing is enabled, the following spans are created:

Span Name Description
claude_agent_sdk.query Query function calls
claude_agent_sdk.session ClaudeSDKClient sessions
claude_agent_sdk.control Control protocol requests
claude_agent_sdk.permission Tool permission checks
claude_agent_sdk.hook Hook callbacks
claude_agent_sdk.mcp MCP server requests

Usage

from opentelemetry import trace
from claude_agent_sdk import query, ClaudeAgentOptions

tracer = trace.get_tracer("my-app")
options = ClaudeAgentOptions(tracer=tracer)

async for message in query(prompt="Hello", options=options):
    print(message)

Install with: pip install claude-agent-sdk[telemetry]

Test Plan

  • All existing tests pass
  • New tracing tests pass (18 tests)
  • Ruff linting passes
  • Works correctly when opentelemetry is not installed (graceful degradation)

Closes #452

Add opt-in OpenTelemetry tracing via the `tracer` parameter in
ClaudeAgentOptions. When a tracer is provided, spans are created for
key operations:

- claude_agent_sdk.query - for query() function calls
- claude_agent_sdk.session - for ClaudeSDKClient sessions
- claude_agent_sdk.control - for control protocol requests
- claude_agent_sdk.permission - for tool permission checks
- claude_agent_sdk.hook - for hook callbacks
- claude_agent_sdk.mcp - for MCP server requests

Usage:
```python
from opentelemetry import trace
tracer = trace.get_tracer("my-app")
options = ClaudeAgentOptions(tracer=tracer)
```

Install with: pip install claude-agent-sdk[telemetry]

Closes anthropics#452
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add OpenTelemetry Tracing Support

1 participant