运行时依赖
安装命令
点击复制技能文档
Claude Code Agent SDK 使用 Claude Code 作为库构建生产级 AI 代理。支持 Python 和 TypeScript。
涵盖以下内容: Quickstart 和设置 代理循环和消息类型 工具配置和内置工具 拦截代理行为的 Hooks 会话管理(resume、fork、continue) MCP 服务器集成 子代理和并行执行 权限和安全 自定义工具、流式输出和结构化输出 成本跟踪和可观测性 Claude Code 功能(skills、commands、memory) 托管和部署 Python 和 TypeScript API 参考
快速导航 参考文件按主题分割在 references/ 目录中。 只加载需要的内容: Core overview.md — SDK 概览、安装、认证、内置工具、权限模式 quickstart.md — 快速开始:构建 bug 修复代理 agent-loop.md — 代理循环:消息类型、工具执行、上下文窗口、压缩 Agent Control hooks.md — Hooks:PreToolUse/PostToolUse/Stop 等、匹配器、回调函数 permissions.md — 权限:allowedTools/disallowedTools、权限模式 user-input.md — 用户输入:批准提示、AskUserQuestion Sessions & State sessions.md — 会话管理:continue/resume/fork、ClaudeSDKClient file-checkpointing.md — 文件检查点:跟踪和还原文件更改 Tools & Integration custom-tools.md — 自定义工具:进程内 MCP 服务器 mcp.md — MCP:连接外部工具 + 工具搜索扩展到数千工具 Sub-agents & Parallelism subagents.md — 子代理:AgentDefinition、上下文隔离、并行任务 + 待办事项跟踪 Streaming & Output streaming-output.md — 流式响应 + 输入模式 + 结构化输出(JSON Schema/Zod/Pydantic) Configuration & Features claude-code-features.md — Claude Code 功能:settingSources、CLAUDE.md、skills modifying-system-prompts.md — 系统提示:claude_code 预设 vs 自定义 skills.md — Agent Skills slash-commands.md — 斜杠命令 plugins.md — 插件系统 Operations hosting.md — 托管 + 安全部署:Docker、云、CI/CD、隔离、凭证管理 cost-tracking.md — 成本跟踪:token 使用、预算 observability.md — 可观测性:OpenTelemetry migration-guide.md — 迁移指南 API Reference python.md — Python SDK API 参考 typescript.md — TypeScript SDK API 参考(含 V2 弃用说明)
关键模式 基本代理
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Fix the bug in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"])
):
print(message)
带有 Hooks 的选项
options = ClaudeAgentOptions(
hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[validate_command])]}
)
带有 MCP 服务器的选项
options = ClaudeAgentOptions(
mcp_servers={"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}}
)
带有子代理的选项
options = ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Agent"],
agents={"reviewer": AgentDefinition(
description="Code reviewer",
prompt="Review code quality",
tools=["Read", "Glob", "Grep"]
)}
)
多回合会话
async with ClaudeSDKClient(options=options) as client:
await client.query("Analyze the auth module")
async for msg in client.receive_response():
print(msg)
await client.query("Now refactor it") # auto-continues
async for msg in client.receive_response():
print(msg)