Claude Agent SDK
The Claude Agent SDK exposes the agent loop, tools, sub-agents, hooks and permissions behind Claude Code for your own agents. Learn how it works and when to use it.
Overview
The Claude Agent SDK is Anthropic's library for building agents on Claude models. It gives you, as a Python or TypeScript library, the same agent loop, built-in tools and context management that power Claude Code. Your program sends a task, and the SDK runs the cycle of thinking, calling tools, reading results and continuing until the task is done. You receive a stream of messages that shows each step.
The point of the SDK is that you do not rebuild the hard parts of an agent. A home-made agent needs a tool loop, file and shell tools, a way to stop runaway actions, a way to resume a conversation, and a way to keep the context window from filling up. The SDK ships all of these. What you add is your task, your tools and your rules.
Think of it as moving into a fitted workshop instead of buying loose tools. You could build the bench, wire the lights and label every drawer yourself. Or you can move into a workshop where the bench, the power and the safety rules are already in place, and spend your time on the actual job. The SDK is the workshop. Your prompts, tools and policies are the job.
What it is
The SDK is a library that runs the Claude Code engine inside your own process. It is published as claude-agent-sdk for Python and @anthropic-ai/claude-agent-sdk for TypeScript. It is different from the plain Claude client SDK, where you write the tool loop yourself, and from the Claude Code command line tool, which is built for people working interactively in a terminal.
| Part | What it does |
|---|---|
| Agent loop | Runs model turns and tool calls until the task finishes or a limit is hit |
| Built-in tools | Read, write and edit files, run shell commands, search files, search and fetch the web |
| Custom tools | Your own functions, exposed to the agent as in-process MCP tools |
| MCP support | Connects external MCP servers for databases, APIs and business systems |
| Sub-agents | Separate agents with their own instructions, tools and context window |
| Hooks | Your code, run at fixed points such as before or after a tool call |
| Permissions | Modes and allow, deny and ask rules that decide what may run without approval |
| Sessions | Keep context across exchanges, and resume or fork a conversation later |
| Skills, commands and memory | Loaded from .claude/ folders, the same way Claude Code loads them |
| Plugins | Packages of skills, agents, hooks and MCP servers loaded from a local path |
Two entry points matter most. The query() function starts a run and returns an asynchronous stream of messages. In Python, the ClaudeSDKClient class keeps a longer, interactive session open, so you can send follow-up messages and change settings mid-session. Options are passed in a ClaudeAgentOptions object in Python, or a plain options object in TypeScript.
Where it came from
Anthropic released Claude Code in 2025 as an agentic coding tool for the terminal. Developers soon wanted to use its engine inside their own programs, so Anthropic published it as the Claude Code SDK. Teams used it for far more than coding: research, customer support, finance operations and data work.
In late September 2025 Anthropic renamed it the Claude Agent SDK, to reflect that it is a general agent runtime. The packages changed name too, and Anthropic published a migration guide from the old Claude Code SDK packages. Since then the SDK has tracked Claude Code closely. Features such as sub-agents, hooks, skills, plugins, extra permission modes and session forking arrived in the SDK as they arrived in Claude Code. Both language versions are open on GitHub with public changelogs. Use of the SDK is governed by Anthropic's commercial terms.
How it works
Step 1: Configure the run
You choose a prompt, an optional system prompt and a set of options. The options name the tools the agent may use without asking, the tools it may never use, the MCP servers to connect, the working directory, the permission mode, any sub-agent definitions and any hooks.
Step 2: The loop runs
The SDK sends the task to Claude. Claude either replies with text or asks to call a tool. The SDK checks whether the call is allowed, runs it, and feeds the result back. This repeats. It is the same reason-act-observe cycle described in the ReAct loop, managed for you.
Step 3: Permissions decide each tool call
Every tool request passes through a fixed order of checks. Hooks run first and can deny a call outright. Deny rules come next and block matching calls in every mode. Ask rules send matching calls to your approval callback. Then the permission mode applies, then allow rules, and finally a canUseTool callback for anything still undecided.
The modes are default, dontAsk (deny anything that would prompt), acceptEdits (auto-approve file edits in the working directory), plan (explore and plan without editing), bypassPermissions (approve almost everything) and auto (a model classifier decides). A deny rule still blocks a call even in bypassPermissions mode. Note that an allow list does not restrict bypassPermissions; unlisted tools are approved too. Use deny rules for anything that must never run.
Step 4: Hooks enforce your rules
Hooks are callbacks at points in the agent's life, such as PreToolUse and PostToolUse. A pre-tool hook can block a shell command, rewrite an input or redact a secret. A post-tool hook can log every action for audit. Hooks are code, so they hold even when the model ignores an instruction.
Step 5: Delegate with sub-agents
A main agent can hand focused work to a sub-agent. Each sub-agent has its own prompt, tool set and fresh context. It returns a short result, so the main context stays small. A sub-agent inherits the parent's permission mode unless you set one on its definition, and it never escalates to bypassPermissions on its own.
Step 6: Stream results and finish
You read messages as they arrive: assistant text, tool calls, tool results, and a final result message with cost and usage. Long runs rely on context compaction, which summarises older turns so work can continue. A session ID lets you resume later.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix the failing test in tests/",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Grep", "Glob", "Edit"],
permission_mode="acceptEdits",
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
Key concepts and terms
| Term | Meaning |
|---|---|
query() |
Function that starts a run and streams messages back |
ClaudeSDKClient |
Python class for a long-lived, interactive session |
ClaudeAgentOptions |
Python options object for tools, mode, MCP servers, hooks and agents |
| Allowed tools | Tools that are approved without asking |
| Disallowed tools | Tools or patterns that are removed or always denied |
| Permission mode | Global policy for which calls are approved automatically |
canUseTool |
Callback that makes a runtime decision on undecided calls |
| Hook | Code run at a lifecycle point that can allow, deny or change an action |
| Sub-agent | Delegated agent with its own context and tools |
| Session | Conversation state that can be resumed or forked |
| Compaction | Summarising older context so a long run can continue |
A worked example
This scenario is illustrative. A finance operations team wants a month-end reconciliation agent.
- The team gives the agent read access to an exports folder and connects one MCP server that queries the ledger database.
- Allowed tools are
Read,Grep,Globand the ledger query tool.Bashis disallowed entirely. The mode isdontAsk, so anything not pre-approved is denied rather than prompted. - A
PreToolUsehook inspects every ledger query and denies any statement that is not aSELECT. - A sub-agent called "summary-writer" may only write to an
output/folder. - On a test month with 4,200 bank lines, the agent matches 4,131 to ledger entries and lists 69 exceptions in a CSV. The sub-agent drafts a one-page summary.
- A
PostToolUsehook writes every call to an audit log. A reviewer checks a sample of 10 exceptions before sign-off.
The value is that the safety rules live in code and configuration, not only in the prompt.
Strengths and limitations
Strengths:
- A production-tested loop with strong file, shell and web tools out of the box.
- First-class MCP support for both external servers and in-process custom tools.
- Layered control through hooks, deny rules, modes and callbacks.
- Sub-agents and compaction for long, broad tasks.
- Sessions that can be resumed or forked.
Limitations:
- It is built around Claude models, so it suits teams that have chosen Claude.
- Shell and file tools are powerful and need sandboxing and narrow permissions.
- The permission order has subtle cases, such as allow lists not limiting
bypassPermissions. - Third-party products may not offer claude.ai login; they should use API key authentication.
- As with any agent runtime, quality depends on your tools, prompts and evaluation.
How it compares with alternatives
| Option | Best for | Main trade-off |
|---|---|---|
| Claude Agent SDK | Claude agents that need files, shell, MCP and sub-agents built in | Tied to Claude models |
| OpenAI Agents SDK | Agents with handoffs, guardrails and built-in tracing | Fewer built-in local tools |
| Google ADK | Gemini and Google Cloud agents with workflow agents | Best fit inside Google's stack |
| LangGraph | Model-agnostic graphs with explicit state | You build the tools and loop policy |
| Raw API with function calling | Small, tightly controlled loops | You write everything yourself |
Practical guidance and best practices
- Start with a short allow list and add tools only when a real task needs them.
- Put every rule that must hold into hooks or deny rules, not only the system prompt.
- Prefer
dontAskwith an explicit allow list for headless agents. - Avoid
bypassPermissionsoutside a disposable sandbox. - Run shell-capable agents in containers without production credentials.
- Use sub-agents for wide reading tasks so the main context stays focused.
- Log every tool call with a post-tool hook and keep the log.
- Build a small set of real tasks and re-run them as evals after each change.
Common mistakes
- Assuming
allowed_toolslimits what runs inbypassPermissionsmode. It does not. - Putting the only safety check inside a
canUseToolcallback, which auto-approved calls skip. - Giving the agent production credentials "just for testing".
- Loading every MCP server at once, which crowds the context with tool descriptions.
- Never reading the transcript of failed runs.
Frequently asked questions
What is the Claude Agent SDK?
It is Anthropic's Python and TypeScript library for building agents on Claude. It runs the same agent loop, tools and context management as Claude Code inside your own application, and adds hooks, permissions, sub-agents and sessions you control from code.
Is it the same as the Claude Code SDK?
Yes. It was first published as the Claude Code SDK and renamed the Claude Agent SDK in late September 2025, because people used it for many kinds of agents beyond coding. A migration guide covers the package changes.
How is it different from the normal Claude API SDK?
With the client SDK you call the model and write the tool loop yourself. The Agent SDK runs the loop for you and ships built-in tools, permissions, hooks, sessions and compaction.
Can it use MCP servers?
Yes. You can connect external MCP servers and also define custom tools in your own process, which the SDK exposes to the agent as MCP tools.
How do I keep an SDK agent safe?
Use a short allow list, deny rules for dangerous patterns, hooks for checks that must always run, a cautious permission mode, a sandboxed environment and full logging. Ask a person to approve side effects that matter, as described in human-in-the-loop.
Does it work only for coding?
No. Coding is its origin, but the file, shell, web and MCP tools suit research, operations, support and data tasks too.
Glossary
- Agent loop: the repeated cycle of model turn, tool call and result.
- Hook: a callback that runs at a defined point in the agent's life.
- MCP: an open protocol for connecting tools and data to models.
- Permission mode: a global setting for automatic tool approval.
- Deny rule: a rule that blocks a tool or pattern in every mode.
- Sub-agent: a helper agent with its own context and tools.
- Session: saved conversation state that can be resumed.
- Compaction: summarising older context to free space.
- Plugin: a package of skills, agents, hooks and MCP servers.
Summary
The Claude Agent SDK packages the engine behind Claude Code as a library: an agent loop, built-in tools, MCP support, sub-agents, hooks, permissions, sessions and context management. It lets a team focus on its own tools and rules instead of rebuilding agent plumbing. Keep tool access narrow, put hard rules in hooks and deny rules, sandbox anything that runs commands, and test with real tasks after every change.
Related
It belongs to Agent SDKs in my stack, under Agentic AI. Others in the same group: