首页 教程 常见问题

Agent SDK 概览

## Documentation Index

Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

Use this file to discover all available pages before exploring further.

Agent SDK overview

Build production AI agents with Claude Code as a library

<Note>

The Claude Code SDK has been renamed to the Claude Agent SDK. If you're migrating from the old SDK, see the Migration Guide.

</Note>

Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript.

<Note>

Opus 4.7 (claude-opus-4-7) requires Agent SDK v0.2.111 or later. If you see a thinking.type.enabled API error, see Troubleshooting.

</Note>

<CodeGroup>

```python Python theme={null}

import asyncio

from claudeagentsdk import query, ClaudeAgentOptions

async def main():

async for message in query(

prompt="Find and fix the bug in auth.py",

options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),

):

print(message) # Claude reads the file, finds the bug, edits it

asyncio.run(main())

```

```typescript TypeScript theme={null}

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({

prompt: "Find and fix the bug in auth.ts",

options: { allowedTools: ["Read", "Edit", "Bash"] }

})) {

console.log(message); // Claude reads the file, finds the bug, edits it

}

```

</CodeGroup>

The Agent SDK includes built-in tools for reading files, running commands, and editing code, so your agent can start working immediately without you implementing tool execution. Dive into the quickstart or explore real agents built with the SDK:

<CardGroup cols={2}>

<Card title="Quickstart" icon="play" href="/en/agent-sdk/quickstart">

Build a bug-fixing agent in minutes

</Card>

<Card title="Example agents" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">

Email assistant, research agent, and more

</Card>

</CardGroup>

Get started

<Steps>

<Step title="Install the SDK">

<Tabs>

<Tab title="TypeScript">

```bash theme={null}

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

```

</Tab>

<Tab title="Python">

```bash theme={null}

pip install claude-agent-sdk

```

</Tab>

</Tabs>

<Note>

The TypeScript SDK bundles a native Claude Code binary for your platform as an optional dependency, so you don't need to install Claude Code separately.

</Note>

</Step>

<Step title="Set your API key">

Get an API key from the Console, then set it as an environment variable:

```bash theme={null}

export ANTHROPICAPIKEY=your-api-key

```

The SDK also supports authentication via third-party API providers:

See the setup guides for Bedrock, Vertex AI, or Azure AI Foundry for details.

<Note>

Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead.

</Note>

</Step>

<Step title="Run your first agent">

This example creates an agent that lists files in your current directory using built-in tools.

<CodeGroup>

```python Python theme={null}

import asyncio

from claudeagentsdk 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 TypeScript theme={null}

import { query } from "@anthropic-ai/claude-agent-sdk";

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);

}

```

</CodeGroup>

</Step>

</Steps>

Ready to build? Follow the Quickstart to create an agent that finds and fixes bugs in minutes.

Capabilities

Everything that makes Claude Code powerful is available in the SDK:

<Tabs>

<Tab title="Built-in tools">

Your agent can read files, run commands, and search codebases out of the box. Key tools include:

ToolWhat it does
----------------------------------------------------------------------------------------------------------------------------------------------
ReadRead any file in the working directory
WriteCreate new files
EditMake precise edits to existing files
BashRun terminal commands, scripts, git operations
MonitorWatch a background script and react to each output line as an event
GlobFind files by pattern (/.ts, src//.py)
GrepSearch file contents with regex
WebSearchSearch the web for current information
WebFetchFetch and parse web page content
AskUserQuestionAsk the user clarifying questions with multiple choice options

This example creates an agent that searches your codebase for TODO comments:

<CodeGroup>

```python Python theme={null}

import asyncio

from claudeagentsdk 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())

```

```typescript TypeScript theme={null}

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({

prompt: "Find all TODO comments and create a summary",

options: { allowedTools: ["Read", "Glob", "Grep"] }

})) {

if ("result" in message) console.log(message.result);

}

```

</CodeGroup>

</Tab>

<Tab title="Hooks">

Run custom code at key points in the agent lifecycle. SDK hooks use callback functions to validate, log, block, or transform agent behavior.

Available hooks: PreToolUse, PostToolUse, Stop, SessionStart, SessionEnd, UserPromptSubmit, and more.

This example logs all file changes to an audit file:

<CodeGroup>

```python Python theme={null}

import asyncio

from datetime import datetime

from claudeagentsdk import query, ClaudeAgentOptions, HookMatcher

async def logfilechange(inputdata, tooluse_id, context):

filepath = inputdata.get("toolinput", {}).get("filepath", "unknown")

with open("./audit.log", "a") as f:

f.write(f"{datetime.now()}: modified {file_path}\n")

return {}

async def main():

async for message in query(

prompt="Refactor utils.py to improve readability",

options=ClaudeAgentOptions(

permission_mode="acceptEdits",

hooks={

"PostToolUse": [

HookMatcher(matcher="Edit|Write", hooks=[logfilechange])

]

},

),

):

if hasattr(message, "result"):

print(message.result)

asyncio.run(main())

```

```typescript TypeScript theme={null}

import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";

import { appendFile } from "fs/promises";

const logFileChange: HookCallback = async (input) => {

const filePath = (input as any).toolinput?.filepath ?? "unknown";

await appendFile("./audit.log", ${new Date().toISOString()}: modified ${filePath}\n);

return {};

};

for await (const message of query({

prompt: "Refactor utils.py to improve readability",

options: {

permissionMode: "acceptEdits",

hooks: {

PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]

}

}

})) {

if ("result" in message) console.log(message.result);

}

```

</CodeGroup>

Learn more about hooks →

</Tab>

<Tab title="Subagents">

Spawn specialized agents to handle focused subtasks. Your main agent delegates work, and subagents report back with results.

Define custom agents with specialized instructions. Include Agent in allowedTools since subagents are invoked via the Agent tool:

<CodeGroup>

```python Python theme={null}

import asyncio

from claudeagentsdk import query, ClaudeAgentOptions, AgentDefinition

async def main():

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)

asyncio.run(main())

```

```typescript TypeScript theme={null}

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({

prompt: "Use the code-reviewer agent to review this codebase",

options: {

allowedTools: ["Read", "Glob", "Grep", "Agent"],

agents: {

"code-reviewer": {

description: "Expert code reviewer for quality and security reviews.",

prompt: "Analyze code quality and suggest improvements.",

tools: ["Read", "Glob", "Grep"]

}

}

}

})) {

if ("result" in message) console.log(message.result);

}

```

</CodeGroup>

Messages from within a subagent's context include a parenttooluse_id field, letting you track which messages belong to which subagent execution.

Learn more about subagents →

</Tab>

<Tab title="MCP">

Connect to external systems via the Model Context Protocol: databases, browsers, APIs, and hundreds more.

This example connects the Playwright MCP server to give your agent browser automation capabilities:

<CodeGroup>

```python Python theme={null}

import asyncio

from claudeagentsdk import query, ClaudeAgentOptions

async def main():

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)

asyncio.run(main())

```

```typescript TypeScript theme={null}

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({

prompt: "Open example.com and describe what you see",

options: {

mcpServers: {

playwright: { command: "npx", args: ["@playwright/mcp@latest"] }

}

}

})) {

if ("result" in message) console.log(message.result);

}

```

</CodeGroup>

Learn more about MCP →

</Tab>

<Tab title="Permissions">

Control exactly which tools your agent can use. Allow safe operations, block dangerous ones, or require approval for sensitive actions.

<Note>

For interactive approval prompts and the AskUserQuestion tool, see Handle approvals and user input.

</Note>

This example creates a read-only agent that can analyze but not modify code. allowed_tools pre-approves Read, Glob, and Grep.

<CodeGroup>

```python Python theme={null}

import asyncio

from claudeagentsdk import query, ClaudeAgentOptions

async def main():

async for message in query(

prompt="Review this code for best practices",

options=ClaudeAgentOptions(

allowed_tools=["Read", "Glob", "Grep"],

),

):

if hasattr(message, "result"):

print(message.result)

asyncio.run(main())

```

```typescript TypeScript theme={null}

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({

prompt: "Review this code for best practices",

options: {

allowedTools: ["Read", "Glob", "Grep"]

}

})) {

if ("result" in message) console.log(message.result);

}

```

</CodeGroup>

Learn more about permissions →

</Tab>

<Tab title="Sessions">

Maintain context across multiple exchanges. Claude remembers files read, analysis done, and conversation history. Resume sessions later, or fork them to explore different approaches.

This example captures the session ID from the first query, then resumes to continue with full context:

<CodeGroup>

```python Python theme={null}

import asyncio

from claudeagentsdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage

async def main():

session_id = None

# First query: capture the session ID

async for message in query(

prompt="Read the authentication module",

options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),

):

if isinstance(message, SystemMessage) and message.subtype == "init":

sessionid = message.data["sessionid"]

# Resume with full context from the first query

async for message in query(

prompt="Now find all places that call it", # "it" = auth module

options=ClaudeAgentOptions(resume=session_id),

):

if isinstance(message, ResultMessage):

print(message.result)

asyncio.run(main())

```

```typescript TypeScript theme={null}

import { query } from "@anthropic-ai/claude-agent-sdk";

let sessionId: string | undefined;

// First query: capture the session ID

for await (const message of query({

prompt: "Read the authentication module",

options: { allowedTools: ["Read", "Glob"] }

})) {

if (message.type === "system" && message.subtype === "init") {

sessionId = message.session_id;

}

}

// Resume with full context from the first query

for await (const message of query({

prompt: "Now find all places that call it", // "it" = auth module

options: { resume: sessionId }

})) {

if ("result" in message) console.log(message.result);

}

```

</CodeGroup>

Learn more about sessions →

</Tab>

</Tabs>

Claude Code features

The SDK also supports Claude Code's filesystem-based configuration. With default options the SDK loads these from .claude/ in your working directory and ~/.claude/. To restrict which sources load, set setting_sources (Python) or settingSources (TypeScript) in your options.

FeatureDescriptionLocation
SkillsSpecialized capabilities defined in Markdown.claude/skills/*/SKILL.md
Slash commandsCustom commands for common tasks.claude/commands/*.md
MemoryProject context and instructionsCLAUDE.md or .claude/CLAUDE.md
PluginsExtend with custom commands, agents, and MCP serversProgrammatic via plugins option

Compare the Agent SDK to other Claude tools

The Claude Platform offers multiple ways to build with Claude. Here's how the Agent SDK fits in:

<Tabs>

<Tab title="Agent SDK vs Client SDK">

The Anthropic Client SDK gives you direct API access: you send prompts and implement tool execution yourself. The Agent SDK gives you Claude with built-in tool execution.

With the Client SDK, you implement a tool loop. With the Agent SDK, Claude handles it:

<CodeGroup>

```python Python theme={null}

# Client SDK: You implement the tool loop

response = client.messages.create(...)

while response.stopreason == "tooluse":

result = yourtoolexecutor(response.tool_use)

response = client.messages.create(tool_result=result, **params)

# Agent SDK: Claude handles tools autonomously

async for message in query(prompt="Fix the bug in auth.py"):

print(message)

```

```typescript TypeScript theme={null}

// Client SDK: You implement the tool loop

let response = await client.messages.create({ ...params });

while (response.stopreason === "tooluse") {

const result = yourToolExecutor(response.tool_use);

response = await client.messages.create({ tool_result: result, ...params });

}

// Agent SDK: Claude handles tools autonomously

for await (const message of query({ prompt: "Fix the bug in auth.ts" })) {

console.log(message);

}

```

</CodeGroup>

</Tab>

<Tab title="Agent SDK vs Claude Code CLI">

Same capabilities, different interface:

Use caseBest choice
----------------------------------
Interactive developmentCLI
CI/CD pipelinesSDK
Custom applicationsSDK
One-off tasksCLI
Production automationSDK

Many teams use both: CLI for daily development, SDK for production. Workflows translate directly between them.

</Tab>

<Tab title="Agent SDK vs Managed Agents">

Managed Agents is a hosted REST API: Anthropic runs the agent and the sandbox, and your application sends events and streams back results. The Agent SDK is a library that runs the agent loop inside your own process.

Agent SDKManaged Agents
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Runs inYour process, your infrastructureAnthropic-managed infrastructure
InterfacePython or TypeScript libraryREST API
Agent works onFiles on your infrastructureA managed sandbox per session
Session stateJSONL on your filesystemAnthropic-hosted event log
Custom toolsIn-process Python or TypeScript functionsClaude triggers the tool; you execute and return results
Best forLocal prototyping, agents that work directly on your filesystem and servicesProduction agents without operating sandbox or session infrastructure, long-running and asynchronous sessions

A common path is to prototype with the Agent SDK locally, then move to Managed Agents for production.

</Tab>

</Tabs>

Changelog

View the full changelog for SDK updates, bug fixes, and new features:

If you encounter bugs or issues with the Agent SDK:

For partners integrating the Claude Agent SDK, use of Claude branding is optional. When referencing Claude in your product:

Allowed:

Not permitted:

Your product should maintain its own branding and not appear to be Claude Code or any Anthropic product. For questions about branding compliance, contact the Anthropic sales team.

License and terms

Use of the Claude Agent SDK is governed by Anthropic's Commercial Terms of Service, including when you use it to power products and services that you make available to your own customers and end users, except to the extent a specific component or dependency is covered by a different license as indicated in that component's LICENSE file.

Next steps

<CardGroup cols={2}>

<Card title="Quickstart" icon="play" href="/en/agent-sdk/quickstart">

Build an agent that finds and fixes bugs in minutes

</Card>

<Card title="Example agents" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">

Email assistant, research agent, and more

</Card>

<Card title="TypeScript SDK" icon="code" href="/en/agent-sdk/typescript">

Full TypeScript API reference and examples

</Card>

<Card title="Python SDK" icon="code" href="/en/agent-sdk/python">

Full Python API reference and examples

</Card>

</CardGroup>