工具与文件 Hooks
选择通用或专用事件,处理权限返回、MCP 身份和文件编辑载荷。
通用工具事件适合覆盖多类工具;专用事件提供 shell、MCP 或文件相关字段。先确定要观察还是阻止,再选事件和响应 schema。
通用工具事件
| 事件 | 输入重点 | 可返回内容 |
|---|---|---|
| preToolUse | tool_name、tool_input、tool_use_id、cwd | permission、提示信息、updated_input |
| postToolUse | tool_output、duration、工具标识 | additional_context,MCP 专用 updated_mcp_tool_output |
| postToolUseFailure | error_message、failure_type、duration、is_interrupt | additional_context |
preToolUse 当前只应依赖 allow 或 deny:schema 接受 ask,但调用方目前不执行它。postToolUse 的 tool_output 是 JSON 字符串化的工具结果,不是原始终端文本;duration 单位为毫秒。
failure_type 可为 error、timeout、permission_denied。matcher 对这三种事件匹配工具类型,如 Shell、Read、Write、Grep、Delete、Task 或 MCP:<tool_name>。
Shell 与 MCP
beforeShellExecution 输入 command、cwd、sandbox;beforeMCPExecution 输入 tool_name、JSON 字符串 tool_input、mcp_server_name,以及 HTTP/SSE 的 URL 字段或 stdio 的启动 command。
这两个 before 事件支持如下决定:
{
"permission": "ask",
"user_message": "Review this operation before it runs.",
"agent_message": "Wait for approval before continuing."
}识别 MCP 时按 mcp_server_name 和 tool_name 判断。command 可能因相对路径、插件变量或传输方式变化,HTTP server 甚至没有该字段。关键策略应处理缺失或未知身份,并按失败策略配置 failClosed。
afterShellExecution 提供完整 output、duration、sandbox;afterMCPExecution 提供 result_json、duration 和服务器信息。两者 duration 都不包含审批等待时间。
文件访问与编辑
beforeReadFile 带 file_path、content、attachments,返回 allow/deny 与可选 user_message。afterFileEdit 带绝对 file_path 和 edits 中的 old_string/new_string,适合格式化或记录变更。
对应 matcher 不是文件路径:beforeReadFile 匹配固定 Read,afterFileEdit 匹配固定 Write。按路径筛选应在脚本中读取 file_path 实现。
Tab 使用独立 beforeTabFileRead/afterTabFileEdit,不能由 Agent 事件替代。Tab 读取不带 attachments,编辑另外提供 range、old_line、new_line;afterTabFileEdit 当前不支持输出字段。