Claude Agent SDK

RawGraph

Last edited

Fact-checked

In review queue

Sources

17 citations

Revision

v6 · 6,725 words

Fact-checks are independent of edits: a reviewer re-verifies the article against its sources and stamps the date. How we verify

The Claude Agent SDK is Anthropic's official software development kit for building custom AI agents powered by Claude, released on September 29, 2025 as the renamed and expanded successor to the Claude Code SDK.[1][2] Available for both Python and TypeScript, it provides developers with the same tools, agent loop, and context management infrastructure (the "agent harness") that powers Claude Code, packaged as a programmable library.[1][2] The SDK enables the creation of autonomous agents that can read files, execute terminal commands, search the web, edit code, and interact with external systems through the Model Context Protocol (MCP).[1]

Anthropic describes the core idea in one sentence: "The key design principle behind the Claude Agent SDK is to give your agents a computer, allowing them to work like humans do."[2] The September 2025 rename from Claude Code SDK to Claude Agent SDK reflected that the same harness was being used well beyond coding, for deep research, video creation, customer support, and legal analysis.[2] As Anthropic put it: "The agent harness that powers Claude Code (the Claude Code SDK) can power many other types of agents, too. To reflect this broader vision, we're renaming the Claude Code SDK to the Claude Agent SDK."[2]

The SDK is open source. The Python implementation lives at anthropics/claude-agent-sdk-python on GitHub under an MIT license,[3] and the TypeScript implementation lives at anthropics/claude-agent-sdk-typescript.[4] Both wrap the Claude Code CLI binary, which itself ships under Anthropic's Commercial Terms. The SDK is free to install and use; the only running cost is Claude API usage, billed per token through whichever inference backend the developer chooses (Anthropic API, AWS Bedrock, Google Vertex AI, or Microsoft Foundry).

Quick reference

AttributeValue
Original nameClaude Code SDK
Renamed toClaude Agent SDK
Rename dateSeptember 29, 2025
First PyPI prereleaseJuly 21, 2025 (claude-code-sdk 0.0.0.dev20250121)
First stable releaseSeptember 29, 2025 (alongside Claude Sonnet 4.5)
Current Python version (mid-2026)0.2.105 (June 2026), bundling claude-cli ~2.1.150
LanguagesPython 3.10+, TypeScript / Node.js 18+
License (SDK code)MIT
License (CLI binary)Anthropic Commercial Terms
Sourcegithub.com/anthropics/claude-agent-sdk-python, github.com/anthropics/claude-agent-sdk-typescript
Default modelClaude Sonnet 4.5 (configurable to Opus 4.7, Sonnet 4.6, Haiku 4.5)
Inference backendsAnthropic API, AWS Bedrock, Google Vertex AI, Microsoft Foundry
Documentationdocs.claude.com/en/api/agent-sdk

When was the Claude Agent SDK released?

The roots of the Claude Agent SDK trace back to February 2025, when Anthropic launched Claude Code as a preview. Claude Code was an agentic command-line tool that allowed developers to delegate coding tasks directly from their terminal. By May 2025, Claude Code reached general availability alongside the release of Claude 4.

As Claude Code matured, Anthropic began exposing its internal infrastructure as a programmable SDK. The first pre-release version of the Claude Code SDK appeared on PyPI on July 21, 2025 (version 0.0.0.dev20250121).[12] Through July, August, and early September, the SDK existed as a thin Python wrapper that spawned the Claude Code CLI as a subprocess and parsed its streaming JSON output. Internal teams at Anthropic, plus a handful of design partners including Cursor and Vercel, were already using it to build production agents during this period.

The stable 1.0 release followed on September 29, 2025, at which point Anthropic also renamed the package from claude-code-sdk to claude-agent-sdk (Python) and from @anthropic-ai/claude-code to @anthropic-ai/claude-agent-sdk (TypeScript / JavaScript).[2][5] The rename was timed alongside the launch of Claude Sonnet 4.5 and the Claude Code 2.0 release.[2] Anthropic published an engineering post titled "Building agents with the Claude Agent SDK" on September 29, 2025, explaining the design philosophy: that giving a model access to a real computer, with real tools, is a shorter path to capable agents than reinventing tool calling on top of a chat API.[2]

A notable enterprise milestone came on February 3, 2026, when Apple announced that Xcode 26.3 would include a native integration with the Claude Agent SDK, bringing agentic coding capabilities to iOS, macOS, and visionOS development.[10][11] Apple's announcement specifically called out the SDK's hooks and subagents as the building blocks for Xcode's new agentic coding view.[11] The integration relies on Xcode Previews to give Claude visual feedback when it edits SwiftUI views, closing the verify step of the agent loop without a human in the middle.[11]

