
通过skills创建和使用claude skills我们可以服用常用的prompt或者scripts,得到比较稳定的输出,如果希望每次都默认执行或者LLM简单决策下就执行的行为,我们可以使用hook功能。
Hooks 是用户定义的 shell 命令,在 Claude Code 生命周期中的特定点执行。它们对 Claude Code 的行为提供确定性控制,确保某些操作始终发生,而不是依赖 LLM 选择运行它们。使用 hooks 来强制执行项目规则、自动化重复任务,并将 Claude Code 与现有工具集成。对于需要判断而不是确定性规则的决策,你也可以使用 prompt-based hooks 或 agent-based hooks,它们使用 Claude 模型来评估条件。
下面看下如何实现hook,首先可以通过向导创建
/hooks
──────────────────────────────────────────────────
Hooks
5 hooks
❯ 1. PreToolUse - Before tool execution
2. PostToolUse - After tool execution
3. PostToolUseFailure - After tool execution fails
4. Notification - When notifications are sent
↓ 5. UserPromptSubmit - When the user submits a prompt填入我们需要执行的脚本
osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'然后确认后就可以看到安装成功的提示
❯ /hooks
⎿ Added Notification hook: osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'
Added Notification hook: jq -r '.tool_input.file_path | select(endswith(".go"))' | xargs -r gofmt -w这个hook命令保存到哪里了呢?打开.claude/settings.json,可以看到下面的内容
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
},
{
"type": "command",
"command": "jq -r '.tool_input.file_path | select(endswith(\".go\"))' | xargs -r gofmt -w"
}
]
}
],
}本质上在配置文件中增加hook点需要执行的命令。对于大量的命令可以定义hook脚本,创建 hook 脚本,将其保存到 .claude/hooks/protect-files.sh
chmod +x .claude/hooks/protect-files.sh然后把配置文件这册到settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
}
]
}
]
}
}可以看到每个hook都有一个type字段,除了command三种其他类型可用:
"type": "http":将事件数据 POST 到 URL。请参阅 HTTP hooks。
"type": "prompt":单轮 LLM 评估。请参阅 Prompt-based hooks。
"type": "agent":具有工具访问权限的多轮验证。请参阅 Agent-based hooks。如何使用呢?每次执行到对应的hook点会自动执行,比如我们添加了下面两个hook
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
},
{
"type": "command",
"command": "jq -r '.tool_input.file_path | select(endswith(\".go\"))' | xargs -r gofmt -w"
}
]
}
],简单测试下
❯ 1+1
⏺ 2
✢ Thinking… (running stop hooks… 1/2)
⏺ Ran 2 stop hooks (ctrl+o to expand)
⎿ Stop hook error: JSON validation failed完整的hook点如下
When a session begins or resumes本文分享自 golang算法架构leetcode技术php 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!