Claude Code 生命周期 Hooks 完整使用指南:从零开始掌握回调方法与高级实战技巧
摘要
ClaudeCode生命周期Hooks提供Shell命令、HTTP请求、LLM提示和Agent验证四种类型,分别作用于Setup
Claude Code Hooks 核心概念
Hooks 本质上是你在 Claude Code 中预设的自定义脚本或命令,能够在指定的生命周期节点自动触发。这套体系支持 4 种类型,覆盖 4 个关键生命周期事件。

Hook 的 4 种类型详解
| 类型 | type 字段 |
说明 |
|---|---|---|
| Shell 命令 | "command" |
最直接的方式,执行 shell 命令,标准输出作为结果返回 |
| HTTP 请求 | "http" |
向指定接口发送 POST 请求,将 hook 输入以 JSON 格式放入请求体 |
| LLM 提示 | "prompt" |
让大语言模型评估一段提示词,拿到结构化结果 |
| Agent 验证 | "agent" |
调用 agent 执行验证任务,比如确认测试全部通过 |
4 个生命周期事件
Setup
在 Claude Code 进程启动时仅执行一次,专门处理项目初始化工作。
{"hooks": {"Setup": [{"matcher": "","hooks": [{ "type": "command", "command": "npm install", "timeout": 60 }]}]}}触发时机在进程启动之后、REPL 渲染之前。Hook Input 字段包含:
| 字段 | 类型 | 说明 |
|---|---|---|
hook_event_name |
"Setup" |
— |
trigger |
"init" | "maintenance" |
触发来源 |
session_id |
string | 当前会话唯一标识 |
cwd |
string | 工作目录路径 |
transcript_path |
string | 会话日志文件位置 |
注意:该 hook 的 stdout 内容不会注入给 Claude 模型。
SessionStart
每次会话开始时触发。无论是全新启动、通过 /resume 恢复、还是 /clear 清空后,都会执行。其 stdout 内容会作为 system message 注入到模型上下文中。
{"hooks": {"SessionStart": [{"matcher": "","hooks": [{ "type": "command", "command": "cat .claude/session-context.md", "timeout": 10 }]}]}}触发场景分为以下几种:
| source | 场景 |
|---|---|
startup |
进程首次启动 |
resume |
使用 --resume 或 /resume 恢复会话 |
clear |
执行 /clear 后 |
compact |
上下文压缩完成后 |
Hook Input 字段:
| 字段 | 类型 | 说明 |
|---|---|---|
hook_event_name |
"SessionStart" |
— |
source |
"startup" | "resume" | "clear" | "compact" |
触发来源 |
agent_type |
string (optional) | agent 类型 |
model |
string (optional) | 当前模型标识 |
此处 stdout 会注入为 system message,模型能够读取。
UserPromptSubmit
在用户每次提交消息之前执行。适合对用户输入做预处理,比如插入安全检查或补充上下文信息。
{"hooks": {"UserPromptSubmit": [{"matcher": "","hooks": [{"type": "command","command": "node scripts/validate-input.js","timeout": 10,"statusMessage": "Validating input..."}]}]}}Hook Input 字段:
| 字段 | 类型 | 说明 |
|---|---|---|
hook_event_name |
"UserPromptSubmit" |
— |
prompt |
string | 用户输入的原始文本 |
该 hook 的 stdout 同样会作为 system message 注入,模型可见。
SessionEnd
会话结束时触发,例如进程退出或执行 /clear。常用于清理资源、记录日志等收尾工作。
{"hooks": {"SessionEnd": [{"matcher": "","hooks": [{ "type": "command", "command": "node scripts/cleanup.js", "timeout": 5 }]}]}}Hook Input 字段:
| 字段 | 类型 | 说明 |
|---|---|---|
hook_event_name |
"SessionEnd" |
— |
reason |
"clear" | "resume" | "logout" | "prompt_input_exit" | "other" |
结束原因 |
该 hook 的 stdout 不会注入模型,静默执行。超时控制方面,默认值为 1.5 秒,可通过环境变量 CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS 自定义。
Hook 命令通用字段
所有类型的 hook 均支持以下字段:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
type |
"command" | "http" | "prompt" | "agent" |
✅ | Hook 类型 |
command / prompt / url |
string | ✅ | 具体命令、提示词或 URL(根据 type 决定) |
timeout |
number | ❌ | 超时时间(秒) |
statusMessage |
string | ❌ | 执行时 spinner 显示的自定义提示信息 |
once |
boolean | ❌ | 仅执行一次后自动从配置中移除 |
if |
string | ❌ | 条件过滤(权限规则语法,例如 "Bash(git *)") |
async |
boolean | ❌ | 后台异步执行,不阻塞主流程(仅 command 类型) |
asyncRewake |
boolean | ❌ | 后台执行且 exit code 为 2 时唤醒模型(仅 command 类型,隐含 async) |
HTTP 类型特有字段
| 字段 | 类型 | 说明 |
|---|---|---|
url |
string | POST 请求目标 URL(hook input 以 JSON body 发送) |
headers |
object | 自定义请求头,支持 $VAR 环境变量引用 |
allowedEnvVars |
string[] | 允许在 header 值中插值的环境变量白名单 |
Prompt 类型特有字段
| 字段 | 类型 | 说明 |
|---|---|---|
prompt |
string | LLM 评估的提示词,使用 $ARGUMENTS 占位符引用 hook input JSON |
model |
string | 使用的模型(默认小模型) |
配置位置
hooks 配置存放在 settings.json 中,支持两个层级:
用户级(全局生效)
位于 ~/.claude/settings.json:
{"hooks": {"SessionStart": [{"matcher": "","hooks": [{ "type": "command", "command": "echo 'Hello from global hook'", "timeout": 5 }]}]}}
项目级(仅当前项目)
位于项目根目录下的 .claude/settings.json:
{"hooks": {"Setup": [{"matcher": "","hooks": [{ "type": "command", "command": "npm install", "timeout": 120 }]}],"SessionStart": [{"matcher": "","hooks": [{ "type": "command", "command": "cat .claude/instructions.md", "timeout": 5 }]}],"UserPromptSubmit": [{"matcher": "","hooks": [{"type": "command","command": "scripts/lint-check.sh","timeout": 15,"if": "Write"}]}],"SessionEnd": [{"matcher": "","hooks": [{ "type": "command", "command": "scripts/cleanup.sh", "timeout": 5 }]}]}}
实用示例
1. 每次启动加载项目文档
这个场景非常实用——让 Claude Code 启动时自动加载项目文档,确保模型掌握项目背景。
{"hooks": {"SessionStart": [{"matcher": "","hooks": [{"type": "command","command": "cat .claude/project-guide.md","timeout": 5,"statusMessage": "Loading project guide..."}]}]}}
2. 提交前做代码规范检查
在用户每次提交前,自动运行代码规范检查,提前拦截问题。
{"hooks": {"UserPromptSubmit": [{"matcher": "","hooks": [{"type": "command","command": "node scripts/check-code-style.js "$CLAUD_PROMPT"","timeout": 10}]}]}}
3. HTTP webhook 通知
会话结束时,通过 HTTP 请求通知外部系统,例如将会话摘要推送到团队协作平台。
{"hooks": {"SessionEnd": [{"matcher": "","hooks": [{"type": "http","url": "https://api.example.com/claude-end","timeout": 5,"headers": {"Authorization": "Bearer $MY_API_TOKEN"},"allowedEnvVars": ["MY_API_TOKEN"]}]}]}}
4. 项目初始化时安装依赖
新项目首次启动时,自动检查并安装依赖,省去手动操作。
{"hooks": {"Setup": [{"matcher": "","hooks": [{"type": "command","command": "test -f package.json && npm install || echo 'No package.json found'","timeout": 120,"statusMessage": "Installing dependencies..."}]}]}}
注意事项
最后列出几个容易踩坑的关键点:
- 超时控制:
timeout字段单位是秒。Setup 和 SessionStart 默认无严格限制,但 SessionEnd 默认仅 1.5 秒,并且有一个 failsafe 机制在 5 秒后会兜底。 - stdout 注入:SessionStart 和 UserPromptSubmit 的 stdout 会作为 system message 发送给模型;Setup 和 SessionEnd 则不会,设计意图明确。
- 异步执行:
async: true的 command hook 会在后台运行,不阻塞主流程。asyncRewake: true更高级,若 exit code 为 2,可以唤醒模型处理错误。 - 条件过滤:
if字段使用权限规则语法(例如"Bash(git *)"、"Write"),只有匹配时才会执行,避免无关操作触发 hook。 - once:设置为
true的 hook 执行一次后自动从配置中移除,适合仅需单次运行的场景。 - 安全:http hook 的 header 中如需引用环境变量,必须在
allowedEnvVars显式声明,否则不生效。
来源:互联网
本网站新闻资讯均来自公开渠道,力求准确但不保证绝对无误,内容观点仅代表作者本人,与本站无关。若涉及侵权,请联系我们处理。本站保留对声明的修改权,最终解释权归本站所有。