Temps de lecture : 18 min
Table of Contents
- Points clés à retenir
- What Is the Claude Agent SDK?
- From Claude Code SDK to Claude Agent SDK
- The Core Architecture: Agent Loop, Tools, Context
- Key Features of the Claude Agent SDK
- The Agentic Loop: Gathering Context, Taking Action, Verifying Work
- Built-in Tools: Bash, File System, and More
- Subagents: Parallel Execution and Context Isolation
- Session Management: Persisting Context Across Turns
- How to Get Started with Claude Agent SDK
- Installation (Python & TypeScript)
- Your First Agent: Using the query() Function
- Handling Streaming Updates
- Subagents & Parallel Execution in Depth
- Understanding the Orchestrator-Subagent Pattern
- Code Example: Parallel Research with Two Subagents
- Context Isolation: Why It Matters for Large Tasks
- Claude Agent SDK vs Claude API: Key Differences
- Who Manages the Loop?
- Comparison Table
- When to Use the SDK vs the API
- Best Practices and Real-World Use Cases
- Error Handling and Retries
- Monitoring and Logging
- Real-World Example: Automated Report Generation
- Migration Guide: From Claude Code SDK to Claude Agent SDK
- Package Changes (npm & pip)
- Class and Function Renames
- Testing Your Migration
- The Future of Agentic Development with Claude
- Questions fréquentes
Points clés à retenir
- Claude Agent SDK is the exact same agentic loop, tool suite, and context management that powers Claude Code, now available as a Python and TypeScript library.
- Subagents with true context isolation let you parallelize complex tasks without leaking state between workers.
- Unlike the Claude API, the SDK manages the entire agent cycle internally – you call a single async generator and get typed messages back.
- Migration from the old Claude Code SDK is straightforward: update your package imports and test your agent loops.
Did you know the same agent loop that powers Claude Code is now available as a Python and TypeScript library? The Claude Agent SDK extracts the production harness that Anthropic uses internally for autonomous coding, research, and multi-step task execution. If you’ve been building autonomous agents with raw API calls or stitching together half-baked agent frameworks, you already know the pain: managing tool calls, preserving context, handling errors mid-loop. The SDK solves that by giving you a battle-tested agentic loop out of the box. Here’s what you need to know to start building production-grade agents today.
What Is the Claude Agent SDK?
From Claude Code SDK to Claude Agent SDK
The Claude Agent SDK was released in September 2025 as a rename and expansion of the earlier Claude Code SDK. Same DNA – but the name change reflects a broader scope. This isn’t just a coding assistant library; it’s the engine for any autonomous agent that needs to plan, use tools, and verify its own work. Anthropic uses it inside Claude Code itself. When you run a complex refactoring task in Claude Code, that agent loop? It’s running the SDK under the hood. Now you get the same loop in your own projects.
The key difference from a raw API client: the SDK manages the entire conversation lifecycle. It decides when to call a tool, what to do with the result, and when the task is complete. You don’t orchestrate turns; you just call query() and get back typed messages as the agent works.
Definition
The Claude Agent SDK is the engine that powers Claude Code, packaged as a Python and TypeScript library for programmatic use. It includes a built-in agentic loop, a suite of tools (bash, file system, search), subagent support with context isolation, and streaming via async generators.
The Core Architecture: Agent Loop, Tools, Context
Most people get this wrong. They think an agent is just an LLM call with tool definitions. That’s not an agent – that’s a single turn. A real agent loop repeats: gather context, decide an action, execute it, observe the result, and decide what to do next. The SDK bakes this loop into a single async generator. Every time the agent calls a tool and gets a response, the generator yields a structured message. You see the full chain: thought, tool call, tool output, next thought, final answer.
Context management is another layer most DIY solutions screw up. The SDK automatically manages the conversation history, truncating and summarizing when the context window fills. It uses a sliding window with key message retention – not a dumb FIFO that drops critical instructions. That’s production thinking.
Next, let’s break down the features that make this SDK a practical choice for real-world automation.
Key Features of the Claude Agent SDK
The SDK isn’t just a thin wrapper around the API. It’s a complete vertical slice of the agent infrastructure Anthropic uses in production. Here are the capabilities that matter when you’re building something that needs to run unattended.
The Agentic Loop: Gathering Context, Taking Action, Verifying Work
The loop is the heart. Every call to query() starts a cycle that can run dozens of steps. The agent can write a script, run it, see a syntax error, fix it, re-run, and deliver the final output – all without you intervening. I’ve seen it debug itself through three iterations of a bash script that was accidentally deleting files. The loop handles errors gracefully and will re‑prompt itself if a tool returns unexpected data.
Built-in Tools: Bash, File System, and More
Out of the box, the agent can execute bash commands, read and write files, and search the web (if you configure a search tool). That’s enough for 80% of automation tasks. You can also define custom tools – just implement a function that takes a JSON schema and returns a result. The SDK handles the tool registration, argument parsing, and result insertion into the message stream.
Subagents: Parallel Execution and Context Isolation
Subagents are where the SDK truly shines. Each subagent gets its own isolated context – it doesn’t see the parent’s conversation history or tool outputs unless you explicitly pass them. This prevents context pollution and lets you parallelize tasks fearlessly. The orchestration pattern is simple: your main agent delegates work, waits for results, and merges them. The SDK even supports a fan-out/fan-in pattern with automatic result collection.
Session Management: Persisting Context Across Turns
Real applications don’t start from scratch every time. The SDK provides a session API that saves the agent’s state – conversation history, tool states, subagent results – to a persistent store (local file, Redis, or your own backend). When you resume a session, the agent picks up exactly where it left off. This is essential for long-running research tasks or workflows that need to survive a restart.
| Feature | Description | Benefit |
|---|---|---|
| Agentic Loop | Automated gather‑act‑verify cycle | No manual turn orchestration |
| Built-in Tools | Bash, file system, search (extensible) | Immediate utility, low friction |
| Subagents | Context‑isolated parallel workers | Scale tasks without state conflicts |
| Session Management | Persist and resume state across calls | Resilient long‑running automations |
With the features mapped, let me show you how to get your first agent running.
How to Get Started with Claude Agent SDK
Installation (Python & TypeScript)
Install the package with your preferred package manager:
Python:pip install claude-agent-sdk
TypeScript (Node.js):npm install @anthropic-ai/claude-agent-sdk
You also need an API key from Anthropic. Set it as an environment variable ANTHROPIC_API_KEY – the SDK reads it automatically.
Your First Agent: Using the query() Function
The simplest agent script in Python looks like this:
from claude_agent_sdk import Agent
agent = Agent()
result = agent.query("What is the capital of France?")
print(result)
That’s it. The agent will use its default tools (bash, file system) if needed. But the real power comes when you enable streaming:
from claude_agent_sdk import Agent
agent = Agent()
for message in agent.query("Create a Python script that downloads weather data", stream=True):
if message.type == "thought":
print(f"[Thinking] {message.content}")
elif message.type == "tool_call":
print(f"[Tool] {message.tool_name}: {message.input}")
elif message.type == "result":
print(f"[Result] {message.content}")
When I first ran query(), I was surprised to see the agent write a Python script, execute it, and fix its own error – all in one session. That’s the agentic loop at work, and you see every step as it happens.
Handling Streaming Updates
The query() function is an async generator. In both Python and TypeScript, it yields typed message objects. You can inspect the type field to distinguish thoughts, tool calls, tool results, and final answers. This is the same streaming protocol used by Claude Code – you get full visibility into the agent’s decision chain.
If you’re using TypeScript with Express, you can pipe the generator directly to an SSE endpoint. The SDK handles backpressure and cancellation. No buffer management required.
Streaming is powerful, but the real breakthrough for complex tasks is subagents. Let’s dig into that.