Releases on both SDKs are roughly weekly. By June 2026 the Python SDK had reached version 0.2.105, bundling Claude CLI in the 2.1.x series.[12] The changelog reads like a slow merger of features that previously lived only in the CLI: skills, hot reload, plan mode, named themes, the /loop slash command, extended-thinking effort levels (low, medium, high, max), a SessionStore protocol, and a steady stream of permission UX work.

Languages and runtime support

Anthropic ships two first-party SDKs. Community ports cover most other languages, but they call into the same CLI binary under the hood, so feature parity is mostly a matter of which language you want to write your wrapper in.

LanguagePackageStatusNotes
Pythonclaude-agent-sdk (PyPI)Official, stableRequires Python 3.10+. Async-first API based on asyncio.
TypeScript@anthropic-ai/claude-agent-sdk (npm)Official, stableRequires Node.js 18+. Uses async iterators and AsyncGenerator.
Gohumanloop-go-sdk, agent-sdk-goCommunityWraps the CLI; not feature-complete.
Rustclaude-agent-rsCommunityBindings to the streaming JSON protocol.
Javaclaude-agent-sdk-javaCommunityMaintained by independent contributors.
Rubyclaude_agent_sdk (gem)CommunityThin wrapper over the CLI.

The official Python and TypeScript SDKs share the same conceptual model. The names of options classes match (ClaudeAgentOptions), the lifecycle hooks fire at the same points, and tool names (Read, Bash, Glob) are identical across runtimes. A subagent definition written in Python can be ported to TypeScript in a few minutes. This is largely because both SDKs delegate the actual work to the same CLI binary, which spawns as a child process and communicates over JSONL on stdout.

How does the Claude Agent SDK work?

The Claude Agent SDK is built around the idea that giving an AI model access to a computer's terminal provides it with everything it needs to accomplish complex tasks.[2] Anthropic states the principle directly: "give your agents a computer, allowing them to work like humans do."[2] Rather than requiring developers to implement their own tool execution loops and message passing, the SDK handles the entire agent loop internally.[1]

The agent loop

The SDK operates on a continuous feedback cycle that Anthropic frames as "gather context, take action, verify work, repeat":[2]

  1. Gather context. The agent retrieves and searches for relevant information using file system tools, web search, or MCP servers.
  2. Take action. The agent executes tasks using the tools available to it, such as running bash commands, editing files, or calling external APIs.
  3. Verify work. The agent evaluates the quality of its output through rules-based feedback, visual verification, or secondary model evaluation.
  4. Iterate. Based on verification results, the agent refines and improves its work until the task is complete.

This loop runs autonomously. Unlike the lower-level Anthropic API Client SDK, where the developer must implement the tool execution cycle manually, the Agent SDK handles tool invocation, result processing, and multi-turn conversation management on its own.[1] The developer's job is to define the system prompt, the available tools, the allowed permissions, and the success criteria. Everything between the prompt and the final answer is the SDK's responsibility.

This is a deliberate inversion of the usual framework design. LangChain and similar libraries give the developer raw building blocks: a prompt template, a tool registry, an output parser, a memory module, a chain. The Agent SDK gives the developer a black box that already runs and asks the developer to configure how it should behave. The trade-off is less flexibility for far less code.

Two API surfaces

The Python SDK offers two primary interfaces:[1]

InterfaceDescriptionUse case
query()Async generator function for simple queriesLightweight, one-shot tasks
ClaudeSDKClientFull-featured client with session managementMulti-turn conversations, custom tools, hooks

The query() function is the simpler entry point. Developers pass a prompt and options, then iterate over streamed messages:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Find all TODO comments and create a summary",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())

The ClaudeSDKClient provides full control over conversations, including the ability to resume sessions, use custom tools, and register hooks:

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

options = ClaudeAgentOptions(
    system_prompt="You are a helpful assistant",
    max_turns=1
)

async with ClaudeSDKClient(options=options) as client:
    await client.query("Tell me a joke")
    async for msg in client.receive_response():
        print(msg)

The TypeScript SDK exposes the same two patterns through its query() function and ClaudeAgentClient class, with idiomatic Node.js types.

What tools are built into the Claude Agent SDK?

One of the defining characteristics of the Claude Agent SDK is that it ships with a full set of built-in tools.[1] Developers do not need to implement file reading, command execution, or code editing from scratch. The SDK bundles the Claude Code CLI, which provides these capabilities automatically. Anthropic notes that tools "are the primary building blocks of execution for agents" and are kept prominent in Claude's context window so they are the first actions the model considers.[2]

ToolDescriptionTypical use
ReadRead any file in the working directory, with line numbers and offsetsReading source files, configs, logs
WriteCreate new filesGenerating new modules, reports, manifests
EditMake precise string replacements in existing filesRefactors, bug fixes, surgical edits
NotebookEditEdit cells in Jupyter notebooksData science notebooks (.ipynb)
BashRun terminal commands, scripts, and git operationsTests, builds, version control, system queries
GlobFind files by pattern (e.g., **/*.ts, src/**/*.py)Locating files by name
GrepSearch file contents using regular expressionsFinding code that matches a pattern
WebSearchSearch the web for current informationLooking up library docs, news, recent events
WebFetchFetch and parse web page contentReading specific URLs the user provides
AskUserQuestionPrompt the user for clarifying input with multiple-choice optionsDisambiguating fuzzy requests
TodoWriteTrack multi-step plans inside a long taskLong-running agents that need to remember subtasks
AgentSpawn and delegate tasks to subagentsDecomposing big jobs into focused chunks

Developers control which tools are available through the allowed_tools parameter.[1] A read-only analysis agent might only have access to Read, Glob, and Grep, while a fully autonomous coding agent might use all available tools. Disallowing Bash is the simplest way to keep an agent from running arbitrary shell commands; many production deployments do exactly this and rely only on the structured editors.

Custom tools (in-process MCP servers)

Beyond built-in tools, developers can define custom Python functions that Claude can invoke. These are registered as in-process MCP servers, which avoids the overhead of subprocess management and inter-process communication:[6]

from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient

@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
    return {
        "content": [
            {"type": "text", "text": f"Hello, {args['name']}!"}
        ]
    }

server = create_sdk_mcp_server(
    name="my-tools",
    version="1.0.0",
    tools=[greet_user]
)

options = ClaudeAgentOptions(
    mcp_servers={"tools": server},
    allowed_tools=["mcp__tools__greet"]
)

In-process tools offer better performance, simpler deployment, and easier debugging compared to external MCP servers running as separate processes.[6] Type hints in the @tool decorator double as the JSON Schema that Claude sees, so the developer never has to write the schema by hand.

Model Context Protocol integration

The Claude Agent SDK provides first-class support for the Model Context Protocol, the open standard Anthropic introduced in November 2024 for connecting AI agents to external tools and data sources.[6] MCP enables agents to interact with databases, browsers, APIs, and hundreds of third-party services without hardcoding tool definitions.[6]

Transports

MCP servers can run in three different transport modes, all of which the SDK supports:[6]

TransportWhere it runsWhen to use
stdioLocal subprocessDefault for local servers (filesystem, shell, git tools)
Streamable HTTPRemote HTTP endpointHosted enterprise servers, SaaS connectors
SSE (Server-Sent Events)Remote endpoint with streamingOlder remote servers; being phased out in favor of Streamable HTTP

The in-process MCP server variant introduced earlier is a fourth option that exists only inside the SDK; it skips the wire format entirely and just calls a Python or TypeScript function.[6]

Configuration

MCP servers can be configured either in code or through a .mcp.json configuration file.[6] A practical example connects the Playwright MCP server for browser automation:

async for message in query(
    prompt="Open example.com and describe what you see",
    options=ClaudeAgentOptions(
        mcp_servers={
            "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
        }
    ),
):
    if hasattr(message, "result"):
        print(message.result)

The SDK also supports MCP tool search, which dynamically loads tools on demand instead of preloading all tool definitions into the context window.[6] This feature is available with Claude Sonnet 4 and later models, and matters most for agents connected to dozens of MCP servers at once. Without tool search, every server's full tool list would land in the system prompt and chew through context.

Permissions for MCP tools

MCP tools require explicit permission before Claude can use them.[6] Without permission, Claude sees that the tools exist but cannot invoke them. The SDK's permission flow is the same one Claude Code uses interactively: a tool call is paused, a callback fires, the developer's code (or the user, in interactive mode) approves or denies, and the agent loop continues.

Hooks system

Hooks are the SDK's main mechanism for running custom code at well-defined points in the agent lifecycle.[8] They can validate, log, block, or transform agent behavior without modifying the core agent loop.[8] The hooks system in the SDK is the same one used by Claude Code, which means a hook script written for the CLI works inside an SDK agent and vice versa.[8]

Hook events

Hook eventTrigger pointCommon uses
PreToolUseBefore a tool is invokedValidate or block dangerous commands; redact secrets
PostToolUseAfter a tool completesLog tool usage; collect telemetry; run linters
UserPromptSubmitWhen a user prompt is receivedInject context; rewrite prompts; classify intent
StopWhen the agent finishes a turnNotify external systems; save artifacts
SubagentStopWhen a subagent finishesAggregate or route subagent results
SessionStartWhen a session beginsBootstrap state; load user-specific context
SessionEndWhen a session endsPersist memory; emit usage metrics
NotificationWhen the agent surfaces a status messageForward to chat UIs or logs

Practical example

