🐾LuoLuo Wiki
Claude Code

Hooks 系统

用 Hooks 在 Claude Code 生命周期中自动执行自定义逻辑

Hooks 是用户定义的自动化脚本,在 Claude Code 的特定生命周期节点自动触发。

Hook 事件一览

事件触发时机可阻断
SessionStart会话开始或恢复
UserPromptSubmit用户提交提示词
PreToolUse工具执行前
PostToolUse工具执行成功后
PostToolUseFailure工具执行失败后
PermissionRequest权限对话框出现时
StopClaude 完成响应
SubagentStart子 Agent 启动
SubagentStop子 Agent 结束
TaskCreated任务创建
TaskCompleted任务完成
Notification通知事件
FileChanged文件变更
SessionEnd会话结束

配置方式

settings.jsonhooks 字段中配置:

{
  "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 — 交给后续权限检查

On this page