Claude Agent SDK Usage Guide
The Claude Agent SDK enables you to build AI agents that can autonomously read files, run commands, search the web, edit code, and more.
The Claude Agent SDK exposes the tools, agent loop, and context management capabilities that power Claude Code as programmable Python and TypeScript libraries.
Simply put, this is an SDK that uses Claude Code as a library. You can embed it into your own applications, CI pipelines, or automation scripts to build AI agents that can autonomously complete complex tasks.
Core Capabilities
The SDK includes built-in tools for reading files, running commands, and editing code. Your agent doesn't need to implement tool execution logic itself and can start working immediately. Key capabilities include:
| Capability | Description |
|---|---|
| Built-in Tools | File read/write, terminal commands, code editing, web search, etc. |
| Hooks | Execute custom logic before and after tool calls |
| Subagents | Break large tasks into smaller ones and delegate them to independent subagents for parallel execution |
| MCP Server | Connect to databases, browsers, external APIs, etc. |
| Permission Control | Precisely control what the agent can do and when user approval is required |
| Session Management | Build multi-turn conversational agents that maintain context |
Prerequisites
- Node.js 18+(TypeScript) orPython 3.10+
- AnAnthropic account, and obtain an API Key (Register here)
Step 1: Install the SDK
TypeScript
npm install @anthropic-ai/claude-agent-sdk
The TypeScript SDK bundles the Claude Code binary for your current platform as an optional dependency, so there's no need to install Claude Code separately.
Python
# 使用 pip pip install claude-agent-sdk # 或使用 uv(推荐) uv add claude-agent-sdk
Note: The Claude Code CLI is automatically installed with the package—no separate installation needed! The SDK uses the bundled CLI by default.
If you prefer to use a system-level installation or a specific version, you can use
ClaudeAgentOptions(cli_path="/path/to/claude")Specify a path.
Step 2: Configure API Key
fromClaude ConsoleGet an API Key, then create a file in the project directory:.envfile:
ANTHROPIC_API_KEY=your-api-key-here
Or set it directly as an environment variable:
export ANTHROPIC_API_KEY=your-api-key-here
Support for Third-Party Cloud Platforms
The SDK also supports authentication via third-party API providers: Amazon Bedrock (set theCLAUDE_CODE_USE_BEDROCK=1environment variable and configure AWS credentials), Google Vertex AI (setCLAUDE_CODE_USE_VERTEX=1) and Microsoft Azure (setCLAUDE_CODE_USE_FOUNDRY=1)。
⚠️ Important: Unless prior approval is obtained from Anthropic, third-party developers are not allowed to provide claude.ai login or rate limiting in products built on the Claude Agent SDK. Please use the API Key authentication method described in the documentation.
Step 3: Run Your First Agent
The following example creates an Agent that lists files in the current directory:
Python
Example
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="What files are in this directory?",
options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
TypeScript
Example
async function main() {
for await (const message of query({
prompt: "What files are in this directory?",
options: { allowedTools: ["Bash", "Glob"] },
})) {
if ("result" in message) {
console.log(message.result);
}
}
}
main();
Hands-on: Build an Agent That Automatically Fixes Bugs
The following is a complete example demonstrating the core usage of the Agent SDK.
Prepare a File with a Bug
Createutils.py, containing two intentional bugs:
Example
total = 0
for num in numbers:
total += num
return total / len(numbers) # Bug: division by 0 when list is empty
def get_user_name(user):
return user["name"].upper() # Bug: raises TypeError when user is None
Write the Agent
Createagent.py:
Example
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async def main():
async for message in query(
prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"], # Allowed tools
permission_mode="acceptEdits", # Auto-approve file edits
),
):
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text) # Claude's reasoning process
elif hasattr(block, "name"):
print(f"Tool: {block.name}") # Tool being called
elif isinstance(message, ResultMessage):
print(f"Done: {message.subtype}") # Final result
asyncio.run(main())
Run
python agent.py
After running, checkutils.py, you will see that the Agent autonomously completed the following actions:
- Readalready
utils.pyfile - Analyzedthe code logic, identified edge cases that could cause crashes
- Editedthe file, added comprehensive error handling
Core Concepts Explained
Functions – Entry Point to the Agent Loop
queryis the main entry point for creating an Agent loop, returning an async iterator, so you useasync forto stream messages generated by Claude in real time. The loop ends when Claude completes the task or encounters an error. The SDK handles orchestration (tool execution, context management, retries), and you only need to consume this message stream.
Each iteration produces a message, which can be:
- Claude's reasoning process
- A tool call
- Tool call result
- Final result
Tools – Control What the Agent Can Do
| Tool combinations | Agent capabilities |
|---|---|
Read, Glob, Grep |
Read-only analysis |
Read, Edit, Glob |
Analyze and modify code |
Read, Edit, Bash, Glob, Grep |
Full automation |
PlusWebSearch |
Add web search capability |
Permission Modes – Control the Level of Human Oversight
| Mode | Behavior | Use case |
|---|---|---|
acceptEdits |
Auto-approve file edits, other operations still require confirmation | Trusted development workflow |
dontAsk |
DenyallowedToolsall operations outside of |
Locked-down unattended Agent |
auto(TypeScript only) |
Model classifier automatically approves/denies each tool call | Autonomous Agent with safety guardrails |
bypassPermissions |
Run all tools directly without prompting | Sandboxed CI environment |
default |
Must providecanUseToolcallback to handle approval |
Custom approval process |
Customize Agent Behavior
Add Web Search
options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob", "WebSearch"],
permission_mode="acceptEdits"
)
Add Custom System Prompts
options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"],
permission_mode="acceptEdits",
system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.",
)
Allow Terminal Command Execution
options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob", "Bash"],
permission_mode="acceptEdits"
)
# 可以尝试:
# prompt="Write unit tests for utils.py, run them, and fix any failures"
Load Project Configuration (CLAUDE.md, etc.)
The SDK is built on the same foundation as Claude Code, and SDK Agents can access the same file system-based features: project instructions (CLAUDE.md and rules), skills, Hooks, etc. By default, the SDK does not load any file system settings.
options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit"],
# "user" 从 ~/.claude/ 加载,"project" 从 ./.claude/ 加载
setting_sources=["user", "project"],
)
Error Handling
from claude_agent_sdk import (
ClaudeSDKError, # 基础错误
CLINotFoundError, # Claude Code 未安装
CLIConnectionError, # 连接问题
ProcessError, # 进程失败
CLIJSONDecodeError, # JSON 解析失败
)
try:
async for message in query(prompt="Hello"):
pass
except CLINotFoundError:
print("请先安装 Claude Code")
except ProcessError as e:
print(f"进程失败,退出码:{e.exit_code}")
except CLIJSONDecodeError as e:
print(f"响应解析失败:{e}")
Agent SDK vs. Other Claude Tools
| Agent SDK | Client SDK(Messages API) | Claude Code CLI | |
|---|---|---|---|
| Usage | Python/TypeScript library | HTTP API calls | Terminal command-line tool |
| Tool execution | Built-in, automatic execution | Requires manual implementation | Built-in, interactive |
| Use case | Building autonomous agents, application integration | General LLM calls | Direct coding assistance |
| State management | Stateful, supports sessions | Stateless | Stateful, interactive |
SDK Feature Comparison Table
The SDK also supports Claude Code's file-system-based configuration. To use these features, set them in the optionssetting_sources=["project"](Python) orsettingSources: ['project'](TypeScript)。
| Feature | Description | Location |
|---|---|---|
| Skills | Specialized capabilities defined in Markdown | .claude/skills/*/SKILL.md |
| Slash Commands | Custom commands for common tasks | .claude/commands/*.md |
| Memory | Project context and instructions | CLAUDE.md |
| Plugins | Viapluginsoption extensions |
Configured via code |