Skip to content

Add OpenTelemetry Tracing Support #452

@vasantteja

Description

@vasantteja

Howdy folks, I am working on adding support for this sdk in https://github.com/open-telemetry/opentelemetry-python-contrib. To enable proper instrumentation, I'd like to add native tracing support in the SDK where the SDK creates spans and the contrib package adds semantic convention attributes.

Summary

Add opt-in OpenTelemetry tracing to claude-agent-sdk-python by accepting a user-provided Tracer and creating spans for key operations (query, tool execution, hooks, MCP calls).

Motivation

  • Enable observability for debugging and monitoring agent execution
  • Use industry-standard OpenTelemetry (vendor-neutral, works with all observability platforms)
  • Allow downstream opentelemetry-instrumentation-claude-agent-sdk package in otel-python-contrib to add semantic convention attributes

Proposed Approach

SDK creates minimal spans (names only, no attributes):

  • claude_agent_sdk.query
  • claude_agent_sdk.session
  • claude_agent_sdk.tool
  • claude_agent_sdk.hook
  • claude_agent_sdk.mcp

User provides tracer via ClaudeAgentOptions:

from opentelemetry import trace

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

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

Open Question

How should tracing be enabled?

Option A: User provides tracer (implicit enable)

options = ClaudeAgentOptions(tracer=my_tracer)  # Tracing enabled
options = ClaudeAgentOptions()  # Tracing disabled

Option B: Explicit flag + tracer

options = ClaudeAgentOptions(tracer=my_tracer, enable_tracing=True)

Option C: Flag only (SDK manages tracer internally)

options = ClaudeAgentOptions(enable_tracing=True)

Which approach do you prefer? Option A is simplest and gives users full control over their tracer configuration.

Implementation

  • Add optional dependency: opentelemetry-api>=1.20.0
  • Zero overhead when disabled
  • Fully backward compatible

Let me know your thoughts. If agreed, I am planning to contribute this feature.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions