文档索引
在此获取完整文档索引: https://code.claude.com/docs/llms.txt 使用此文件发现所有可用页面,然后再进一步探索。
在 SDK 中使用 Claude Code 功能
将项目指令、技能、钩子及其他 Claude Code 功能加载到您的 SDK 智能体中。
Agent SDK 构建在与 Claude Code 相同的基础之上,这意味着您的 SDK 智能体可以访问相同的基于文件系统的功能:项目指令(CLAUDE.md 和规则)、技能、钩子等。
当您省略 settingSources 时,query() 会读取与 Claude Code CLI 相同的文件系统设置:用户、项目和本地设置、CLAUDE.md 文件以及 .claude/ 下的技能、智能体和命令。要在没有这些设置的情况下运行,请传递 settingSources: [],这会将智能体限制为您通过编程方式配置的内容。托管策略设置和全局 ~/.claude.json 配置不受此选项影响,始终会被读取。请参阅 settingSources 不控制的内容。
有关每项功能的作用及使用时机的概念概述,请参阅扩展 Claude Code。
使用 settingSources 控制文件系统设置
setting sources 选项(Python 中的 setting_sources,TypeScript 中的 settingSources)控制 SDK 加载哪些基于文件系统的设置。传递显式列表以选择特定来源,或传递空数组以禁用用户、项目和本地设置。
此示例通过将 settingSources 设置为 ["user", "project"] 来加载用户级和项目级设置:
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async for message in query(
prompt="Help me refactor the auth module",
options=ClaudeAgentOptions(
# "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.
# Together they give the agent access to CLAUDE.md, skills, hooks, and
# permissions from both locations.
setting_sources=["user", "project"],
allowed_tools=["Read", "Edit", "Bash"],
),
):
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text)
if isinstance(message, ResultMessage) and message.subtype == "success":
print(f"\nResult: {message.result}")
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Help me refactor the auth module",
options: {
// "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.
// Together they give the agent access to CLAUDE.md, skills, hooks, and
// permissions from both locations.
settingSources: ["user", "project"],
allowedTools: ["Read", "Edit", "Bash"]
}
})) {
if (message.type === "assistant") {
for (const block of message.message.content) {
if (block.type === "text") console.log(block.text);
}
}
if (message.type === "result" && message.subtype === "success") {
console.log(`\nResult: ${message.result}`);
}
}
每个来源从特定位置加载设置,其中 <cwd> 是您通过 cwd 选项传递的工作目录,如果未设置则为进程的当前目录。有关完整的类型定义,请参阅 SettingSource(TypeScript)或 SettingSource(Python)。
| 来源 | 加载内容 | 位置 |
|---|---|---|
"project" | 项目 CLAUDE.md、.claude/rules/*.md、项目技能、项目钩子、项目 settings.json | <cwd>/.claude/ 用于 settings.json 和钩子;<cwd> 及每个父目录用于 CLAUDE.md 和规则;<cwd> 及向上至仓库根目录的每个父目录用于技能 |
"user" | 用户 CLAUDE.md、~/.claude/rules/*.md、用户技能、用户设置 | ~/.claude/ |
"local" | CLAUDE.local.md、.claude/settings.local.json | <cwd>/.claude/ 用于 settings.local.json;<cwd> 及每个父目录用于 CLAUDE.local.md |
省略 settingSources 等同于 ["user", "project", "local"]。
cwd 选项决定 SDK 在哪里查找项目级输入。CLAUDE.md 和规则从 <cwd> 及每个父目录加载。技能从 <cwd> 及向上至仓库根目录的每个父目录加载。项目 settings.json 和钩子仅从 <cwd>/.claude/ 加载,不会回退到父目录。
settingSources 不控制的内容
settingSources 覆盖用户、项目和本地设置。无论其值如何,以下输入都会被读取:
| 输入 | 行为 | 禁用方式 |
|---|---|---|
| 托管策略设置 | 主机上存在时始终加载 | 移除托管设置文件 |
~/.claude.json 全局配置 | 始终读取 | 使用 env 中的 CLAUDE_CONFIG_DIR 重新定位 |
~/.claude/projects/<project>/memory/ 中的自动记忆 | 默认加载到系统提示中 | 在设置中设置 autoMemoryEnabled: false,或在 env 中设置 CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 |
不要依赖默认的 query() 选项进行多租户隔离。由于上述输入不受 settingSources 控制,SDK 进程可能会获取主机级配置和按目录存储的记忆。对于多租户部署,请在各自的文件系统中运行每个租户,并设置 settingSources: [] 以及在 env 中设置 CLAUDE_CODE_DISABLE_AUTO_MEMORY=1。请参阅安全部署。
项目指令(CLAUDE.md 和规则)
CLAUDE.md 文件和 .claude/rules/*.md 文件为您的智能体提供有关项目的持久上下文:编码规范、构建命令、架构决策和指令。当 settingSources 包含 "project"(如上面的示例)时,SDK 会在会话开始时将这些文件加载到上下文中。然后,智能体会遵循您的项目规范,无需您在每个提示中重复说明。
CLAUDE.md 加载位置
| 级别 | 位置 | 加载时机 |
|---|---|---|
| 项目(根目录) | <cwd>/CLAUDE.md 或 <cwd>/.claude/CLAUDE.md | settingSources 包含 "project" |
| 项目规则 | <cwd>/.claude/rules/*.md 及每个父目录中的 .claude/rules/*.md | settingSources 包含 "project" |
| 项目(父目录) | cwd 上方目录中的 CLAUDE.md 文件 | settingSources 包含 "project",在会话开始时加载 |
| 项目(子目录) | cwd 子目录中的 CLAUDE.md 文件 | settingSources 包含 "project",在智能体读取该子树中的文件时按需加载 |
| 本地 | <cwd>/CLAUDE.local.md 及每个父目录中的 CLAUDE.local.md | settingSources 包含 "local" |
| 用户 | ~/.claude/CLAUDE.md | settingSources 包含 "user" |
| 用户规则 | ~/.claude/rules/*.md | settingSources 包含 "user" |
所有级别是累加的:如果项目和用户 CLAUDE.md 文件都存在,智能体将同时看到两者。级别之间没有硬性优先规则;如果指令冲突,结果取决于 Claude 如何解释它们。编写不冲突的规则,或在更具体的文件中明确说明优先级("这些项目指令覆盖任何冲突的用户级默认值")。
您也可以通过 systemPrompt 直接注入上下文,而无需使用 CLAUDE.md 文件。请参阅修改系统提示。当您希望相同的上下文在交互式 Claude Code 会话和 SDK 智能体之间共享时,请使用 CLAUDE.md。
有关如何构建和组织 CLAUDE.md 内容,请参阅管理 Claude 的记忆。
技能
技能是 markdown 文件,为您的智能体提供专业知识和可调用的工作流。与 CLAUDE.md(每次会话都加载)不同,技能按需加载。智能体在启动时接收技能描述,并在相关时加载完整内容。
技能通过 settingSources 从文件系统发现。当 query() 上的 skills 选项被省略时,发现的用户和项目技能将被启用,Skill 工具可用,与 CLI 行为匹配。要控制启用哪些技能,请将 skills 传递为 "all"、技能名称列表或 [] 以禁用所有技能。当设置了 skills 时,SDK 会自动启用 Skill 工具,因此您不需要将其添加到 allowedTools。
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
# Skills in .claude/skills/ are discovered automatically
# when settingSources includes "project"
async for message in query(
prompt="Review this PR using our code review checklist",
options=ClaudeAgentOptions(
setting_sources=["user", "project"],
skills="all",
allowed_tools=["Read", "Grep", "Glob"],
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
import { query } from "@anthropic-ai/claude-agent-sdk";
// Skills in .claude/skills/ are discovered automatically
// when settingSources includes "project"
for await (const message of query({
prompt: "Review this PR using our code review checklist",
options: {
settingSources: ["user", "project"],
skills: "all",
allowedTools: ["Read", "Grep", "Glob"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
技能必须作为文件系统工件创建(.claude/skills/<name>/SKILL.md)。SDK 没有用于注册技能的编程 API。有关完整详情,请参阅 SDK 中的智能体技能。
有关创建和使用技能的更多信息,请参阅 SDK 中的智能体技能。
钩子
SDK 支持两种定义钩子的方式,它们并行运行:
- 文件系统钩子: 在
settings.json中定义的 shell 命令,当settingSources包含相关来源时加载。这些与您为交互式 Claude Code 会话配置的钩子相同。 - 编程钩子: 直接传递给
query()的回调函数。它们在您的应用程序进程中运行,可以返回结构化决策。请参阅使用钩子控制执行。
两种类型在相同的钩子生命周期中执行。如果您的项目 .claude/settings.json 中已有钩子,并且您设置了 settingSources: ["project"],这些钩子会在 SDK 中自动运行,无需额外配置。
钩子回调接收工具输入并返回决策字典。返回 {}(空字典)表示允许工具继续执行。返回 {"decision": "block", "reason": "..."} 会阻止执行,原因会作为工具结果发送给 Claude。有关完整的回调签名和返回类型,请参阅钩子指南。
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, ResultMessage
# PreToolUse hook callback. Positional args:
# input_data: HookInput dict with tool_name, tool_input, hook_event_name
# tool_use_id: str | None, the ID of the tool call being intercepted
# context: HookContext, carries session metadata
async def audit_bash(input_data, tool_use_id, context):
command = input_data.get("tool_input", {}).get("command", "")
if "rm -rf" in command:
return {"decision": "block", "reason": "Destructive command blocked"}
return {} # Empty dict: allow the tool to proceed
# Filesystem hooks from .claude/settings.json run automatically
# when settingSources loads them. You can also add programmatic hooks:
async for message in query(
prompt="Refactor the auth module",
options=ClaudeAgentOptions(
setting_sources=["project"], # Loads hooks from .claude/settings.json
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[audit_bash]),
]
},
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
import { query, type HookInput, type HookJSONOutput } from "@anthropic-ai/claude-agent-sdk";
// PreToolUse hook callback. HookInput is a discriminated union on
// hook_event_name, so narrowing on it gives TypeScript the right
// tool_input shape for this event.
const auditBash = async (input: HookInput): Promise<HookJSONOutput> => {
if (input.hook_event_name !== "PreToolUse") return {};
const toolInput = input.tool_input as { command?: string };
if (toolInput.command?.includes("rm -rf")) {
return { decision: "block", reason: "Destructive command blocked" };
}
return {}; // Empty object: allow the tool to proceed
};
// Filesystem hooks from .claude/settings.json run automatically
// when settingSources loads them. You can also add programmatic hooks:
for await (const message of query({
prompt: "Refactor the auth module",
options: {
settingSources: ["project"], // Loads hooks from .claude/settings.json
hooks: {
PreToolUse: [{ matcher: "Bash", hooks: [auditBash] }]
}
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
何时使用哪种钩子类型
| 钩子类型 | 最适合 |
|---|---|
文件系统(settings.json) | 在 CLI 和 SDK 会话之间共享钩子。支持 "command"(shell 脚本)、"http"(POST 到端点)、mcp_tool(调用已连接 MCP 服务器的工具)、"prompt"(LLM 评估提示)和 "agent"(生成验证智能体)。这些在主智能体及其生成的任何子智能体中触发。 |
编程(query() 中的回调) | 应用程序特定逻辑;返回结构化决策;进程内集成。仅限于主会话。 |
TypeScript SDK 支持 Python 之外的额外钩子事件,包括 SessionStart、SessionEnd、TeammateIdle 和 TaskCompleted。有关完整的事件兼容性表,请参阅钩子指南。
有关编程钩子的完整详情,请参阅使用钩子控制执行。有关文件系统钩子语法,请参阅钩子。
选择正确的功能
Agent SDK 为您提供了多种扩展智能体行为的方式。如果您不确定使用哪种方式,此表格将常见目标映射到正确的方法。
| 您想要... | 使用 | SDK 接口 |
|---|---|---|
| 设置智能体始终遵循的项目规范 | CLAUDE.md | settingSources: ["project"] 自动加载 |
| 给智能体在相关时加载的参考资料 | 技能 | settingSources + skills 选项 |
| 运行可复用的工作流(部署、审查、发布) | 用户可调用的技能 | settingSources + skills 选项 |
| 将隔离的子任务委派给新上下文(研究、审查) | 子智能体 | agents 参数 + allowedTools: ["Agent"] |
| 使用共享任务列表和直接智能体间消息协调多个 Claude Code 实例 | 智能体团队 | 不能通过 SDK 选项直接配置。智能体团队是 CLI 功能,其中一个会话作为团队负责人,协调独立队友之间的工作 |
| 在工具调用上运行确定性逻辑(审计、阻止、转换) | 钩子 | hooks 参数配合回调,或通过 settingSources 加载的 shell 脚本 |
| 让 Claude 通过结构化工具访问外部服务 | MCP | mcpServers 参数 |
您启用的每个功能都会增加智能体的上下文窗口。有关每个功能的成本以及这些功能如何叠加,请参阅扩展 Claude Code。