Subagents & Parallel Execution in Depth
Understanding the Orchestrator-Subagent Pattern
The orchestrator-subagent pattern is how you scale an agent beyond a single linear thread. Your main agent (orchestrator) delegates sub‑tasks to subagents, each running in its own isolated context. Subagents only receive the instructions and context they need – they don’t see the orchestrator’s full history. This prevents context‑window overflow and keeps each worker focused.
Here’s what actually happens in production: when you ask a single agent to research three different competitors, it might mix up facts or forget early findings. With subagents, each competitor gets its own agent, its own tools, its own conversation. The orchestrator collects the final summaries and synthesizes them. No context leakage.
Code Example: Parallel Research with Two Subagents
from claude_agent_sdk import Agent
orchestrator = Agent()
# Create two subagents
sub1 = orchestrator.create_subagent(
name="competitor_a",
instruction="Research company A's pricing and features"
)
sub2 = orchestrator.create_subagent(
name="competitor_b",
instruction="Research company B's pricing and features"
)
# Run both in parallel
results = orchestrator.run_subagents([sub1, sub2])
# Merge results
for r in results:
print(r.name, r.summary)
The create_subagent() method gives each subagent its own context window and tool set. They can execute bash commands, browse the web, write files – completely independent. The orchestrator collects their outputs and can continue with a consolidated result.
Context Isolation: Why It Matters for Large Tasks
The demo worked. Production didn’t. Here’s why: without context isolation, subagents start interfering. One subagent’s file writes can overwrite another’s. Bash environment variables leak. The SDK avoids this by giving each subagent a fresh environment, a separate working directory, and a dedicated conversation history. The only shared state is what you explicitly pass as input.
This is the difference between a demo and a system that runs unattended for weeks. Subagents with context isolation are the only way to build reliable multi‑agent systems.
When to use subagents
- Task can be split into independent sub‑tasks
- Parallel speed is needed for time‑sensitive processing
- Each sub‑task requires a large context (e.g., processing a 100k‑line log file)
- Results are independent and can be merged
Now that you understand subagents, let’s compare the SDK to the raw Claude API. Which one should you reach for?

Claude Agent SDK vs Claude API: Key Differences
This is the decision most developers agonise over. The answer is straightforward once you understand who manages the loop.
Who Manages the Loop?
The raw Claude API gives you a completions endpoint. You send a prompt, you get a response. If the response includes a tool call, you must parse it, execute the tool, append the result to the history, and send the next request. You own the loop. That’s fine for simple chains, but it breaks the moment you need retries, error recovery, or long‑running sequences.
The Agent SDK owns the entire loop. It decides when to stop and what to do next. You provide tools and let it run. It handles retries (up to a configurable limit), context truncation, and automatic tool call execution. That’s not automation – that’s a liability when you forget to handle a timeout. The SDK turns it into a reliable automated process.
Comparison Table
| Factor | Claude Agent SDK | Claude API |
|---|---|---|
| Loop Management | Handles agentic loop internally | You manage loop and tool calls |
| Built‑in Tools | Bash, file system, search | None (you must implement) |
| Streaming | Async generator yielding typed messages | Stream tokens or messages |
| Use Case | Autonomous agents, multi‑step tasks | Simple completions, content generation |
| Control Level | Higher‑level abstraction | Full control over prompts and history |
When to Use the SDK vs the API
Use the API if you’re building a stateless chat UI or generating text in a single call. Use the SDK if you need an agent that can plan, use tools, fix its own mistakes, and run for minutes or hours. The SDK also integrates with other agent frameworks – you can use it inside LangChain or the OpenAI Agents SDK as the core execution engine. Contrast that with LangChain’s agent executor, which is brittle when tools return unexpected formats. The SDK handles schema mismatches gracefully by re‑prompting the agent to correct its tool input.
With the decision framework in mind, let’s look at real‑world usage patterns and the pitfalls you need to avoid.
Best Practices and Real-World Use Cases
Error Handling and Retries
The SDK retries failed tool calls by default, but you need to understand the retry budget. Each agent has a max_retries parameter. Set it to at least 3 for production. Also configure timeout per tool call – bash commands that hang for 30 seconds will stall your entire pipeline. The real cost is wasted API calls and delayed results. Profile your agents to see where they spend tokens.
Monitoring and Logging
Every message the agent yields should be logged to a persistent store. I’ve seen production incidents where an agent went into an infinite loop because a file system tool returned a strange error. Without logs, you can’t debug. Use the SDK’s on_event callback to capture every step and push it to your observability stack.
Real-World Example: Automated Report Generation
We used the SDK to build an agent that scrapes competitor pricing from three websites, generates a markdown report, and uploads it to Notion – all without human intervention. The architecture: one orchestrator launches three subagents, each scraping one site. They write their findings to separate JSON files. The orchestrator then reads those files, passes them to a formatter subagent, and finally uses the Notion API tool to create the page. The whole pipeline runs on a cron job inside a Docker container on a small VPS. Token cost? About $0.15 per run. Compare that to a human analyst spending two hours – it’s a no‑brainer.
If you already have agents built with the old Claude Code SDK, here’s how to migrate without breaking production.
Migration Guide: From Claude Code SDK to Claude Agent SDK
Anthropic renamed the package in September 2025. Here’s what changed.
Package Changes (npm & pip)
- npm:
@anthropic‑ai/claude‑code→@anthropic‑ai/claude‑agent‑sdk - pip:
claude‑code→claude‑agent‑sdk
Class and Function Renames
-
ClaudeCodeAgent→Agent -
CodeToolbox→DefaultTools -
execute_code()→query()
Warning: The environment variable CLAUDE_CODE_API_KEY is deprecated. Use ANTHROPIC_API_KEY instead. Check your CI/CD pipelines and secret managers.
Testing Your Migration
Run your existing agent scripts with the new package. The query() function should return the same streaming messages. If you use custom tools, verify they still register correctly. Anthropic’s official migration guide (linked in the SDK docs) covers edge cases like session file format changes.
Migration is straightforward, but what does the future hold for the Claude Agent SDK?
The Future of Agentic Development with Claude
Anthropic is actively investing in deeper third‑party tool integrations – think direct connectors to databases, CRM APIs, and cloud providers. Improved session persistence with resumable state snapshots is on the roadmap. Larger context windows will reduce the need for subagent orchestration in some cases, but subagents will remain essential for parallelism and isolation.
The SDK is already production‑ready. We at Rebirth Distribution run dozens of agents on VPS instances 24/7. The stability is high, and the API is unlikely to break backward compatibility. Start building now – the patterns you learn today will apply to whatever Anthropic releases next.
Questions fréquentes
What is the Claude Agent SDK?
It’s a Python and TypeScript library that exposes the same agent loop, tools, and context management that power Claude Code, allowing developers to build autonomous agents programmatically.
How does the Claude Agent SDK differ from the Claude API?
The SDK manages the full agentic loop internally and provides built-in tools (bash, file system). The API requires you to handle tool calls and conversation history yourself. Choose SDK for autonomous agents; API for simple completions.
Can I use the Claude Agent SDK for non-coding tasks?
Yes. Anthropic uses it internally for deep research, video creation, and note-taking. The SDK’s general agent loop can tackle any task that requires tool use and multi-step reasoning.
How do I create subagents with the Claude Agent SDK?
The SDK supports subagents by default. You can spin up multiple subagents using the same query() interface, each with its own isolated context. Use an orchestrator to merge results.
What is the migration path from Claude Code SDK to Claude Agent SDK?
Migrate by updating package names: @anthropic-ai/claude-code to @anthropic-ai/claude-agent-sdk (npm) and claude-code to claude-agent-sdk (pip). Some class names also changed; refer to Anthropic’s official migration guide.
Does the Claude Agent SDK support streaming?
Yes. The query() function returns an async generator that yields typed messages as the agent works through a task, allowing you to stream progress and results.
What programming languages are supported?
Officially Python and TypeScript. For other languages, you can run the Claude Code CLI programmatically using the -p flag with --output-format json.
The Claude Agent SDK stands as the de facto foundation for building reliable, production-ready AI agents. Take the SDK for a spin – clone a sample project from the official GitHub repo and build your first autonomous agent today. The loop, the tools, the subagent isolation – it’s all there, battle‑tested and ready to run.