用钩子拦截与控制智能体行为
介绍智能体 SDK 中钩子机制的事件触发、匹配器过滤与回调配置方式,说明输入输出字段如何控制工具调用,并给出拒绝工具调用、多工具匹配过滤及超时处理等实践要点。
Hooks 是针对代理事件运行您的代码的调用功能, 就像一个被调用的工具, 一个会话开始, 或者执行停止。 通过钩子, 您可以: - **B. 封锁危险行动** 执行前, 如破坏性 shell 命令或未经授权的文件访问 - **记录和审计** 工具要求遵守、调试或分析 - **投入和产出的转变** 用于消毒数据、注入证书或重定向文件路径 - **需要人类批准** 用于数据库写入或 API 呼叫等敏感动作 - **跟踪会话生命周期** 用于管理状态、清理资源或发送通知 ## 钩子是怎样工作的 1 一个事件火灾 代理执行期间发生一些事件, 并且SDK 点火事件: 一个工具即将被调用(`PreToolUse`),一个工具返回结果(`PostToolUse`),一个子代理启动或停止,代理闲置,或执行完毕。 [全部事件列表](<https://code.claude.com/docs/en/agent-sdk/hooks#available-hooks>). 2 SDK 收集注册钩 用于该事件类型注册的钩子的 SDK 检查。 其中包括您通过的回调钩 `options.hooks` 和来自设置文件的 shell 命令钩钩, 当相应的 [`settingSources`](<https://code.claude.com/docs/en/agent-sdk/typescript#settingsource>) 或 时 间 [`setting_sources`](<https://code.claude.com/docs/en/agent-sdk/python#settingsource>) 已启用条目, 用于默认 `query()` 选项。 3 钩子运行的匹配器过滤器 如果钩子有 [`matcher`](<https://code.claude.com/docs/en/agent-sdk/hooks#matchers>) 模式( 如 `"Write|Edit"`),SDK对照事件的目标进行测试(例如工具名称). Hooks没有匹配器就运行于该类型的每个事件. 4 回调函数已执行 每个匹配的钩子 [回调函数](<https://code.claude.com/docs/en/agent-sdk/hooks#callback-functions>) 接收关于正在发生的情况的输入:工具名称、其参数、会话 ID 和其他特定事件的细节。 5 您的回调返回一个决定 执行任何操作( logb, API 调用, 校验)后, 您的回调返回 a [输出对象](<https://code.claude.com/docs/en/agent-sdk/hooks#outputs>) 告诉代理人该怎么做:允许操作,屏蔽它,修改输入,或者在对话中注入上下文。 此示例登记 a `PreToolUse` 钩(步骤 1 ) `"Write|Edit"` 匹配器( step 3 ) , 因此 Write 和 Edit 工具的回调点火。 当触发时, 回调器接收工具的输入( step 4 ) , 请检查文件路径是否针对 a `.env` 文件,并返回 `permissionDecision: "deny"` 以屏蔽操作( 步骤 5 ): ``` import asyncio from claude_agent_sdk import ( AssistantMessage, ClaudeSDKClient, ClaudeAgentOptions, HookMatcher, ResultMessage, ) # Define a hook callback that receives tool call details async def protect_env_files(input_data, tool_use_id, context): # Extract the file path from the tool's input arguments file_path = input_data["tool_input"].get("file_path", "") file_name = file_path.split("/")[-1] # Block the operation if targeting a .env file if file_name.lower() == ".env": return { "hookSpecificOutput": { "hookEventName": input_data["hook_event_name"], "permissionDecision": "deny", "permissionDecisionReason": "Cannot modify .env files", } } # Empty object: no decision, normal permissions apply return {} async def main(): options = ClaudeAgentOptions( hooks={ # Register the hook for PreToolUse events # The matcher filters to only Write and Edit tool calls "PreToolUse": [HookMatcher(matcher="Write|Edit", hooks=[protect_env_files])] } ) async with ClaudeSDKClient(options=options) as client: await client.query("Create a .env file with the standard local development database configuration") async for message in client.receive_response(): # Filter for assistant and result messages if isinstance(message, (AssistantMessage, ResultMessage)): print(message) asyncio.run(main()) ``` ``` import { query, HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk"; // Define a hook callback with the HookCallback type const protectEnvFiles: HookCallback = async (input, toolUseID, { signal }) => { // Cast input to the specific hook type for type safety const preInput = input as PreToolUseHookInput; // Cast tool_input to access its properties (typed as unknown in the SDK) const toolInput = preInput.tool_input as Record<string, unknown>; const filePath = toolInput?.file_path as string; const fileName = filePath?.split("/").pop(); // Block the operation if targeting a .env file if (fileName?.toLowerCase() === ".env") { return { hookSpecificOutput: { hookEventName: preInput.hook_event_name, permissionDecision: "deny", permissionDecisionReason: "Cannot modify .env files" } }; } // Empty object: no decision, normal permissions apply return {}; }; for await (const message of query({ prompt: "Create a .env file with the standard local development database configuration", options: { hooks: { // Register the hook for PreToolUse events // The matcher filters to only Write and Edit tool calls PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnvFiles] }] } } })) { // Filter for assistant and result messages if (message.type === "assistant" || message.type === "result") { console.log(message); } } ``` 钩子拒绝使用 Write 或 Edit 调用 `file_path` 结尾为 `/.env`在任何信件中。 `file_path` 使用后鞭打,例如: `C:\project\.env`,而这个钩子不会阻断一个写入或编辑呼叫 `C:\project\.env`. 那个... `Write|Edit` 匹配者将这个钩子限制在 Write 和 Edit 工具中。如果 Claude 写 `.env` 使用 Bash 命令时, 钩子不会运行 。 要屏蔽 Bash 写入文件 。 [沙盒运行](<https://code.claude.com/docs/en/sandboxing>),参见沙盒配置 [Python 键](<https://code.claude.com/docs/en/agent-sdk/python#sandbox-configuration>) 或 时 间 [TypeScript](<https://code.claude.com/docs/en/agent-sdk/typescript#sandbox-configuration>). ## 可用钩子 SDK为代理执行的不同阶段提供钩子,有些钩子在两种SDK中都可以使用,而有些钩子只有TypeScript. | 钩子事件 | Python SDK (英语). | TypeScript SDK | 是什么触发了它 | 示例使用大小写 | | --- | --- | --- | --- | --- | | `PreToolUse` | 对 | 对 | 工具调用请求( 可屏蔽或修改) | 屏蔽危险贝壳命令 | | `PostToolUse` | 对 | 对 | 工具执行结果 | 日志文件更改为审计线索 | | `PostToolUseFailure` | 对 | 对 | 工具执行失败 | 处理或日志工具错误 | | `PostToolBatch` | 没有 | 对 | 一整批工具调用解决了,每批一次在下次模式调用之前 | 整个批次的注入公约一次 | | [`UserPromptSubmit`](<https://code.claude.com/docs/en/hooks#userpromptsubmit>) | 对 | 对 | 提交一个提示, 包括一个回合 Claude 代码 开始自己的 | 将附加上下文注入提示 | | [`UserPromptExpansion`](<https://code.claude.com/docs/en/hooks#userpromptexpansion>) | 没有 | 对 | 一个用户类型的命令,或者一个MCP 提示,在它到达克劳德之前会扩展成一个提示。当克劳德自己引用一个技能时,不会开火 。 | 当一个技能被键入时, 屏蔽一个直接引用或添加上下文的命令 | | `MessageDisplay` | 没有 | 对 | 一旦每条消息带有完整的消息文本, 便会完成一个带有文本的助理消息 | 在不更改记录的情况下重写已显示文本 | | `Stop` | 对 | 对 | 代理执行停止 | 退出前保存会话状态 | | `StopFailure` | 没有 | 对 | 转弯结束为 API 错误而不是正常的停止 | 日志失败或发送提醒 | | `SubagentStart` | 对 | 对 | 亚剂初始化 | 跟踪并行任务产卵 | | `SubagentStop` | 对 | 对 | 副剂完成 | 并行任务的总结果 | | `PreCompact` | 对 | 对 | 对话压缩请求 | 在总结前存档完整记录 | | `PostCompact` | 没有 | 对 | 对话压缩完成 | 记录生成的摘要 | | [`PreModelSwitch`](<https://code.claude.com/docs/en/hooks#premodelswitch>) | 没有 | 对 | 请求的型号开关, 在它发生之前( 可屏蔽) | 块切换到特定模式 | | [`PostModelSwitch`](<https://code.claude.com/docs/en/hooks#postmodelswitch>) | 没有 | 对 | 会议模式的改变,包括自动退缩 | 为新模式提供克洛德模式特有的指导 | | `PermissionRequest` | 对 | 对 | 工具调用需要权限决定 | 自定义权限处理 | | `PermissionDenied` | 没有 | 对 | 自动模式拒绝一个工具调用, 包括没有分类器判定的拒绝 | 日志拒绝, 或者告诉模型它可能会重试; Claude Code 忽略 `retry: true` 以无证的否认为理由。 [PermissionDenied](<https://code.claude.com/docs/en/hooks#permissiondenied>) | | `SessionStart` | 没有 | 对 | 会话初始化 | 初始化记录和遥测 | | `SessionEnd` | 没有 | 对 | 会话终止 | 清理临时资源 | | `Notification` | 对 | 对 | 代理状态消息 | 向 Slack 或 PagerDuty 发送代理服务器状态更新 | | `Setup` | 没有 | 对 | 会话设置/维护 | 运行初始化任务 | | `TeammateIdle` | 没有 | 对 | 队友变得空闲 | 重新安排工作或通知 | | `TaskCreated` | 没有 | 对 | 任务通过 `TaskCreate` 工具 | 执行任务命名公约 | | [`TaskCompleted`](<https://code.claude.com/docs/en/hooks#taskcompleted>) | 没有 | 对 | 任务已标记完成 | 任务结束前需要通过测试 | | `Elicitation` | 没有 | 对 | 一个 MCP 服务器请求用户在任务中间输入 | 响应 MCP 输入请求程序 | | `ElicitationResult` | 没有 | 对 | 一个用户响应了 MCP 诱导 | 在返回服务器前修改或屏蔽回复 | | `ConfigChange` | 没有 | 对 | 配置文件更改 | 动态重新装入设置 | | `InstructionsLoaded` | 没有 | 对 | A `CLAUDE.md` 或规则文件装入上下文 | 审计哪些指令文件加载 | | `WorktreeCreate` | 没有 | 对 | Claude Code需要一条工作树 钩子会创造它而不是Git | 创建工作树并返回路径 [`hookSpecificOutput.worktreePath`](<https://code.claude.com/docs/en/hooks#worktreecreate-output>) | | `WorktreeRemove` | 没有 | 对 | 由一棵工作树所创造 `WorktreeCreate` 钩子正在被移除 | 清理工作空间资源 | | `CwdChanged` | 没有 | 对 | 会话中工作目录的更改 | 每个目录重新装入环境变量 | | `FileChanged` | 没有 | 对 | 被监视的文件被修改、创建或删除 | 项目文件更改时重新加载配置 | | `DirectoryAdded` | 没有 | 对 | 在会话中添加一个工作目录 | 安装添加到会话中段的寄存器的依赖性 | ## 配置钩子 要配置钩子,请在 `hooks` 您代理选项的字段( Y)`ClaudeAgentOptions` 在Python语中, `options` 对象在 TypeScript 中。此片段假设您已经定义了钩调回, 如 `protect_env_files` 以 Python 键或 `protectEnvFiles` 在TypeScript中,从上面的例子: ``` options = ClaudeAgentOptions( hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[my_callback])]} ) async with ClaudeSDKClient(options=options) as client: await client.query("Your prompt") async for message in client.receive_response(): print(message) ``` ``` for await (const message of query({ prompt: "Your prompt", options: { hooks: { PreToolUse: [{ matcher: "Bash", hooks: [myCallback] }] } } })) { console.log(message); } ``` 那个... `hooks` 选项是 Python 中的词典或 TypeScript 中的对象,其中: - **密钥**: [钩状事件名称](<https://code.claude.com/docs/en/agent-sdk/hooks#available-hooks>) 例如, `'PreToolUse'`, `'PostToolUse'`,以及 `'Stop'` - **数值**: 数组 [匹配点](<https://code.claude.com/docs/en/agent-sdk/hooks#matchers>),每个包含可选过滤模式和您的 [回调函数](<https://code.claude.com/docs/en/agent-sdk/hooks#callback-functions>) ### 匹配者 使用匹配器来过滤您召回的信号 。 `matcher` 字段比对不同的值,视钩子事件类型而定。例如,基于工具的钩子比对工具名称,而 `Notification` 钩子与通知类型匹配。 SDK 匹配者遵循相同的规则 [设置文件中的匹配者](<https://code.claude.com/docs/en/hooks#matcher-patterns>)。该节记录了准确的字符串和正则表达式评价路径、其版本要求以及每种事件类型的匹配值。 | 选项 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | `matcher` | `string` | `undefined` | 与事件过滤字段相匹配的图案 [设置文件中匹配者的规则](<https://code.claude.com/docs/en/hooks#matcher-patterns>)。对于工具钩,该字段是工具名称。内建工具包括 `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`以及其他人。 [工具输入类型](<https://code.claude.com/docs/en/agent-sdk/typescript#tool-input-types>) 。 MCP 工具使用图案 `mcp__<server>__<action>`时, `<server>` 是您在其中使用的密钥 `mcpServers` 配置, 拼写为 [工具命名公约](<https://code.claude.com/docs/en/agent-sdk/mcp#tool-naming-convention>) 描述。 | | `hooks` | `HookCallback[]` | - | 需要。 当模式匹配时需要执行的调用函数矩阵 | | `timeout` | `number` | `undefined` | 以秒计的超时。省略时, Claude Code 应用 [事件默认超时](<https://code.claude.com/docs/en/agent-sdk/hooks#hook-timeout>)您的 SDK 调用 `command` 钩子默认值 | | `onFailure` | `"continue" \| "block"` | `undefined` | 一个失败的回话会做什么。 设置 `"block"` 改为: [当召回失败时屏蔽动作](<https://code.claude.com/docs/en/agent-sdk/hooks#block-the-action-when-a-callback-fails>)在 Python 中,使用 `on_failure` | 使用该 `matcher` 模式,尽可能针对特定工具。 `'Bash'` matcher, 您的回调运行到 Bash 命令。 在 Claude Code v2.1.314 上, 它们也会运行到 `PreToolUse` 财务报告和财务报告 `PermissionRequest` 用于监视器命令, 它们是 [可拒绝但不批准](<https://code.claude.com/docs/en/hooks#match-monitor-commands>)在没有匹配者的情况下,他们为每一次事件奔跑。 ### 回调函数 #### 输入 每个钩子回调都收到三个论点: - **输入数据 :** 包含事件细节的输入对象。每个钩子类型都有自己的输入形状。例如, `PreToolUseHookInput` 包含 `tool_name` 财务报告和财务报告 `tool_input`时 `NotificationHookInput` 包含 `message`中,请参见 [TypeScript](<https://code.claude.com/docs/en/agent-sdk/typescript#hookinput>) 财务报告和财务报告 [Python 键](<https://code.claude.com/docs/en/agent-sdk/python#hookinput>) SDK参考文献. - 所有钩状输入共享 `session_id`, `cwd`,以及 `hook_event_name`. - `agent_id` 财务报告和财务报告 `agent_type` 在 TypeScript 中,这些在底钩输入上,可供所有类型的钩子使用。在 Python 中,它们是可选的字段。 `PreToolUse`, `PostToolUse`, `PostToolUseFailure`,以及 `PermissionRequest`字段 `SubagentStart` 财务报告和财务报告 `SubagentStop`. - **工具使用 ID** (`str | None` / `string | undefined`: 关联 `PreToolUse` 财务报告和财务报告 `PostToolUse` 用于同一工具调用的事件。 - **背景情况 :** 在TypeScript中,包含一个 `signal` 财产(`AbortSignal`) 用于取消。在 Python 中,这个参数留给将来使用。 #### 产出 您的回调返回包含两个字段的对象 : - **顶级字段** 每次活动都接受: `systemMessage` 向用户显示消息,以及 `continue` (`continue_` 在 Python 中)决定代理是否继续运行在此钩后。有些事件会丢弃它们或把它们送到别处。 [事件部分](<https://code.claude.com/docs/en/hooks#hook-events>) 钩子上写着他们降落的地方 - **`hookSpecificOutput`** 控制当前操作。您在其中设置的字段取决于钩事件类型 : - 为: `PreToolUse` 钩子,这是你设置的地方 `permissionDecision` (`"allow"`, `"deny"`, `"ask"`,或 `"defer"`), `permissionDecisionReason`,以及 `updatedInput`。如果返回的话 `"defer"`,转弯以一个结果信息结束, `stop_reason` 为: `"tool_deferred"`这样你就可以 [稍后恢复通话](<https://code.claude.com/docs/en/hooks#defer-a-tool-call-for-later>). - 为: `PostToolUse` 钩子,你可以设置 `additionalContext` 在工具结果中附加信息。在克劳德看到之前替换工具的输出,设置 `updatedToolOutput`,用于两种SDK中的内置和MCP工具。 `updatedMCPToolOutput` 字段只替换 MCP 工具输出。 - 在TypeScript SDK中,a `PostToolUse` 调用也可以返回 `classifierContext`,简短地说明该工具的调用结果。 [自动模式](<https://code.claude.com/docs/en/permission-modes#eliminate-prompts-with-auto-mode>) 权限分类器。由于您的调用在应用程序的自身程序中运行,分类器可能会将您在注释中转发的用户声明作为用户意图。字段需要TypeScript Agent SDK v0.3.236 或稍后。 [为自动模式分类器注释结果](<https://code.claude.com/docs/en/hooks#annotate-a-result-for-the-auto-mode-classifier>) 覆盖长度盖,同步唯一规则,以及不放入注释的内容. 为: `PreToolUse`时,返回 `{}` 不做决定,所以正常的 [权限流量](<https://code.claude.com/docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) 应用。 SDK 调回钩子使用相同的 JSON 输出格式, 如 [Claude 代码 shell 命令钩](<https://code.claude.com/docs/en/hooks#json-output>),用于记录每个字段和特定事件选项。关于 SDK 类型定义,参见 [TypeScript](<https://code.claude.com/docs/en/agent-sdk/typescript#synchookjsonoutput>) 财务报告和财务报告 [Python 键](<https://code.claude.com/docs/en/agent-sdk/python#synchookjsonoutput>) SDK参考文献. 多次时 `PreToolUse` 钩子返回不同 [决定](<https://code.claude.com/docs/en/hooks#pretooluse-decision-control>), `deny` 优先级高于 `defer`,优先排序于 `ask`,优先排序于 `allow`. #### 同步输出 默认情况下, 代理在程序开始前等待您的钩子返回 。 如果您的钩子执行副作用, 如记录或发送网钩, 并且不需要影响代理的行为, 您可以返回一个同步输出 。 这告诉代理在不等待钩子完成的情况下立即继续。 在此片断中, `send_to_logging_service` 在 Python 中和 `sendToLoggingService` 在 TypeScript 中为您定义的任何日志函数表示: ``` async def async_hook(input_data, tool_use_id, context): # Start a background task, then return immediately asyncio.create_task(send_to_logging_service(input_data)) return {"async_": True, "asyncTimeout": 30000} ``` ``` const asyncHook: HookCallback = async (input, toolUseID, { signal }) => { // Start a background task, then return immediately sendToLoggingService(input).catch(console.error); return { async: true, asyncTimeout: 30000 }; }; ``` | 外地 | 类型 | 说明 | | --- | --- | --- | | `async` | `true` | 信号同步模式。 代理机不等待即前进。 在 Python 中, 使用 `async_` 以避免保留关键词。 | | `asyncTimeout` | `number` | 背景操作的可选超时( 毫秒) | Async 输出无法阻断、修改或插入上下文到操作中,因为代理已经启动。 仅用于诸如记录、 度量或通知等副作用。 ### 当召回失败时屏蔽动作 在大多数事件上,如果回调时丢弃或返回未验证的输出,则动作会继续,您的应用程序会收到一个 [`SDKInformationalMessage`](<https://code.claude.com/docs/en/agent-sdk/typescript#sdkinformationalmessage>) 警告者, `tag` 为: `hook_callback_failed`. A `PreToolUse` 守护崩溃后让工具调用到达正常权限流。 回调不返回, 如没有路径 。 `return`,也可以算作失败。在 Python 中,读作 `tag` 从 `SystemMessage.data`。要阻止动作,设置 `onFailure: "block"` 在 TypeScript 中,或 `on_failure="block"` 在匹配器上的 Python 中。 需要 TypeScript 代理 SDK v0.3.317 或以后, 或 Python 代理 SDK v0.2.177 或以后。 此示例会阻断 Bash 调用 `check_policy` 以 Python 键或 `checkPolicy` 在 TypeScript 中失败 : ``` options = ClaudeAgentOptions( hooks={ "PreToolUse": [ HookMatcher(matcher="Bash", hooks=[check_policy], on_failure="block") ] } ) ``` ``` import type { Options } from "@anthropic-ai/claude-agent-sdk"; const options: Options = { hooks: { PreToolUse: [{ matcher: "Bash", hooks: [checkPolicy], onFailure: "block" }] } }; ``` 要测试它, 请让调用提醒错误并请求 Claude 运行 Bash 命令。 工具结果包括 `failed; blocking because onFailure is "block"`,而克劳德没有看到您的错误文本。返回 `{}` 当召回者没有意见时。 `"block"` 设置, 无路径 `return` 阻断动作。一个捕捉到自己错误并返回的回调 `{}` 而不是失败,所以让一个警卫传播错误。 A `WorktreeCreate` 调用必须返回 `hookSpecificOutput.worktreePath`. #### 行为不同的事件 这些事件并非总能阻止, `"block"` 设定 : - **`Stop`, `SubagentStop`, `TaskCompleted`,以及 `TeammateIdle`**:这些事件忽略了这个选项,所以行动开始. - **`PermissionRequest`**: 区块只有在你到达之前才算数 `canUseTool` 召回回复。 - **`PostToolUse`**:该工具已经运行,所以克劳德接收失败作为反馈. 超过超时的召回 [Hook 超时](<https://code.claude.com/docs/en/agent-sdk/hooks#hook-timeout>)与 `"block"` 设置, 超时也设置块 `PreCompact` 财务报告和财务报告 `Elicitation`. #### 启动错误 `onFailure` 与 `"block"` 设置, 启动时查询失败, 无法遵守此选项时不会发出提示 : - **Claude Code 不支持这个选项**: 错误包括 `does not honor`。更新 Claude 代码,或删除选项。 - **会话已经运行, 但没有注册您的钩子**: 错误包括 `did not register your hooks`。开始新的会话。 ## 实例 本节中的几个例子只显示调用函数。 要运行一个, 请在匹配事件下将调用记录在 `hooks` 字段,请参见 [配置钩子](<https://code.claude.com/docs/en/agent-sdk/hooks#configure-hooks>). ### 修改工具输入 此示例截取 写入工具调用并重写 `file_path` 要预开的参数 `/sandbox`返回调用 `updatedInput` 带有修改过的路径,以及 `permissionDecision: 'allow'` 自动批准重写操作 : ``` async def redirect_to_sandbox(input_data, tool_use_id, context): if input_data["hook_event_name"] != "PreToolUse": return {} if input_data["tool_name"] == "Write": original_path = input_data["tool_input"].get("file_path", "") return { "hookSpecificOutput": { "hookEventName": input_data["hook_event_name"], "permissionDecision": "allow", "updatedInput": { **input_data["tool_input"], "file_path": f"/sandbox{original_path}", }, } } return {} ``` ``` const redirectToSandbox: HookCallback = async (input, toolUseID, { signal }) => { if (input.hook_event_name !== "PreToolUse") return {}; const preInput = input as PreToolUseHookInput; const toolInput = preInput.tool_input as Record<string, unknown>; if (preInput.tool_name === "Write") { const originalPath = toolInput.file_path as string; return { hookSpecificOutput: { hookEventName: preInput.hook_event_name, permissionDecision: "allow", updatedInput: { ...toolInput, file_path: `/sandbox${originalPath}` } } }; } return {}; }; ``` 平对 `updatedInput` 与 `permissionDecision: 'allow'` 自动批准修改后的输入,或 `permissionDecision: 'ask'` 以显示给用户。如果省略 `permissionDecision`中,修改后的输入仍然适用,并通过正常权限评价进行。 `'defer'`, `updatedInput` 。总是返回新对象,而不是改变原对象 `tool_input`. 要确认方向调整, 请将前缀设定为您可以写入的路径, 例如 : `./sandbox` 或 时 间 `/tmp/sandbox` (macOS不允许创建根级) `/sandbox` ),然后请代理写一个文件: Write 工具在消息流中的结果用您的沙盒前缀命名路径,而不是克劳德要求的路径 。 ### 添加上下文并屏蔽工具 此示例否认工具调用 `file_path` 开始于 `/etc` 并解释为什么模型和用户: - `permissionDecision: 'deny'` 停止工具调用。 - `permissionDecisionReason` 告诉模特儿为什么 - `systemMessage` 显示用户发生的情况。 ``` async def block_etc_writes(input_data, tool_use_id, context): file_path = input_data["tool_input"].get("file_path", "") if file_path.startswith("/etc"): return { # Top-level field: message shown to the user "systemMessage": "Remember: system directories like /etc are protected.", # hookSpecificOutput: block the operation "hookSpecificOutput": { "hookEventName": input_data["hook_event_name"], "permissionDecision": "deny", "permissionDecisionReason": "Writing to /etc is not allowed", }, } return {} ``` ``` const blockEtcWrites: HookCallback = async (input, toolUseID, { signal }) => { const preInput = input as PreToolUseHookInput; const toolInput = preInput.tool_input as Record<string, unknown>; const filePath = toolInput?.file_path as string; if (filePath?.startsWith("/etc")) { return { // Top-level field: message shown to the user systemMessage: "Remember: system directories like /etc are protected.", // hookSpecificOutput: block the operation hookSpecificOutput: { hookEventName: preInput.hook_event_name, permissionDecision: "deny", permissionDecisionReason: "Writing to /etc is not allowed" } }; } return {}; }; ``` 为了确认这个区块,请在 `PreToolUse` 带一个 `Write|Edit` 匹配者,请代理商在 `/etc`: 写入工具在消息流中的结果包含 `Writing to /etc is not allowed`,则没有创建文件。 ### 自动认可特定工具 默认情况下, 代理程序在使用某些工具前可能会提示许可 。 此示例通过返回来自动批准只读文件系统工具( Read, Glob, Grep) `permissionDecision: 'allow'`,让他们在未经用户确认的情况下运行,除了读取 [网络路径](<https://code.claude.com/docs/en/permissions#network-paths>),同时将所有其他工具置于正常权限检查之下: ``` async def auto_approve_read_only(input_data, tool_use_id, context): if input_data["hook_event_name"] != "PreToolUse": return {} read_only_tools = ["Read", "Glob", "Grep"] if input_data["tool_name"] in read_only_tools: return { "hookSpecificOutput": { "hookEventName": input_data["hook_event_name"], "permissionDecision": "allow", "permissionDecisionReason": "Read-only tool auto-approved", } } return {} ``` ``` const autoApproveReadOnly: HookCallback = async (input, toolUseID, { signal }) => { if (input.hook_event_name !== "PreToolUse") return {}; const preInput = input as PreToolUseHookInput; const readOnlyTools = ["Read", "Glob", "Grep"]; if (readOnlyTools.includes(preInput.tool_name)) { return { hookSpecificOutput: { hookEventName: preInput.hook_event_name, permissionDecision: "allow", permissionDecisionReason: "Read-only tool auto-approved" } }; } return {}; }; ``` ### 注册多个钩子 当事件起火时,匹配的钩子会平行运行。对于许可决定,适用最限制性的结果。 一个钩子 `deny` 屏蔽工具调用 。 因为补全命令是非决定性的, 请写每个钩子独立行动, 而不是依赖另一个钩子先运行。 下面的例子将登记三个独立的检查, 每个检查都有一个 [省略匹配器](<https://code.claude.com/docs/en/hooks#matcher-patterns>)。其中的钩名,例如 `audit_logger` 以 Python 键或 `auditLogger` 在 TypeScript 中,表示您定义的召回: ``` options = ClaudeAgentOptions( hooks={ "PreToolUse": [ HookMatcher(hooks=[authorization_check]), HookMatcher(hooks=[input_validator]), HookMatcher(hooks=[audit_logger]), ] } ) ``` ``` const options = { hooks: { PreToolUse: [ { hooks: [authorizationCheck] }, { hooks: [inputValidator] }, { hooks: [auditLogger] } ] } }; ``` ### 使用多工具匹配器过滤 使用多工具匹配器在相关工具之间共享一个回调。 此示例会登记三个具有不同范围的匹配器, 每个钩子中它的名字代表您定义的回调 : - 烟管分离的精确清单(`Write|Edit|NotebookEdit`) 触发器 `file_security_hook` 用于 Write, Edit, 和 NotebookEdit 工具。 - 缩写( RGex )`^mcp__`) 触发器 `mcp_audit_hook` 用于名称始于 MCP 工具 `mcp__`. - 省略的匹配器触发器 `global_logger` 不通过工具名称过滤。 ``` options = ClaudeAgentOptions( hooks={ "PreToolUse": [ # Match file modification tools HookMatcher(matcher="Write|Edit|NotebookEdit", hooks=[file_security_hook]), # Match all MCP tools HookMatcher(matcher="^mcp__", hooks=[mcp_audit_hook]), # Match everything (no matcher) HookMatcher(hooks=[global_logger]), ] } ) ``` ``` const options = { hooks: { PreToolUse: [ // Match file modification tools { matcher: "Write|Edit|NotebookEdit", hooks: [fileSecurityHook] }, // Match all MCP tools { matcher: "^mcp__", hooks: [mcpAuditHook] }, // Match everything (no matcher) { hooks: [globalLogger] } ] } }; ``` ### 音轨亚剂活动 使用( U) `SubagentStop` 钩子以监视子剂完成工作时。请在 [TypeScript](<https://code.claude.com/docs/en/agent-sdk/typescript#hookinput>) 财务报告和财务报告 [Python 键](<https://code.claude.com/docs/en/agent-sdk/python#hookinput>) SDK 引用。 此示例记录一个子代理完成时的摘要 : ``` async def subagent_tracker(input_data, tool_use_id, context): # Log subagent details when it finishes print(f"[SUBAGENT] Completed: {input_data['agent_id']}") print(f" Transcript: {input_data['agent_transcript_path']}") print(f" Tool use ID: {tool_use_id}") print(f" Stop hook active: {input_data.get('stop_hook_active')}") return {} options = ClaudeAgentOptions( hooks={"SubagentStop": [HookMatcher(hooks=[subagent_tracker])]} ) ``` ``` import { HookCallback, SubagentStopHookInput } from "@anthropic-ai/claude-agent-sdk"; const subagentTracker: HookCallback = async (input, toolUseID, { signal }) => { // Cast to SubagentStopHookInput to access subagent-specific fields const subInput = input as SubagentStopHookInput; // Log subagent details when it finishes console.log(`[SUBAGENT] Completed: ${subInput.agent_id}`); console.log(` Transcript: ${subInput.agent_transcript_path}`); console.log(` Tool use ID: ${toolUseID}`); console.log(` Stop hook active: ${subInput.stop_hook_active}`); return {}; }; const options = { hooks: { SubagentStop: [{ hooks: [subagentTracker] }] } }; ``` 要确认钩火, 注册回调, 请代理将一个小任务委托给子代理, 例如将文件列出在当前目录中: 当子代理完成后, 回调会打印 `[SUBAGENT] Completed:` 带有子代理的 ID 和记录路径的线条。 ### 使 HTTP 从钩子请求 Hooks 能够像 HTTP 请求一样进行同步操作。 在您的钩子中捕捉错误, 而不是让它们传播。 此示例会在每个工具完成后发送一个 Webhook, 记录哪个工具运行和何时运行。 钩子捕获错误来自一个失败的webhook : ``` import asyncio import json import urllib.request from datetime import datetime def _send_webhook(tool_name): """Synchronous helper that POSTs tool usage data to an external webhook.""" data = json.dumps( { "tool": tool_name, "timestamp": datetime.now().isoformat(), } ).encode() req = urllib.request.Request( "https://api.example.com/webhook", data=data, headers={"Content-Type": "application/json"}, method="POST", ) urllib.request.urlopen(req) async def webhook_notifier(input_data, tool_use_id, context): # Only fire after a tool completes (PostToolUse), not before if input_data["hook_event_name"] != "PostToolUse": return {} try: # Run the blocking HTTP call in a thread to avoid blocking the event loop await asyncio.to_thread(_send_webhook, input_data["tool_name"]) except Exception as e: # Log the error but don't raise print(f"Webhook request failed: {e}") return {} ``` ``` import { query, HookCallback, PostToolUseHookInput } from "@anthropic-ai/claude-agent-sdk"; const webhookNotifier: HookCallback = async (input, toolUseID, { signal }) => { // Only fire after a tool completes (PostToolUse), not before if (input.hook_event_name !== "PostToolUse") return {}; try { await fetch("https://api.example.com/webhook", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tool: (input as PostToolUseHookInput).tool_name, timestamp: new Date().toISOString() }), // Pass signal so the request cancels if the hook times out signal }); } catch (error) { // Handle cancellation separately from other errors if (error instanceof Error && error.name === "AbortError") { console.log("Webhook request cancelled"); } // Don't re-throw } return {}; }; // Register as a PostToolUse hook for await (const message of query({ prompt: "Refactor the auth module", options: { hooks: { PostToolUse: [{ hooks: [webhookNotifier] }] } } })) { console.log(message); } ``` 为了确认钩火,将Webhook URL指向一个端点,您可以观看并发送一个使用工具的提示:钩子在每个工具完成后会发送一个带有工具名称和时间戳的POST. ### 将通知转发给 Slack 使用( U) `Notification` 接收代理机发送的系统通知并转发到外部服务的钩子。 在 SDK 会话中, Claude Code 运行此钩子用于以下通知类型 : - [`permission_prompt`](<https://code.claude.com/docs/en/hooks#notification>) 一旦一个许可申请 等待了大约6秒 [`canUseTool` 回调](<https://code.claude.com/docs/en/agent-sdk/user-input>). 要求 TypeScript 代理 SDK v0.3.233 或以后,或 Python 代理 SDK v0.2.139 或以后 - `elicitation_complete` 财务报告和财务报告 `elicitation_response` 用于用户即时引出流量 - `plugin_notification` 当一个 [模式](<https://code.claude.com/docs/en/plugins/mods/api#show-something-without-starting-a-turn>) 电话 `$.ui.notify` Claude 代码发布其他类型,例如: `idle_prompt`, `auth_success`,以及 `elicitation_dialog`,来自交互式的 UI , 即 SDK 会话不运行。每份通知中都包含一个 `message` 字段,带有人可读的描述和可选的a `title`。此示例将每个通知转发给Slack频道。它要求 [黑进的网络 URL](<https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/>),您通过在您的 Slack 工作空间中添加一个应用程序并允许进入的 webhokes 创建 : ``` import asyncio import json import urllib.request from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, HookMatcher def _send_slack_notification(message): """Synchronous helper that sends a message to Slack via incoming webhook.""" data = json.dumps({"text": f"Agent status: {message}"}).encode() req = urllib.request.Request( "https://hooks.slack.com/services/YOUR/WEBHOOK/URL", data=data, headers={"Content-Type": "application/json"}, method="POST", ) urllib.request.urlopen(req) async def notification_handler(input_data, tool_use_id, context): try: # Run the blocking HTTP call in a thread to avoid blocking the event loop await asyncio.to_thread(_send_slack_notification, input_data.get("message", "")) except Exception as e: print(f"Failed to send notification: {e}") # Return empty object. Notification hooks don't modify agent behavior return {} async def main(): options = ClaudeAgentOptions( hooks={ # Register the hook for Notification events (no matcher needed) "Notification": [HookMatcher(hooks=[notification_handler])], }, ) async with ClaudeSDKClient(options=options) as client: await client.query("Analyze this codebase") async for message in client.receive_response(): print(message) asyncio.run(main()) ``` ``` import { query, HookCallback, NotificationHookInput } from "@anthropic-ai/claude-agent-sdk"; // Define a hook callback that sends notifications to Slack const notificationHandler: HookCallback = async (input, toolUseID, { signal }) => { // Cast to NotificationHookInput to access the message field const notification = input as NotificationHookInput; try { // POST the notification message to a Slack incoming webhook await fetch("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: `Agent status: ${notification.message}` }), // Pass signal so the request cancels if the hook times out signal }); } catch (error) { if (error instanceof Error && error.name === "AbortError") { console.log("Notification cancelled"); } else { console.error("Failed to send notification:", error); } } // Return empty object. Notification hooks don't modify agent behavior return {}; }; // Register the hook for Notification events (no matcher needed) for await (const message of query({ prompt: "Analyze this codebase", options: { hooks: { Notification: [{ hooks: [notificationHandler] }] } } })) { console.log(message); } ``` 当a `Notification` 发生火灾时,钩子会张贴通知 `message`,前缀为 `Agent status:`,到频道,你的网页锁定目标。 ## 解决共同问题 ### 钩子不要开火 - 校验钩子事件名称正确且区分大小写( E)`PreToolUse`,没有 `preToolUse`) - 检查您的匹配者模式是否与工具名称完全匹配 - 确保勾钩在正确的事件类型下 `options.hooks` - 对于非工具钩 支持匹配者,例如 `Notification` 财务报告和财务报告 `SubagentStop`,匹配者匹配 不同的田间,和 `Stop` 完全忽略匹配者(参见 [匹配模式](<https://code.claude.com/docs/en/hooks#matcher-patterns>)) - 虎克不会开火 当特工击中时 [`max_turns`](<https://code.claude.com/docs/en/agent-sdk/python#claudeagentoptions>) 限制, 因为会话在钩子执行前结束 ### 匹配器未按预期过滤 匹配者只匹配工具名, 不匹配文件路径或其他参数。 要通过文件路径过滤, 请检查 `tool_input.file_path` 在你的钩子里: ``` const myHook: HookCallback = async (input, toolUseID, { signal }) => { const preInput = input as PreToolUseHookInput; const toolInput = preInput.tool_input as Record<string, unknown>; const filePath = toolInput?.file_path as string; if (!filePath?.endsWith(".md")) return {}; // Skip non-markdown files // Process markdown files... return {}; }; ``` ### Hook 超时 Claude Code 以超时运行每个调回, 您用秒数设置 。 `timeout` 字段显示 `HookMatcher`。当你不设置一个时, Claude Code 使用事件默认值: 大部分事件为 600 秒, 30 秒为 `UserPromptSubmit`, `PreModelSwitch`,以及 `PostModelSwitch`,且 10 秒为 `MessageDisplay`。克劳德代码运行 `SessionEnd` 关闭时在较短的时间内调用 [SessionEnd 超时预算](<https://code.claude.com/docs/en/hooks#sessionend-input>), 默认情况下, 1.5 秒。 当召回超过其超时时, Claude Code 取消并丢弃其输出。 在下面的事件上, Claude Code 则会屏蔽动作或继续而不召回: - `PreToolUse`: Claude Code 屏蔽工具调用。如果其他钩子没有返回,或者只返回一个 `allow` 工具结果告诉 Klaude 键在超时前没有响应, 转动仍在继续 。 如果您的另一个钩子已经拒绝呼叫, 它的拒绝仍然到达了 Claude: 工具结果包括了该钩子的理由, 而超时文本可以遵循它 。 在 v2.1.210 之前, Claude Code 将超时报告给 Claude 作为用户拒绝, 它让未出席的会话停止并等待输入 。 - `PostToolUse` 财务报告和财务报告 `PostToolUseFailure`: Claude Code保持工具结果,转弯继续. - `UserPromptSubmit` 财务报告和财务报告 [`UserPromptExpansion`](<https://code.claude.com/docs/en/hooks#userpromptexpansion>): Claude Code 屏蔽了提示, 并有信件命名了钩子和超时, 会话继续。 在 v2.1.208 之前, Claude Code 结束查询以 `error_during_execution` 当这些事件的回话超时。 - `Stop` 财务报告和财务报告 `SubagentStop`: 超时调回计时计数为不返回任何决定。 代理或副代理停止调回计时, 仿佛允许它, 您其他钩子对事件的决定仍然适用。 在 Claude Code v2.1.273 之前, 一个超时 `Stop` 或 时 间 `SubagentStop` Claude Code 放弃了您在事件上其他钩子的决定。 - `SessionStart`: 计时后调用计数为返回无输出,会话会话会随其他输出继续 `SessionStart` 钩子. - `PreModelSwitch`: Claude Code 屏蔽了模型开关。 一个不回答的钩子没有批准开关。 - `WorktreeCreate`: 工作树创建失败, 错误 。 - `Notification`, `PreCompact`,以及 `PostModelSwitch`: Claude Code 记录失败并继续进行。当一个 `PreCompact` 取消调用时间, 设定 [`onFailure: "block"`](<https://code.claude.com/docs/en/agent-sdk/hooks#block-the-action-when-a-callback-fails>). 第一次 第一次 第一次 第一次 `Stop` 或 时 间 `SessionStart` 主会话中的调回时间, 您的消息流中也包含一个 [`SDKInformationalMessage`](<https://code.claude.com/docs/en/agent-sdk/typescript#sdkinformationalmessage>) 对象表示驱动会话的应用程序没有响应 。 您的应用程序没有响应, 最多每个钩子类型都会有一个这样的消息到达。 如果您在等待回调时中断了查询, Claude Code 将取消待决工具调用 。 在 v2.1.208 之前, 如果您在待决期间中断, 工具调用仍然可以继续 。 `PreToolUse` 回调。 如果您的回调需要更多时间, 请设置更高的 `timeout` 联 合 国 `HookMatcher`在TypeScript中,使用 `AbortSignal` 从第三个召回参数中, 可以在超时时优雅地处理取消 。 ### 工具意外被屏蔽 - 检查所有 `PreToolUse` 钩子 `permissionDecision: 'deny'` 返回时 - 在钩子上添加日志以查看 `permissionDecisionReason` 他们回来了 - 校验匹配者模式并不太宽:空匹配者匹配所有工具 - 如果工具结果显示钩子 `returned updatedInput that failed schema validation` 或 时 间 `returned updatedInput that the tool refused`,修补钩子 `updatedInput`。包含不变的 `tool_input` 字段,如 [修改工具输入](<https://code.claude.com/docs/en/agent-sdk/hooks#modify-tool-input>),因为 `updatedInput` 替换整个输入。 ### 未应用的修改输入 - 保证 `updatedInput` 内在 `hookSpecificOutput`,而不是在顶层: ``` return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { command: "new command" } } }; ``` - 不要对对 `updatedInput` 与 `permissionDecision: 'defer'`,将修改后的输入减少。Omiting `permissionDecision` fine:修改后的输入仍然通过普通权限评价应用。您也可以返回 `'allow'` 自动批准修改过的输入或 `'ask'` 以显示给用户批准 - 包含 `hookEventName` 输入 `hookSpecificOutput` 以识别输出的哪个钩子类型 ### Python 不可用的会话钩 `SessionStart` 财务报告和财务报告 `SessionEnd` 可以在 SDK 中注册为 TypeScript 的回调钩,但是在 Python SDK 中不可用,因为它 `HookEvent` 类型省略它们。在 Python 中,它们只能作为 [shell 命令钩](<https://code.claude.com/docs/en/hooks#hook-events>) 在设置文件中定义, 如 `.claude/settings.json`。哪些设置文件您的 SDK 应用程序负载取决于 [`setting_sources`](<https://code.claude.com/docs/en/agent-sdk/python#settingsource>) 或 时 间 [`settingSources`](<https://code.claude.com/docs/en/agent-sdk/typescript#settingsource>)。如果设置了该选项,则包括持有钩的源 : ``` options = ClaudeAgentOptions( setting_sources=["project"], # Loads .claude/settings.json including hooks ) ``` ``` const options = { settingSources: ["project"] // Loads .claude/settings.json including hooks }; ``` 要以 Python SDK 回调方式运行初始化逻辑, 请使用第一个来自 `client.receive_response()` 作为你的触发器。 ### 子代理许可提示乘数 当生成多个子剂时, 每个人可以为自己的工具调用单独请求权限。 为了避免重复的提示, 请使用 。 `PreToolUse` 自动批准特定工具的钩子, 或配置许可规则, 哪个子代理 [从父对话框继承](<https://code.claude.com/docs/en/sub-agents#permission-modes>). ### 带有子剂的递归式钩子环 A `UserPromptSubmit` 如果这些副剂触发同一个钩子,产卵亚剂的钩子可以产生无限循环。为了防止这种情况: - 使用共享变量或会话状态来跟踪您是否已经在子代理中 - 仅运行于顶级代理会话的范围钩钩 ### 输出中未出现的 systemMessage 那个... `systemMessage` 字段向用户显示消息,而不是模型。在克劳德代码 v2.1.227 上或稍后,一个钩子 `systemMessage` 可以在信息流中以 [`SDKInformationalMessage`](<https://code.claude.com/docs/en/agent-sdk/typescript#sdkinformationalmessage>)。是否取决于事件。 [事件部分](<https://code.claude.com/docs/en/hooks#hook-events>) 显示输出的表面。要将上下文传递到模型中,请返回 [`additionalContext`](<https://code.claude.com/docs/en/hooks#add-context-for-claude>)。在 v2.1.227 之前, SDK 在消息流中表面的钩子输出仅用于 `SessionStart` 财务报告和财务报告 `Setup` 钩子。对于任何其他事件,输出只出现在生命周期中 [`includeHookEvents`](<https://code.claude.com/docs/en/agent-sdk/typescript#options>) (`include_hook_events` 在 Python 中添加。该选项的条目涵盖每个钩事件产生的生命周期事件。如果您需要将钩子决定显示在您的应用程序上,请单独登录,或使用专用输出通道。 ## 相关资源 - [Claude 代码钩子引用](<https://code.claude.com/docs/en/hooks>): 完整的 JSON 输入/输出计划、事件文档和匹配器模式 - [Claude 代码钩子指南](<https://code.claude.com/docs/en/hooks-guide>): shell 命令钩子示例和走过 - [TypeScript SDK 参考文献](<https://code.claude.com/docs/en/agent-sdk/typescript>): 钩子类型、输入/输出定义和配置选项 - [Python SDK 参考文献](<https://code.claude.com/docs/en/agent-sdk/python>): 钩子类型、输入/输出定义和配置选项 - [权限](<https://code.claude.com/docs/en/agent-sdk/permissions>): 控制您的代理人所能做的 - [自定义工具](<https://code.claude.com/docs/en/agent-sdk/custom-tools>): 建立工具以扩大代理能力
查看原始来源