A common use case is blocking dangerous commands. A PreToolUse hook on the Bash tool can inspect the command string and deny execution if it matches a blocklist:[8]

from claude_agent_sdk import HookMatcher, HookContext

async def block_destructive(input_data, tool_use_id, context: HookContext):
    cmd = input_data["tool_input"].get("command", "")
    if any(bad in cmd for bad in ["rm -rf /", "mkfs", ":(){ :|:& };:"]):
        return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny"}}
    return {}

options = ClaudeAgentOptions(
    hooks={
        "PreToolUse": [HookMatcher(matcher="Bash", hooks=[block_destructive])]
    }
)

Hooks can also be specified as shell commands in settings.json, the same JSON format Claude Code uses.[8] This means an organization can define a single set of safety hooks, drop the file into .claude/settings.json, and have it apply uniformly to interactive Claude Code sessions and to programmatic SDK agents running in production.

Skills integration

Claude Skills are Anthropic's packaging format for reusable workflows.[9] Anthropic launched Skills publicly on October 16, 2025 across Claude.ai, Claude Code, the Anthropic API, and the Claude Agent SDK simultaneously.[14] The SDK has supported skills natively since CLI version 2.1, with hot reload added shortly after.[9]

Skill format

A skill is a directory containing a SKILL.md file with YAML frontmatter, plus any supporting files (templates, reference docs, scripts) that the workflow needs:[9]

---
name: pdf-processing
description: Extract text and tables from PDFs, fill forms, merge documents. Use when the user mentions PDFs.
---

# PDF processing

Use pdfplumber to extract text from PDFs.
See FORMS.md for the form-filling reference.

The name field is the unique identifier (lowercase, hyphenated, maximum 64 characters).[9] The description is what Claude sees first when deciding whether to load the skill.

Discovery and loading

The SDK searches three locations for skills, in this order:[9]

ScopeLocationUse
User~/.claude/skills/Personal workflows that follow you across projects
Project.claude/skills/ (in working directory)Team-shared skills checked into a repo
Plugin.claude/plugins/<plugin>/skills/Skills bundled with a Claude Code plugin

At session start, the SDK indexes every skill it finds and adds the name and description of each to the agent's system prompt.[9] The body of the SKILL.md is not loaded yet. When the user's request matches a skill description, the agent reads the full body, and only then opens supporting files as needed. This is the progressive disclosure pattern: the cost of having many skills installed is roughly one line of system prompt per skill.[14]

Configuration

Skills loading is controlled through setting_sources.[9] Setting it to ["user", "project"] enables both user-level and repo-level skills:

options = ClaudeAgentOptions(
    setting_sources=["user", "project"],
    permission_mode="acceptEdits",
)

If setting_sources is left unset (the default), no filesystem settings are loaded at all, including skills.[9] This is intentional: production agents running in CI or in multi-tenant servers usually do not want to inherit whatever happens to be in ~/.claude/skills/ on the build host.

What are subagents in the Claude Agent SDK?

Subagents allow a main agent to spawn specialized child agents that handle focused subtasks.[7] Each subagent runs in its own fresh conversation with an isolated context window, custom system prompt, specific tool access, and independent permissions.[7] The Claude Agent SDK supports subagents by default.[2]

The key benefit of context isolation is that intermediate tool calls and results stay inside the subagent.[7] Only the final result is returned to the parent agent.[7] A research-assistant subagent might explore dozens of files, but the parent receives only a concise summary rather than every file the subagent read. This pattern is how teams keep agents on task across hour-long jobs without filling the context window with debug noise.

Multiple subagents can run concurrently, which significantly speeds up complex workflows.[7] Claude automatically determines whether to invoke a subagent based on its description field, or developers can explicitly request one by name.[7]

from claude_agent_sdk import AgentDefinition, query, ClaudeAgentOptions

async for message in query(
    prompt="Use the code-reviewer agent to review this codebase",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Glob", "Grep", "Agent"],
        agents={
            "code-reviewer": AgentDefinition(
                description="Expert code reviewer for quality and security reviews.",
                prompt="Analyze code quality and suggest improvements.",
                tools=["Read", "Glob", "Grep"],
            )
        },
    ),
):
    if hasattr(message, "result"):
        print(message.result)

Subagents can themselves spawn subagents, but most production deployments cap recursion at one or two levels. Going deeper tends to confuse the parent's notion of what the agent is supposed to be doing.

Sessions

The SDK supports persistent sessions that maintain context across multiple exchanges. Claude remembers files it has read, analysis it has performed, and the full conversation history. Developers can capture a session ID from the first query and resume it later with full context preservation:

# First query: capture the session ID
async for message in query(
    prompt="Read the authentication module",
    options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
):
    if hasattr(message, "subtype") and message.subtype == "init":
        session_id = message.session_id

