agent-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Agent SDK Guide

Claude Agent SDK 指南

Build custom AI agents powered by Claude. Same infrastructure as Claude Code.
构建基于Claude的自定义AI Agent。与Claude Code使用相同的基础设施。

Installation

安装

TypeScript

TypeScript

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

Python

Python

bash
pip install claude-agent-sdk
bash
pip install claude-agent-sdk

Core Features

核心功能

Context Management

上下文管理

Automatic compaction ensures your agent doesn't run out of context during extended operations.
自动压缩功能确保你的Agent在长时间操作中不会耗尽上下文。

Tool Ecosystem

工具生态系统

Built-in capabilities:
  • File operations - Read, write, edit files
  • Code execution - Run bash commands safely
  • Web search - Access real-time information
  • MCP extensibility - Add custom tools via Model Context Protocol
内置功能:
  • 文件操作 - 读取、写入、编辑文件
  • 代码执行 - 安全运行bash命令
  • 网页搜索 - 获取实时信息
  • MCP扩展性 - 通过Model Context Protocol添加自定义工具

Permission Controls

权限控制

typescript
{
  allowedTools: ['Read', 'Write', 'Bash'],  // Explicit allowlist
  disallowedTools: ['WebSearch'],            // Explicit blocklist
  permissionMode: 'default' | 'strict'       // Overall strategy
}
typescript
{
  allowedTools: ['Read', 'Write', 'Bash'],  // 显式允许列表
  disallowedTools: ['WebSearch'],            // 显式阻止列表
  permissionMode: 'default' | 'strict'       // 整体策略
}

Authentication Providers

身份验证提供商

Anthropic API (Default)

Anthropic API(默认)

bash
export ANTHROPIC_API_KEY=sk-ant-...
bash
export ANTHROPIC_API_KEY=sk-ant-...

Amazon Bedrock

Amazon Bedrock

bash
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_REGION=us-east-1
bash
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_REGION=us-east-1

Google Vertex AI

Google Vertex AI

bash
export CLAUDE_CODE_USE_VERTEX=1
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
export VERTEX_REGION=us-central1
export VERTEX_PROJECT_ID=your-project
bash
export CLAUDE_CODE_USE_VERTEX=1
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
export VERTEX_REGION=us-central1
export VERTEX_PROJECT_ID=your-project

Microsoft Foundry

Microsoft Foundry

bash
export CLAUDE_CODE_USE_FOUNDRY=1
bash
export CLAUDE_CODE_USE_FOUNDRY=1

Azure credentials configuration

Azure 凭据配置

undefined
undefined

File-Based Configuration

基于文件的配置

