Claude Code
Hooks 系统
用 Hooks 在 Claude Code 生命周期中自动执行自定义逻辑
Hooks 是用户定义的自动化脚本,在 Claude Code 的特定生命周期节点自动触发。
Hook 事件一览
| 事件 | 触发时机 | 可阻断 |
|---|---|---|
SessionStart | 会话开始或恢复 | 否 |
UserPromptSubmit | 用户提交提示词 | 是 |
PreToolUse | 工具执行前 | 是 |
PostToolUse | 工具执行成功后 | 否 |
PostToolUseFailure | 工具执行失败后 | 否 |
PermissionRequest | 权限对话框出现时 | 否 |
Stop | Claude 完成响应 | 否 |
SubagentStart | 子 Agent 启动 | 否 |
SubagentStop | 子 Agent 结束 | 否 |
TaskCreated | 任务创建 | 否 |
TaskCompleted | 任务完成 | 否 |
Notification | 通知事件 | 否 |
FileChanged | 文件变更 | 否 |
SessionEnd | 会话结束 | 否 |
配置方式
在 settings.json 的 hooks 字段中配置:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"handler": {
"type": "command",
"command": "npx biome format --write $FILE"
}
}
]
}
}交互式配置
在 Claude Code 中输入 /hooks,通过菜单引导配置,无需手动编辑 JSON。
四种处理器类型
1. Command(Shell 命令)
最常用,通过 stdin 接收 JSON 上下文:
{
"type": "command",
"command": "npx biome format --write $FILE"
}退出码含义:
0— 成功,继续执行2— 阻断,中止操作
2. HTTP(发送请求)
向指定 URL 发送 POST 请求:
{
"type": "http",
"url": "https://your-webhook.com/hook"
}3. Prompt(发送给 Claude 评估)
让 Claude 自己评估一段提示词:
{
"type": "prompt",
"prompt": "检查这个文件是否包含敏感信息,如果有则阻断"
}4. Agent(生成子 Agent)
启动子 Agent 进行复杂验证:
{
"type": "agent",
"prompt": "审查这个代码变更是否符合项目规范"
}Matcher 模式匹配
matcher 字段用正则匹配工具名,决定 Hook 对哪些工具生效:
"Bash"— 匹配所有 Bash 命令"Edit|Write"— 匹配编辑或写入"mcp__.*__write"— 匹配所有 MCP 写入工具
实用示例
写文件后自动格式化
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"handler": {
"type": "command",
"command": "npx biome format --write $FILE"
}
}
]
}
}提交前自动跑测试
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"handler": {
"type": "command",
"command": "if echo \"$TOOL_INPUT\" | grep -q 'git commit'; then npm test; fi"
}
}
]
}
}会话开始时提醒
{
"hooks": {
"SessionStart": [
{
"handler": {
"type": "command",
"command": "echo '记得先拉最新代码!'"
}
}
]
}
}PreToolUse 权限决策
PreToolUse Hook 可以返回权限决策来控制工具行为:
allow— 直接允许,跳过权限检查deny— 直接拒绝ask— 弹出审批框defer— 交给后续权限检查