# Resume with full context
async for message in query(
    prompt="Now find all places that call it",
    options=ClaudeAgentOptions(resume=session_id),
):
    if hasattr(message, "result"):
        print(message.result)

Sessions can also be forked to explore different approaches while preserving the original conversation state. A common pattern is to fork at a decision point, run two candidate agents in parallel against the fork, and pick the one whose verification step succeeds. As of the 2026 releases, both SDKs expose a SessionStore protocol (with an in-memory reference implementation) so applications can persist and reload session state through their own storage layer.[12]

Session teleportation

Claude Code 2.1 introduced session teleportation, which the SDK exposes through the same resume mechanism.[16] A developer can pause an agent on a laptop, capture its session ID, and resume the same conversation later from a CI worker or a production server. The full transcript and any persistent state move with the session ID.

Permissions and safety

The SDK provides granular control over agent permissions. Permissions exist at two layers: which tools are available at all, and how the agent is allowed to invoke them.

SettingEffect
allowed_toolsPre-approves specific tools for automatic execution
disallowed_toolsExplicitly blocks tools the agent should never use
permission_mode="default"Agent must request approval for write operations
permission_mode="acceptEdits"Auto-approves file modifications
permission_mode="acceptAll"Auto-approves every tool call (use with care)
permission_mode="plan"Plan mode: agent drafts a plan first, executes after approval
can_use_tool callbackProgrammatic per-call permission decisions

The can_use_tool callback is the most flexible option.[15] It receives the tool name and arguments and returns either an allow or deny decision. This is how teams build custom approval flows: route bash commands through a sandbox, escalate file writes outside the working directory to a human reviewer, or rate-limit web fetches.

MCP tools require explicit permission before Claude can use them.[6] Without permission, Claude sees that the tools exist but cannot invoke them.

Plan mode

Plan mode, added during Claude Code 2.0 and exposed through the SDK's permission_mode="plan" setting, asks the agent to produce a plan before executing anything.[15] The agent reads files and gathers context, but does not write, edit, or run shell commands until the plan is approved. This is the recommended mode for unfamiliar codebases or tasks where the cost of a wrong action is high. Once the plan is accepted, the agent runs in normal mode with the plan as scaffolding.

Cost tracking

Every message the SDK streams includes the token counts for that turn.[1] The ResultMessage at the end of a query includes a final usage object summing input tokens, output tokens, cache reads, cache writes, and the dollar-equivalent cost based on the active model's pricing.[1] Cost tracking is one of the SDK's most underrated features. It removes the need to instrument the underlying API calls separately:

async for msg in client.receive_response():
    if hasattr(msg, "usage"):
        print(f"Cost: ${msg.usage.cost_usd:.4f} ({msg.usage.input_tokens} in, {msg.usage.output_tokens} out)")

The SDK also exposes a Cost API at the session level, which aggregates spend across an entire conversation including subagent calls. Engineering teams use this to set per-task budgets and to bail out of runaway agents that have started looping.

Configuration options

The ClaudeAgentOptions class (Python) and equivalent TypeScript options object accept numerous configuration parameters:[1]

ParameterTypeDescription
system_promptstring or dictCustom system prompt or preset (e.g., claude_code)
max_turnsintMaximum number of conversation turns
allowed_toolslistTools pre-approved for auto-execution
disallowed_toolslistTools to block entirely
permission_modestringAuto-accept behavior for file edits (default, acceptEdits, acceptAll, plan)
cwdstring or PathWorking directory for the agent
mcp_serversdictMCP server configurations
hooksdictHook handler registrations
cli_pathstringCustom path to Claude Code CLI
modelstringClaude model to use
setting_sourceslistFilesystem settings to load (e.g., ["project"])
agentsdictSubagent definitions
betaslistBeta features to enable (e.g., 1M context window)
max_thinking_tokensintCap on extended thinking tokens per turn
resumestringSession ID to resume
fork_sessionboolFork the resumed session into a new branch

By default, the Agent SDK does not load filesystem settings (CLAUDE.md, settings.json, slash commands).[1] This is a deliberate design choice for predictable behavior in CI/CD environments, deployed applications, and multi-tenant systems. Developers who want Claude Code's default behavior can set setting_sources=["user", "project", "local"].[1]

Installation and authentication

Python

pip install claude-agent-sdk

Requires Python 3.10 or later.[12] The Claude Code CLI is automatically bundled with the package. The first import triggers an integrity check on the bundled binary.

TypeScript / JavaScript

npm install @anthropic-ai/claude-agent-sdk

Requires Node.js 18 or later.[13] The CLI binary is fetched as a postinstall step.

Authentication

The SDK requires an Anthropic API key, set as an environment variable:[1]