DirectoryPurpose
.claude/agents/
Subagent definitions (Markdown)
.claude/skills/
Skill files (
SKILL.md
)
.claude/commands/
Slash commands (Markdown)
.claude/settings.json
Hooks configuration
CLAUDE.md
Project memory/context
Enable project settings:
typescript
{
  settingSources: ['project']
}
目录用途
.claude/agents/
子Agent定义(Markdown格式)
.claude/skills/
Skill文件(
SKILL.md
.claude/commands/
斜杠命令(Markdown格式)
.claude/settings.json
钩子配置
CLAUDE.md
项目记忆/上下文
启用项目设置:
typescript
{
  settingSources: ['project']
}

Code Examples

代码示例

TypeScript: Basic Agent

TypeScript:基础Agent

typescript
import { Agent } from '@anthropic-ai/claude-agent-sdk';

const agent = new Agent({
  model: 'claude-sonnet-4-20250514',
  allowedTools: ['Read', 'Write', 'Bash'],
  systemPrompt: `You are a code review assistant.
    Analyze code for bugs, security issues, and best practices.`,
});

const result = await agent.run({
  prompt: 'Review the code in src/auth.ts for security issues',
});

console.log(result.output);
typescript
import { Agent } from '@anthropic-ai/claude-agent-sdk';

const agent = new Agent({
  model: 'claude-sonnet-4-20250514',
  allowedTools: ['Read', 'Write', 'Bash'],
  systemPrompt: `You are a code review assistant.
    Analyze code for bugs, security issues, and best practices.`,
});

const result = await agent.run({
  prompt: 'Review the code in src/auth.ts for security issues',
});

console.log(result.output);

TypeScript: Agent with MCP Tools

TypeScript:带MCP工具的Agent

typescript
import { Agent } from '@anthropic-ai/claude-agent-sdk';

const agent = new Agent({
  model: 'claude-sonnet-4-20250514',
  mcpServers: {
    database: {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-postgres'],
      env: { DATABASE_URL: process.env.DATABASE_URL },
    },
  },
});

const result = await agent.run({
  prompt: 'List all users who signed up in the last 24 hours',
});
typescript
import { Agent } from '@anthropic-ai/claude-agent-sdk';

const agent = new Agent({
  model: 'claude-sonnet-4-20250514',
  mcpServers: {
    database: {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-postgres'],
      env: { DATABASE_URL: process.env.DATABASE_URL },
    },
  },
});

const result = await agent.run({
  prompt: 'List all users who signed up in the last 24 hours',
});

Python: Basic Agent

Python:基础Agent

python
from claude_agent_sdk import Agent

agent = Agent(
    model="claude-sonnet-4-20250514",
    allowed_tools=["Read", "Write", "Bash"],
    system_prompt="""You are a code review assistant.
    Analyze code for bugs, security issues, and best practices.""",
)

result = agent.run(
    prompt="Review the code in src/auth.py for security issues"
)

print(result.output)
python
from claude_agent_sdk import Agent

agent = Agent(
    model="claude-sonnet-4-20250514",
    allowed_tools=["Read", "Write", "Bash"],
    system_prompt="""You are a code review assistant.
    Analyze code for bugs, security issues, and best practices.""",
)

result = agent.run(
    prompt="Review the code in src/auth.py for security issues"
)

print(result.output)

Python: Agent with Custom Permissions

Python:带自定义权限的Agent

python
from claude_agent_sdk import Agent, PermissionMode

agent = Agent(
    model="claude-sonnet-4-20250514",
    permission_mode=PermissionMode.STRICT,
    allowed_tools=["Read", "Grep", "Glob"],
    disallowed_tools=["Bash"],  # Extra safety
)

result = agent.run(
    prompt="Find all TODO comments in the codebase"
)
python
from claude_agent_sdk import Agent, PermissionMode

agent = Agent(
    model="claude-sonnet-4-20250514",
    permission_mode=PermissionMode.STRICT,
    allowed_tools=["Read", "Grep", "Glob"],
    disallowed_tools=["Bash"],  # 额外安全措施
)

result = agent.run(
    prompt="Find all TODO comments in the codebase"
)

Agent Types & Use Cases

Agent类型与使用场景

Coding Agents

编码Agent

  • SRE Diagnostics - Analyze logs, identify issues, suggest fixes
  • Security Auditing - Scan for vulnerabilities, check dependencies
  • Incident Triage - Correlate alerts, gather context, draft runbooks
  • Code Review - Enforce standards, catch bugs, suggest improvements
  • SRE诊断 - 分析日志、识别问题、建议修复方案
  • 安全审计 - 扫描漏洞、检查依赖项
  • 事件分类 - 关联警报、收集上下文、草拟运行手册
  • 代码审查 - 执行标准、捕获bug、提出改进建议

Business Agents

业务Agent

  • Legal Review - Analyze contracts, flag risks, summarize terms
  • Financial Analysis - Process reports, identify anomalies, forecast
  • Customer Support - Handle tickets, route issues, draft responses
  • Content Creation - Generate docs, edit copy, ensure consistency
  • 法律审查 - 分析合同、标记风险、总结条款
  • 财务分析 - 处理报告、识别异常、进行预测
  • 客户支持 - 处理工单、路由问题、草拟回复
  • 内容创作 - 生成文档、编辑文案、确保一致性

Best Practices

最佳实践

Start Simple

从简开始

Begin with minimal tool access and expand as needed:
typescript
// Start here
allowedTools: ['Read']

// Then add as required
allowedTools: ['Read', 'Grep', 'Glob']

// Only if truly needed
allowedTools: ['Read', 'Write', 'Bash']
从最小的工具访问权限开始,根据需要逐步扩展:
typescript
// 初始配置
allowedTools: ['Read']

// 按需添加
allowedTools: ['Read', 'Grep', 'Glob']

// 仅在确实需要时添加
allowedTools: ['Read', 'Write', 'Bash']

Use Subagents for Complex Tasks

使用子Agent处理复杂任务

Break large tasks into specialized subagents:
.claude/agents/
├── code-reviewer.md      # Reviews code changes
├── test-writer.md        # Generates tests
└── doc-generator.md      # Creates documentation
将大型任务拆分为专门的子Agent:
.claude/agents/
├── code-reviewer.md      # 审查代码变更
├── test-writer.md        # 生成测试用例
└── doc-generator.md      # 创建文档

Handle Errors Gracefully

优雅处理错误

typescript
try {
  const result = await agent.run({ prompt });
  if (result.error) {
    console.error('Agent error:', result.error);
  }
} catch (error) {
  console.error('SDK error:', error);
}
typescript
try {
  const result = await agent.run({ prompt });
  if (result.error) {
    console.error('Agent error:', result.error);
  }
} catch (error) {
  console.error('SDK error:', error);
}

Monitor Agent Behavior

监控Agent行为

typescript
const agent = new Agent({
  onToolUse: (tool, input) => {
    console.log(`Tool: ${tool}, Input: ${JSON.stringify(input)}`);
  },
  onThinking: (thought) => {
    console.log(`Thinking: ${thought}`);
  },
});
typescript
const agent = new Agent({
  onToolUse: (tool, input) => {
    console.log(`Tool: ${tool}, Input: ${JSON.stringify(input)}`);
  },
  onThinking: (thought) => {
    console.log(`Thinking: ${thought}`);
  },
});

Project Scaffolding

项目脚手架

Use
/agent-sdk:agent-scaffold
command to generate a new project.
使用
/agent-sdk:agent-scaffold
命令生成新项目。

Template Files

模板文件

TemplatePurpose
assets/typescript/package.json
Node.js package config
scripts/typescript/agent.ts
TypeScript agent entry
assets/python/pyproject.toml
Python package config
scripts/python/agent.py
Python agent entry
assets/env-*.example
Provider config templates
references/claude/*.md
Subagent/skill/command templates
模板用途
assets/typescript/package.json
Node.js包配置
scripts/typescript/agent.ts
TypeScript Agent入口
assets/python/pyproject.toml
Python包配置
scripts/python/agent.py
Python Agent入口
assets/env-*.example
提供商配置模板
references/claude/*.md
子Agent/Skill/命令模板

Tool Mapping

工具映射

User SelectionSDK Tools
File OperationsRead, Write, Edit, Glob, Grep
Code ExecutionBash
Web SearchWebSearch, WebFetch
MCP Tools(configured via mcpServers)
用户选择SDK工具
文件操作Read, Write, Edit, Glob, Grep
代码执行Bash
网页搜索WebSearch, WebFetch
MCP工具通过mcpServers配置

System Prompts

系统提示词

Coding Agent:
You are a coding assistant that helps developers write better code.
Analyze code for bugs, security issues, and best practices.
Business Agent:
You are a business analyst assistant.
Help with document analysis, data extraction, and report generation.
编码Agent:
You are a coding assistant that helps developers write better code.
Analyze code for bugs, security issues, and best practices.
业务Agent:
You are a business analyst assistant.
Help with document analysis, data extraction, and report generation.

Resources

资源