Skip to main content
The Claude Code SDK is a control protocol for embedding Claude Code in other applications — IDEs, automation scripts, CI/CD pipelines, or any host that can spawn a subprocess and communicate over stdin/stdout. Rather than exposing a library API directly, the SDK communicates with a running claude process over a structured JSON message stream. The host process sends user messages and control requests; the CLI process streams back assistant messages, tool progress events, and result payloads.
The TypeScript types described on this page are exported from @anthropic-ai/claude-code under the agentSdkTypes entry point. Control protocol types (prefixed SDKControl) are @alpha and subject to change.

How it works

1

Spawn a Claude Code process

Start claude with --output-format stream-json and --print (non-interactive mode). Pipe its stdin and stdout into your host process.
For a persistent session that accepts multiple prompts over time, omit --print and instead send SDKUserMessage objects to stdin after the session initializes.
2

Send an initialize request

Write a control_request with subtype: "initialize" to stdin. The CLI responds with an SDKControlInitializeResponse containing available commands, models, agents, and account information.
3

Stream messages from stdout

Read newline-delimited JSON from stdout. Each line is one of the SDKMessage union types — assistant turns, tool progress, system events, and result summaries.
4

Send user messages

Write SDKUserMessage objects to stdin to continue the conversation. Each message contains an Anthropic API-compatible message payload.

Output formats

Pass --output-format to control what Claude Code writes to stdout.
Use stream-json when you need to render progress incrementally or handle tool events. Use json when you only care about the final result.

Control protocol messages

The control protocol uses two top-level envelope types that flow bidirectionally over stdin/stdout.

SDKControlRequest

Sent to the CLI process to configure the session or issue commands.
literal: 'control_request'
required
Always "control_request".
string
required
Unique identifier for this request. The CLI echoes it back in the corresponding control_response.
SDKControlRequestInner
required
The request payload. subtype identifies which operation to perform.

SDKControlResponse

Emitted from the CLI process in response to a control_request.
On error, subtype is "error" and the error field contains a human-readable message.

Initialize request and response

The initialize request is the first control message you must send. It configures the session and returns available capabilities.

SDKControlInitializeRequest

literal: 'initialize'
required
Identifies this as an initialize request.
string
Replaces the default system prompt for this session.
string
Appended to the system prompt without replacing it. Use this to add context while keeping the default behavior.
Record<HookEvent, SDKHookCallbackMatcher[]>
Registers SDK-side hook callbacks. The CLI calls back into the SDK process when hook events fire. See Hooks reference.
string[]
Names of in-process SDK MCP servers (created with createSdkMcpServer) to connect to this session.
Record<string, AgentDefinition>
Custom subagent definitions available to the Agent tool during this session.

SDKControlInitializeResponse

The CLI responds with the session’s current capabilities.
SlashCommand[]
Available slash commands (e.g., /compact, /cost). Each entry has name, description, and argumentHint.
AgentInfo[]
Available subagent types. Each has name, description, and an optional model.
string
The active output format ("stream-json", "json", "text").
ModelInfo[]
Available models for this account.
AccountInfo
Logged-in account details.

User messages

Send user messages to stdin to drive the conversation forward.

SDKUserMessage

literal: 'user'
required
Always "user".
APIUserMessage
required
An Anthropic API-compatible user message. content can be a string or a content block array (for images and other media).
string | null
required
Tool use ID this message is responding to, or null for top-level user messages.
string
Optional UUID to track this message. Echoed back in related events.
'now' | 'next' | 'later'
Scheduling hint for async message queuing.

SDK message stream types

Claude Code emits a stream of JSON messages to stdout. The type field identifies each message.
Emitted once at session start with subtype: "init". Contains the active model, tool list, MCP server statuses, permission mode, and session ID.
Emitted when the model produces a turn. Contains the full Anthropic API response object, including any tool_use blocks.
Emitted during streaming with RawMessageStreamEvent payloads. Use these to render incremental output.
Emitted periodically for tools that take more than a few seconds (e.g., Bash commands). Contains tool_name, tool_use_id, and elapsed time.
Emitted at the end of each turn. subtype is "success" or one of the error subtypes.
Error subtypes: "error_during_execution", "error_max_turns", "error_max_budget_usd", "error_max_structured_output_retries".
Emitted with subtype: "status" when the permission mode or session status changes (e.g., "compacting").

Other control requests

Beyond initialize, the control protocol exposes these operations.

Session management API

For scripting scenarios, the SDK exports functions that operate on saved session transcripts stored in ~/.claude/.
The primary SDK entry point. Accepts a prompt string or AsyncIterable<SDKUserMessage> and returns an async iterable of SDKMessage.
Returns session metadata for a project directory. Pass dir to scope to a specific project, or omit to list all sessions.
Parses the JSONL transcript file for a session and returns messages in chronological order.
Copies a session’s transcript into a new session with remapped UUIDs. Supports upToMessageId to fork from a specific point.

Use cases

IDEs can spawn a persistent Claude Code process and route messages through the control protocol. Send the initialize request with a custom systemPrompt that describes the IDE context, then forward user messages from the editor’s chat panel. Use PreToolUse hook callbacks to intercept file edits and display diffs in the IDE’s native UI before they are applied.