export ANTHROPIC_API_KEY=your-api-key

Alternatively, the SDK supports authentication through third-party cloud providers:[1]

ProviderEnvironment variableDetails
Amazon BedrockCLAUDE_CODE_USE_BEDROCK=1Uses AWS credentials
Google Vertex AICLAUDE_CODE_USE_VERTEX=1Uses Google Cloud credentials
Microsoft FoundryCLAUDE_CODE_USE_FOUNDRY=1Uses Azure credentials

For enterprise customers using SSO, the SDK also supports OAuth flows through the bundled CLI's claude login command. Once a user is authenticated interactively, the SDK picks up the cached credentials and runs without an explicit API key.

How does the Claude Agent SDK relate to Claude Code?

Claude Code is Anthropic's agentic coding tool that lives in the terminal. The Claude Agent SDK is the library (the "agent harness") that powers Claude Code internally; Anthropic describes Claude Code itself as a thin interface over the SDK.[2] The relationship can be summarized as follows:

AspectClaude Code CLIClaude Agent SDK
InterfaceInteractive terminalProgrammatic library
Best forDaily development, one-off tasksCI/CD pipelines, production automation, custom applications
ToolsFull toolsetSame full toolset, configurable
CustomizationCLAUDE.md, settings filesFull programmatic control, hooks, subagents
LanguagesN/A (CLI)Python and TypeScript
Settings loaded by defaultYesNo (must opt in via setting_sources)
Skills loaded by defaultYesNo (must opt in via setting_sources)
OutputPretty terminal UIStructured JSON stream

Many development teams use both: the CLI for interactive daily work and the SDK for production automation. Workflows translate directly between the two because they share the same underlying infrastructure. A developer can prototype a workflow in Claude Code, get the prompt and tool config right, and then drop the same setup into a Python script for batch use without rewriting anything.

How does the Claude Agent SDK compare with other agent frameworks?

The Claude Agent SDK enters a competitive landscape that includes several other frameworks for building AI agents. Each has different design priorities and trade-offs. The single biggest split is between all-in-one runtimes like the Claude Agent SDK and the OpenAI Agents SDK, which give you a working agent the moment you supply a prompt, and toolkits like LangChain or LlamaIndex, which give you a box of parts and ask you to assemble the agent yourself.

FrameworkPrimary languageModel supportBuilt-in toolsMCP supportMulti-agentHooks / lifecycleLicense
Claude Agent SDKPython, TypeScriptAnthropic ClaudeYes (Read, Write, Bash, etc.)First-class, nativeSubagents with context isolationPreToolUse, PostToolUse, Stop, etc.MIT (SDK) / Anthropic Commercial (CLI)
OpenAI Agents SDKPythonOpenAI GPT, partially provider-agnosticHosted tools (web search, code interpreter, file search)LimitedHandoffs between specialized agentsGuardrails and tracingMIT
LangChain / LangGraphPython, TypeScript600+ model integrationsVia integrationsVia pluginsLangGraph for orchestrationCallbacksMIT
LlamaIndexPython, TypeScriptMany providersStrong on data loadersVia pluginsWorkflow frameworkEvent handlersMIT
CrewAIPythonMultiple LLM providersVia integrationsVia pluginsRole-based collaborative agentsTask callbacksMIT
AutoGenPythonMultiple providersVia integrationsVia pluginsConversable multi-agent groupsLimitedMIT
StrandsPythonBedrock-first, multiple providersStrong AWS integrationsYesMulti-agent supportedCallbacksApache 2.0
Pydantic AIPythonMultiple providersLightweightYesYesType-safe lifecycleMIT

Key differentiators

The Claude Agent SDK differentiates itself through its tight integration with Claude and its built-in toolset. Unlike LangChain, which serves as a model-agnostic framework with broad integrations, the Claude Agent SDK is purpose-built for Claude and ships with production-ready tools out of the box. The single-vendor focus is the trade-off: if you need to swap to GPT or Gemini midway through a project, the Claude Agent SDK is not the right framework. If you have already chosen Claude, it is the shortest path to a working agent.

Compared to the OpenAI Agents SDK, which focuses on handoffs between specialized agents with validation guardrails, the Claude Agent SDK centers on hooks and subagents for lifecycle control. The OpenAI SDK has strengths in multimodal and voice scenarios through GPT-4o and the Realtime API. The Claude Agent SDK inherits Claude's particular skill at long-horizon coding work.

CrewAI focuses on collaborative autonomy, where agents assume specific roles and coordinate like a team. The Claude Agent SDK's subagent model provides more hierarchical control, with a parent agent delegating to children that report back. AutoGen sits between the two, with conversable agents that can talk to each other directly. Strands is AWS's agent framework, optimized for Bedrock and AWS service integrations. Pydantic AI is the lightest of the bunch, betting that strong typing and structured outputs are most of what an agent framework actually needs.

