create-hooks
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<objective>
Hooks are event-driven automation for Claude Code that execute shell commands or LLM prompts in response to tool usage, session events, and user interactions. This skill teaches you how to create, configure, and debug hooks for validating commands, automating workflows, injecting context, and implementing custom completion criteria.
:
</matchers>
Hooks provide programmatic control over Claude's behavior without modifying core code, enabling project-specific automation, safety checks, and workflow customization.
</objective>
<context>
Hooks are shell commands or LLM-evaluated prompts that execute in response to Claude Code events. They operate within an event hierarchy: events (PreToolUse, PostToolUse, Stop, etc.) trigger matchers (tool patterns) which fire hooks (commands or prompts). Hooks can block actions, modify tool inputs, inject context, or simply observe and log Claude's operations.
</context>
<quick_start>
<workflow>
- Create hooks config file:
- Project:
.claude/hooks.json - User:
~/.claude/hooks.json
- Project:
- Choose hook event (when it fires)
- Choose hook type (command or prompt)
- Configure matcher (which tools trigger it)
- Test with </workflow>
claude --debug
.claude/hooks.jsonjson
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \\\"No description\\\")\"' >> ~/.claude/bash-log.txt"
}
]
}
]
}
}This hook:
- Fires before () every
PreToolUsetool useBash - Executes a (not an LLM prompt)
command - Logs command + description to a file </example>
</quick_start>
<hook_types>
| Event | When it fires | Can block? |
|---|---|---|
| PreToolUse | Before tool execution | Yes |
| PostToolUse | After tool execution | No |
| UserPromptSubmit | User submits a prompt | Yes |
| Stop | Claude attempts to stop | Yes |
| SubagentStop | Subagent attempts to stop | Yes |
| SessionStart | Session begins | No |
| SessionEnd | Session ends | No |
| PreCompact | Before context compaction | Yes |
| Notification | Claude needs input | No |
Blocking hooks can return to prevent the action. See references/hook-types.md for detailed use cases.
</hook_types>
"decision": "block"<hook_anatomy>
<hook_type name="command">
Type: Executes a shell command
Use when:
- Simple validation (check file exists)
- Logging (append to file)
- External tools (formatters, linters)
- Desktop notifications
Input: JSON via stdin
Output: JSON via stdout (optional)
json
{
"type": "command",
"command": "/path/to/script.sh",
"timeout": 30000
}</hook_type>
<hook_type name="prompt">
Type: LLM evaluates a prompt
Use when:
- Complex decision logic
- Natural language validation
- Context-aware checks
- Reasoning required
Input: Prompt with placeholder
Output: JSON with and
$ARGUMENTSdecisionreasonjson
{
"type": "prompt",
"prompt": "Evaluate if this command is safe: $ARGUMENTS\n\nReturn JSON: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"
}</hook_type>
</hook_anatomy>
<matchers>
Matchers filter which tools trigger the hook:
json
{
"matcher": "Bash", // Exact match
"matcher": "Write|Edit", // Multiple tools (regex OR)
"matcher": "mcp__.*", // All MCP tools
"matcher": "mcp__memory__.*" // Specific MCP server
}No matcher: Hook fires for all tools
json
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [...] // No matcher - fires on every user prompt
}
]
}
}<input_output>
Hooks receive JSON via stdin with session info, current directory, and event-specific data. Blocking hooks can return JSON to approve/block actions or modify inputs.
Example output (blocking hooks):
json
{
"decision": "approve" | "block",
"reason": "Why this decision was made"
}See references/input-output-schemas.md for complete schemas for each hook type.
</input_output>
<environment_variables>
Available in hook commands:
| Variable | Value |
|---|---|
| Project root directory |
| Plugin directory (plugin hooks only) |
| Hook input JSON (prompt hooks only) |
Example:
json
{
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate.sh"
}</environment_variables>
<common_patterns>
Desktop notification when input needed:
json
{
"hooks": {
"Notification": [
{
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs input\" with title \"Claude Code\"'"
}
]
}
]
}
}Block destructive git commands:
json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "prompt",
"prompt": "Check if this command is destructive: $ARGUMENTS\n\nBlock if it contains: 'git push --force', 'rm -rf', 'git reset --hard'\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"
}
]
}
]
}
}Auto-format code after edits:
json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "prettier --write $CLAUDE_PROJECT_DIR",
"timeout": 10000
}
]
}
]
}
}Add context at session start:
json
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"SessionStart\", \"additionalContext\": \"Current sprint: Sprint 23. Focus: User authentication\"}}'"
}
]
}
]
}
}</common_patterns>
<debugging>
Always test hooks with the debug flag:
```bash
claude --debug
```
This shows which hooks matched, command execution, and output. See references/troubleshooting.md for common issues and solutions.
</debugging>
<reference_guides>
Hook types and events: references/hook-types.md
- Complete list of hook events
- When each event fires
- Input/output schemas for each
- Blocking vs non-blocking hooks
Command vs Prompt hooks: references/command-vs-prompt.md
- Decision tree: which type to use
- Command hook patterns and examples
- Prompt hook patterns and examples
- Performance considerations
Matchers and patterns: references/matchers.md
- Regex patterns for tool matching
- MCP tool matching patterns
- Multiple tool matching
- Debugging matcher issues
Input/Output schemas: references/input-output-schemas.md
- Complete schema for each hook type
- Field descriptions and types
- Hook-specific output fields
- Example JSON for each event
Working examples: references/examples.md
- Desktop notifications
- Command validation
- Auto-formatting workflows
- Logging and audit trails
- Stop logic patterns
- Session context injection
Troubleshooting: references/troubleshooting.md
- Hooks not triggering
- Command execution failures
- Prompt hook issues
- Permission problems
- Timeout handling
- Debug workflow </reference_guides>
<security_checklist>
Critical safety requirements:
- Infinite loop prevention: Check flag in Stop hooks to prevent recursive triggering
stop_hook_active - Timeout configuration: Set reasonable timeouts (default: 60s) to prevent hanging
- Permission validation: Ensure hook scripts have executable permissions ()
chmod +x - Path safety: Use absolute paths with to avoid path injection
$CLAUDE_PROJECT_DIR - JSON validation: Validate hook config with before use to catch syntax errors
jq - Selective blocking: Be conservative with blocking hooks to avoid workflow disruption
Testing protocol:
bash
undefined<objective>
Hooks是Claude Code的事件驱动型自动化机制,可响应工具使用、会话事件和用户交互来执行shell命令或LLM提示词。本技能将教您如何创建、配置和调试hooks,以实现命令验证、工作流自动化、上下文注入以及自定义完成条件的设置。
:
</matchers>
无需修改核心代码,Hooks就能让您以编程方式控制Claude的行为,从而实现项目专属的自动化、安全检查和工作流定制。
</objective>
<context>
Hooks是响应Claude Code事件执行的shell命令或经LLM评估的提示词。它们在事件层级结构中运作:事件(PreToolUse、PostToolUse、Stop等)触发匹配器(工具模式),进而触发hooks(命令或提示词)。Hooks可以阻止操作、修改工具输入、注入上下文,或仅用于观察和记录Claude的操作。
</context>
<quick_start>
<workflow>
- 创建hooks配置文件:
- 项目级:
.claude/hooks.json - 用户级:
~/.claude/hooks.json
- 项目级:
- 选择hook触发事件(何时执行)
- 选择hook类型(命令型或提示词型)
- 配置匹配器(触发该hook的工具)
- 使用进行测试 </workflow>
claude --debug
.claude/hooks.jsonjson
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \\\"No description\\\")\"' >> ~/.claude/bash-log.txt"
}
]
}
]
}
}该hook的作用:
- 在每次使用工具前(
Bash)触发PreToolUse - 执行一条(而非LLM提示词)
command - 将命令+描述记录到文件中 </example>
</quick_start>
<hook_types>
| 事件 | 触发时机 | 是否可阻止操作? |
|---|---|---|
| PreToolUse | 工具执行前 | 是 |
| PostToolUse | 工具执行后 | 否 |
| UserPromptSubmit | 用户提交提示词后 | 是 |
| Stop | Claude尝试停止时 | 是 |
| SubagentStop | 子Agent尝试停止时 | 是 |
| SessionStart | 会话开始时 | 否 |
| SessionEnd | 会话结束时 | 否 |
| PreCompact | 上下文压缩前 | 是 |
| Notification | Claude需要输入时 | 否 |
可阻止操作的hooks可返回来阻止对应操作。更多详细用例请查看references/hook-types.md。
</hook_types>
"decision": "block"<hook_anatomy>
<hook_type name="command">
类型:执行shell命令
适用场景:
- 简单验证(检查文件是否存在)
- 日志记录(追加到文件)
- 外部工具(格式化工具、代码检查工具)
- 桌面通知
输入:通过标准输入(stdin)传递JSON
输出:通过标准输出(stdout)返回JSON(可选)
json
{
"type": "command",
"command": "/path/to/script.sh",
"timeout": 30000
}</hook_type>
<hook_type name="prompt">
类型:由LLM评估提示词
适用场景:
- 复杂决策逻辑
- 自然语言验证
- 上下文感知检查
- 需要推理的场景
输入:包含占位符的提示词
输出:包含和的JSON
$ARGUMENTSdecisionreasonjson
{
"type": "prompt",
"prompt": "Evaluate if this command is safe: $ARGUMENTS\n\nReturn JSON: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"
}</hook_type>
</hook_anatomy>
<matchers>
匹配器用于筛选触发hook的工具:
json
{
"matcher": "Bash", // 精确匹配
"matcher": "Write|Edit", // 多个工具(正则表达式或)
"matcher": "mcp__.*", // 所有MCP工具
"matcher": "mcp__memory__.*" // 特定MCP服务器
}无匹配器:该hook会对所有工具触发
json
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [...] // 无匹配器 - 每次用户提交提示词时触发
}
]
}
}<input_output>
Hooks通过标准输入(stdin)接收包含会话信息、当前目录和事件特定数据的JSON。可阻止操作的hooks可返回JSON来批准/阻止操作或修改输入。
示例输出(可阻止操作的hooks):
json
{
"decision": "approve" | "block",
"reason": "Why this decision was made"
}各hook类型的完整模式请查看references/input-output-schemas.md。
</input_output>
<environment_variables>
hook命令中可用的环境变量:
| 变量 | 取值 |
|---|---|
| 项目根目录 |
| 插件目录(仅适用于插件hooks) |
| Hook输入JSON(仅适用于提示词型hooks) |
示例:
json
{
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate.sh"
}</environment_variables>
<common_patterns>
需要输入时发送桌面通知:
json
{
"hooks": {
"Notification": [
{
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs input\" with title \"Claude Code\"'"
}
]
}
]
}
}阻止破坏性git命令:
json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "prompt",
"prompt": "Check if this command is destructive: $ARGUMENTS\n\nBlock if it contains: 'git push --force', 'rm -rf', 'git reset --hard'\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"
}
]
}
]
}
}编辑后自动格式化代码:
json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "prettier --write $CLAUDE_PROJECT_DIR",
"timeout": 10000
}
]
}
]
}
}会话开始时添加上下文:
json
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"SessionStart\", \"additionalContext\": \"Current sprint: Sprint 23. Focus: User authentication\"}}'"
}
]
}
]
}
}</common_patterns>
<debugging>
请始终使用调试标志测试hooks:
```bash
claude --debug
```
该命令会显示匹配的hooks、命令执行情况和输出。常见问题及解决方案请查看references/troubleshooting.md。
</debugging>
<reference_guides>
Hook类型与事件:references/hook-types.md
- 完整的hook事件列表
- 各事件的触发时机
- 各事件的输入/输出模式
- 可阻止与不可阻止hooks的区别
命令型vs提示词型hooks:references/command-vs-prompt.md
- 决策树:如何选择hook类型
- 命令型hook的模式与示例
- 提示词型hook的模式与示例
- 性能考量
匹配器与模式:references/matchers.md
- 工具匹配的正则表达式模式
- MCP工具匹配模式
- 多工具匹配
- 匹配器问题调试
输入/输出模式:references/input-output-schemas.md
- 各hook类型的完整模式
- 字段说明与类型
- 特定hook的输出字段
- 各事件的JSON示例
实用示例:references/examples.md
- 桌面通知
- 命令验证
- 自动格式化工作流
- 日志与审计跟踪
- 停止逻辑模式
- 会话上下文注入
故障排除:references/troubleshooting.md
- Hooks未触发
- 命令执行失败
- 提示词型hook问题
- 权限问题
- 超时处理
- 调试工作流 </reference_guides>
<security_checklist>
关键安全要求:
- 防止无限循环:在Stop hooks中检查标志,避免递归触发
stop_hook_active - 超时配置:设置合理的超时时间(默认:60秒),防止进程挂起
- 权限验证:确保hook脚本具有可执行权限()
chmod +x - 路径安全:结合使用绝对路径,避免路径注入
$CLAUDE_PROJECT_DIR - JSON验证:使用验证hook配置,提前发现语法错误
jq - 选择性阻止:谨慎使用可阻止操作的hooks,避免干扰工作流
测试流程:
bash
undefinedAlways test with debug flag first
请始终先使用调试标志测试
claude --debug
claude --debug
Validate JSON config
验证JSON配置
jq . .claude/hooks.json
</security_checklist>
<success_criteria>
A working hook configuration has:
- Valid JSON in `.claude/hooks.json` (validated with `jq`)
- Appropriate hook event selected for the use case
- Correct matcher pattern that matches target tools
- Command or prompt that executes without errors
- Proper output schema (decision/reason for blocking hooks)
- Tested with `--debug` flag showing expected behavior
- No infinite loops in Stop hooks (checks `stop_hook_active` flag)
- Reasonable timeout set (especially for external commands)
- Executable permissions on script files if using file paths
</success_criteria>jq . .claude/hooks.json
</security_checklist>
<success_criteria>
一个可用的hook配置需满足:
- `.claude/hooks.json`中的JSON格式有效(已通过`jq`验证)
- 为使用场景选择了合适的hook事件
- 匹配器模式正确匹配目标工具
- 命令或提示词可无错误执行
- 输出模式正确(可阻止操作的hooks需包含decision/reason)
- 使用`--debug`标志测试后表现符合预期
- Stop hooks中无无限循环(已检查`stop_hook_active`标志)
- 设置了合理的超时时间(尤其是外部命令)
- 若使用文件路径,脚本文件具备可执行权限
</success_criteria>