How anthropics/claude-agent-sdk-python works
1. What this repo is
- This is a Python SDK package, claude_agent_sdk, that wraps the Claude Code CLI and exposes it as an async API.
- The package is distributed as a wheel/sdist and, importantly, bundles the Claude Code CLI inside the wheel by default, so users do not need a separate CLI install.
2. Public API boundary
- The main entry points are query() for one-shot async conversations and ClaudeSDKClient for long-lived, bidirectional sessions.
- The public surface is concentrated in src/claude_agent_sdk/__init__.py, query.py, client.py, types.py, and _errors.py.
3. Core runtime flow
- User code calls query() or opens a ClaudeSDKClient.
- Those APIs delegate into _internal/client.py and _internal/transport/subprocess_cli.py, which launch and talk to the Claude Code CLI as a subprocess.
- Messages are streamed back asynchronously, parsed from CLI output, and surfaced as typed Python message objects.
4. Message and protocol handling
- _internal/message_parser.py and related internal modules translate CLI-emitted JSON/event streams into SDK message types such as assistant, user, system, and result messages.
- This parsing layer is a key boundary: the SDK is not reimplementing the model; it is adapting CLI protocol output into Python-native structures.
5. Configuration and option layering
- ClaudeAgentOptions drives behavior such as working directory, system prompt, max turns, tool permissions, MCP server wiring, and CLI path selection.
- _internal/query.py, _internal/session_*, and _internal/session_store_validation.py handle option normalization, session settings, and validation before execution.
6. Tools and permissions subsystem
- Claude’s default toolset is mediated by SDK options like allowed_tools, disallowed_tools, permission_mode, and tool callbacks.
- This repo also supports Python-defined custom tools via in-process MCP servers, created with create_sdk_mcp_server() and @tool.
- There is a clear boundary between:
- external MCP servers launched separately, and
- SDK MCP servers that run in the same Python process.
7. Hooks and agent interception
- Hooks are Python callbacks invoked by the SDK at agent lifecycle points such as pre-tool-use.
- examples/hooks.py and the hooks option in ClaudeAgentOptions show that the application can inject deterministic policy, filtering, or automation before Claude executes an action.
8. Session lifecycle and persistence
- The _internal/session_* modules support importing, resuming, mutating, summarizing, and storing sessions.
- src/claude_agent_sdk/_internal/session_store.py defines the abstraction for persistent session storage, while example stores demonstrate concrete backends for Postgres, Redis, and S3.
- This makes session state an explicit subsystem rather than an implicit CLI detail.
9. Streaming, transcripts, and callbacks
- The SDK is designed around async streaming rather than blocking request/response.
- _internal/transcript_mirror_batcher.py and callback examples indicate that message streams can be mirrored, inspected, or consumed incrementally while a conversation is in progress.
10. Examples, tests, and conformance
- examples/ documents the major usage modes: quick start, streaming, hooks, MCP tools, session stores, structured output, and permission control.
- tests/ covers unit/integration behavior, while e2e-tests/ exercises full SDK-to-CLI flows, hooks, dynamic control, tool permissions, and MCP integration.
- src/claude_agent_sdk/testing/session_store_conformance.py suggests a reusable conformance layer for validating session store implementations.
11. Packaging, bundling, and release pipeline
- scripts/build_wheel.py downloads and bundles the Claude Code CLI into the package artifacts.
- GitHub Actions workflows handle linting, tests, wheel validation, PyPI quota checks, release automation, and publishing.
- The release process updates both the Python package version and the bundled CLI version, reflecting that the shipped artifact contains two independently versioned components.
12. Architectural diagram takeaway
- The central diagram should show: Python application → SDK public API → internal orchestration/parsing/session layers → subprocess Claude Code CLI, with side paths for in-process MCP tools, hook callbacks, and persistent session stores.
- Surrounding that core are build/release automation, examples, and test suites that validate the contract between the SDK and the CLI.
Main entry points: client.py Client core · __init__.py API surface · examples Examples · subprocess_cli.py Subprocess CLI
Components 21
Public SDK
User-facing package surface and core runtime orchestration.
- API surface · Public entrypoint re-exporting the main SDK types and functions.
src/claude_agent_sdk/__init__.py - Query API · One-shot async conversation API.
src/claude_agent_sdk/query.py - Client API · Long-lived bidirectional client for streaming conversations.
src/claude_agent_sdk/client.py - Types · Public message, option, and result type definitions.
src/claude_agent_sdk/types.py - Errors · SDK error hierarchy and error mapping.
src/claude_agent_sdk/_errors.py
Internal runtime
Client lifecycle, transport, parsing, sessions, and transcript handling.
- Client core · Internal execution coordinator for query and client sessions.
src/claude_agent_sdk/_internal/client.py - Query setup · Normalizes agent options and prepares a runnable session.
src/claude_agent_sdk/_internal/query.py - Subprocess CLI · Launches and communicates with the bundled Claude Code CLI.
src/claude_agent_sdk/_internal/transport/subprocess_cli.py - Message parser · Parses CLI event streams into SDK message objects.
src/claude_agent_sdk/_internal/message_parser.py - Session flows · Resume, import, mutate, and summarize session state.
src/claude_agent_sdk/_internal/sessions.py - Transcript mirror · Batches and mirrors streamed transcript data.
src/claude_agent_sdk/_internal/transcript_mirror_batcher.py
Tooling
MCP tools, hooks, and session store extensions.
- Session store · Abstraction for persistent session backends.
src/claude_agent_sdk/_internal/session_store.py - Store checks · Validates session store implementations and settings.
src/claude_agent_sdk/_internal/session_store_validation.py - MCP tools · Python-defined tools hosted inside the SDK process.
- Hooks · Lifecycle interception points such as pre-tool-use.
examples/hooks.py - Conformance · Reusable conformance checks for session store implementations.
src/claude_agent_sdk/testing/session_store_conformance.py
Delivery
Packaging, examples, and validation surfaces.
- CLI bundle · Bundled Claude Code CLI artifact shipped inside the wheel.
src/claude_agent_sdk/_bundled - Wheel build · Downloads and packages the bundled CLI into release artifacts.
scripts/build_wheel.py - Examples · Representative usage modes including streaming, tools, hooks, and stores.
examples - Tests · Unit, integration, and end-to-end coverage of SDK behavior.
tests - E2E tests · Full SDK-to-CLI flows including hooks, permissions, and MCP integration.
e2e-tests
Connections 28
- API surface → Query API: exports · Public API exposes the one-shot query helper.
- API surface → Client API: exports · Public API exposes the long-lived client.
- API surface → Types: types · Public API publishes shared SDK types.
- API surface → Errors: errors · Public API publishes the exception surface.
- Query API → Query setup: configures · Query entrypoint normalizes agent options and session settings.
- Client API → Client core: drives · Client API delegates runtime behavior to the internal orchestrator.
- Query setup → Client core: creates · Prepared query configuration enters the client core.
- Client core → Subprocess CLI: launches · Core runtime starts and talks to the subprocess CLI.
- Subprocess CLI → Message parser: streams · CLI output is parsed into structured events and messages.
- Message parser → Types: maps to · Parsed events are surfaced as public message types.
- Client core → Session flows: manages · Client core coordinates session lifecycle operations.
- Session flows → Session store: persists · Session flows can be backed by persistent stores.
- Session store → Store checks: validated by · Store implementations are checked against the session contract.
- Client core → Transcript mirror: mirrors · Streaming runtime can mirror transcript data incrementally.
- Client core → MCP tools: invokes · Runtime can attach in-process MCP tool servers.
- Client core → Hooks: calls · Agent lifecycle hooks intercept execution at policy points.
- MCP tools → Types: emits · Custom tools integrate through the same typed message surface.
- Wheel build → CLI bundle: bundles · Build script packages the CLI into the wheel artifact.
- CLI bundle → Subprocess CLI: used by · Transport executes the bundled CLI binary or entrypoint.
- Examples → Query API: demonstrates · Examples show the query-oriented workflow.
- Examples → Client API: demonstrates · Examples show the streaming client workflow.
- Examples → MCP tools: demonstrates · Examples show SDK-defined MCP tools.
- Examples → Hooks: demonstrates · Examples show hook-based interception.
- Tests → Client core: covers · Unit and integration tests exercise the runtime core.
- E2E tests → Subprocess CLI: exercises · End-to-end tests validate subprocess CLI behavior.
- E2E tests → MCP tools: exercises · End-to-end tests cover MCP tool integration.
- E2E tests → Hooks: exercises · End-to-end tests cover hook execution paths.
- Conformance → Session store: supports · Conformance harness validates session store backends.