Real-world use cases and deployments

The Claude Agent SDK supports a wide range of applications across different domains. The list below mixes Anthropic's own usage, public customer announcements, and patterns that have shown up in third-party blog posts and conference talks.

DeploymentUse of the SDKSource
Cursor Background AgentsLong-running coding agents that run on cloud workers and open PRs autonomouslyCursor changelog, late 2025
GitHub Copilot Workspace tasksSome task-execution flows wrap the Agent SDK alongside Copilot's own runtimeGitHub blog
Apple Xcode 26.3 agentic codingNative integration; Xcode UI calls the SDK with Xcode Previews as the verification stepApple Newsroom, Feb 2026
Anthropic Claude Code (the CLI)Claude Code is a thin user interface over the same libraryAnthropic engineering blog
Anthropic internal SREOn-call agents that triage alerts and draft mitigationsAnthropic engineering talks
Anthropic Code ReviewThe 2026 Code Review product is built on the SDK plus subagentsAnthropic news, March 2026
Devin competitorsSeveral autonomous coding startups use the SDK as their execution layerVarious
Cloud sandbox providersCompanies that sell ephemeral VMs for agents (e.g., E2B, Daytona) ship Claude Agent SDK templatesVendor docs
Customer support automationHelp-desk agents that read knowledge bases via MCP and draft responsesAnthropic case studies
Legal contract reviewDocument review agents that compare drafts against precedent librariesAnthropic case studies
Financial analysisPortfolio agents that pull market data via MCP and produce reportsIndustry talks
Research assistantsMulti-document research agents that synthesize findings across PDFs and the webVarious

Software development

The most common use case remains software work. The full toolset is purpose-built for it: Bash for tests and builds, Read/Write/Edit for code, Glob/Grep for navigation, WebFetch and WebSearch for documentation lookups. Typical agents include bug detection and fixing agents, code review agents, CI/CD automation, and SRE bots that monitor systems and respond to incidents.

Business applications

Many teams use the SDK for non-coding work.[2] Customer support agents handle ticket routing and draft responses. Legal analysis agents review contracts and summarize documents. Financial analysis agents evaluate investments and generate reports. Research assistants synthesize information from multiple documents.

Enterprise integration

The most prominent enterprise integration is Apple's Xcode 26.3, released February 2026, which natively integrates the Claude Agent SDK to enable autonomous coding for iOS, macOS, and visionOS development.[10][11] The integration includes visual verification through Xcode Previews, which closes the verify step of the agent loop without a human in the middle.[11]

Through MCP, agents can also connect to Slack, GitHub, Asana, Google Drive, and hundreds of other services.[6] The SDK does not bake in connectors for any specific SaaS product; that is the MCP ecosystem's job.

Error handling and message types

The SDK provides a structured error hierarchy for handling different failure modes:[1]

Error classDescription
ClaudeSDKErrorBase error class for all SDK errors
CLINotFoundErrorClaude Code CLI not installed or not found
CLIConnectionErrorConnection issues with the CLI process
ProcessErrorCLI process failed (includes exit code)
CLIJSONDecodeErrorFailed to parse response JSON

Message types and content blocks

The SDK streams messages of several types during agent execution:[1]

Message typeDescription
AssistantMessageResponse content from Claude
UserMessageUser input forwarded to the agent
SystemMessageSystem-level instructions or status updates
ResultMessageFinal result of the agent's work, including usage and cost

Content within messages is structured as blocks: TextBlock for text content, ToolUseBlock for tool invocations, ToolResultBlock for tool execution results, and ThinkingBlock for extended-thinking traces when that mode is enabled.

Is the Claude Agent SDK open source?

The wrapper code is open source under an MIT license, while the bundled Claude Code CLI binary is not. Use of the Claude Agent SDK is governed by Anthropic's Commercial Terms of Service. This applies even when the SDK is used to power products and services made available to third-party customers and end users. Individual components or dependencies may be covered by separate licenses as indicated in their respective LICENSE files.

The Python and TypeScript SDK source repositories on GitHub carry an MIT license for the SDK wrapper code,[3][4] while the bundled Claude Code CLI binary falls under Anthropic's Commercial Terms. Practically speaking, the wrapper code is forkable and modifiable under MIT terms; the CLI binary is not.

The SDK source code is publicly available at anthropics/claude-agent-sdk-python[3] and anthropics/claude-agent-sdk-typescript.[4] Issues and pull requests are accepted, and Anthropic's engineering team reviews them on roughly a weekly cadence.

How do I migrate from the Claude Code SDK?

Developers who built on the original Claude Code SDK need to update their code for the renamed package.[5] The migration involves changing package names, import paths, and one renamed type:[5]

AspectOld (Claude Code SDK)New (Claude Agent SDK)
Python packageclaude-code-sdkclaude-agent-sdk
TypeScript package@anthropic-ai/claude-code@anthropic-ai/claude-agent-sdk
Python importfrom claude_code_sdk import ...from claude_agent_sdk import ...
Options classClaudeCodeOptionsClaudeAgentOptions

The Agent SDK also introduced breaking changes that go beyond a simple rename.[5] The system prompt no longer defaults to Claude Code's system prompt; an SDK agent now starts with no role unless one is provided.[5] Filesystem settings (CLAUDE.md, slash commands, settings.json) are no longer loaded automatically; they must be enabled with setting_sources.[5] These changes improve isolation and predictability for production deployments, at the cost of a small migration burden.

For at least a year after the rename, both package names continued to install. The old claude-code-sdk package became a thin alias that imports from claude-agent-sdk and emits a deprecation warning, so existing projects do not silently break.

Recent additions

The SDK's release cadence is fast. The most consequential additions since the September 2025 stable release include:

DateAdditionWhy it matters
Oct 2025Claude Skills integrationReusable workflows packaged as SKILL.md files, loaded on demand
Nov 2025Streamable HTTP transport for MCPReplaces SSE for remote MCP servers; cleaner error semantics
Dec 2025Plan mode in the SDKMakes the agent draft a plan before any write or shell action
Jan 2026Long-running tool supportTool calls that take minutes (e.g., builds, video renders) no longer time out
Feb 2026Apple Xcode native integrationFirst major IDE to ship the SDK as a built-in feature
Feb 2026Improved permission UXPer-call approval callbacks with structured reasons
Mar 2026Code Review subagent productAnthropic's first product built on the SDK as a paid offering
Apr 2026Claude Opus 4.7 as defaultDefault model upgraded from Sonnet 4.5 to Opus 4.7 for new SDK projects that opt into Opus pricing
Jun 2026SessionStore protocol and thinking effort levelsPluggable session persistence at TS/Python parity; low/medium/high/max extended-thinking control

Documentation and learning resources

Anthropic maintains the canonical documentation at docs.claude.com/en/api/agent-sdk.[1] The site is organized into a tutorial track, a reference for every option and tool, and a growing catalog of cookbook recipes. Both Python and TypeScript share the same conceptual docs, with code samples shown side by side.

The two GitHub repositories include examples/ directories with runnable agents: a code reviewer, a research assistant, a Slack bot, a documentation generator, and a web scraper.[3][4] The anthropic-cookbook repository on GitHub holds longer-form notebooks, including an agent that orchestrates computer use through the SDK and a multi-agent research pipeline.

See also

References

  1. Anthropic. "Agent SDK overview." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/overview
  2. Anthropic. "Building agents with the Claude Agent SDK." Anthropic Engineering Blog, September 29, 2025. https://www.anthropic.com/engineering/building-agents-with-the-claude-agent-sdk
  3. Anthropic. "claude-agent-sdk-python." GitHub. https://github.com/anthropics/claude-agent-sdk-python
  4. Anthropic. "claude-agent-sdk-typescript." GitHub. https://github.com/anthropics/claude-agent-sdk-typescript
  5. Anthropic. "Migrate to Claude Agent SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/migration-guide
  6. Anthropic. "Connect to external tools with MCP." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/mcp
  7. Anthropic. "Subagents in the SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/subagents
  8. Anthropic. "Hooks in the SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/hooks
  9. Anthropic. "Skills in the SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/skills
  10. Anthropic. "Apple's Xcode now supports the Claude Agent SDK." Anthropic News, February 2026. https://www.anthropic.com/news/apple-xcode-claude-agent-sdk
  11. Apple. "Xcode 26.3 unlocks the power of agentic coding." Apple Newsroom, February 2026. https://www.apple.com/newsroom/2026/02/xcode-26-point-3-unlocks-the-power-of-agentic-coding/
  12. PyPI. "claude-agent-sdk." https://pypi.org/project/claude-agent-sdk/
  13. npm. "@anthropic-ai/claude-agent-sdk." https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk
  14. Anthropic. "Equipping agents for the real world with Agent Skills." Anthropic Engineering Blog, October 16, 2025. https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills
  15. Anthropic. "Plan mode and permission UX." Anthropic Engineering Blog, December 2025.
  16. Anthropic. "Claude Code 2.1 release notes." Anthropic Documentation.
  17. Cursor. "Background Agents." Cursor changelog, late 2025. https://cursor.com/changelog

Improve this article

Add missing citations, update stale details, or suggest a clearer explanation. Every suggestion is reviewed for sourcing before it goes live.

5 revisions by 1 contributors · full history

Suggest edit