Claude Code 的 Hooks 機制能讓你在工具呼叫的前後插入自訂邏輯。先前的文章介紹過用 Stop Hook 做任務完成通知,這次分享四個更實用的情境:攔截不合理的 Agent 呼叫、自動格式化程式碼、修改文章後自動截圖驗證、提交前檢查建置。

它們的共同點:全都是踩了坑才加上的。


Hooks 機制速覽

Hooks 在 ~/.claude/settings.json 的 hooks 欄位設定,支援三個觸發時機:

時機 觸發點 典型用途
PreToolUse 工具呼叫前 攔截、驗證、前處理
PostToolUse 工具呼叫後 格式化、通知、驗證
Stop 工作階段結束時 通知、收尾

每個 hook 都是一個腳本,透過 stdin 接收 JSON 格式的工具呼叫資訊,結束代碼 0 放行、2 攔截。


案例 1:攔截 Agent 濫用

踩坑情境:Claude Code 有時會用 Agent 子呼叫去做本來一個 Read 就能搞定的事——「幫我讀一下那個檔案」。一次 Agent 呼叫要啟動新程序、載入上下文,耗時好幾秒,而直接 Read 只要 0.1 秒。更糟的是 Explore agent,每次呼叫都要進行大量程式碼搜尋,對簡單的查找來說簡直是殺雞用牛刀。

Hook 腳本 ~/.claude/hooks/pre_tool_use_agent_guard.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
"""
PreToolUse hook: 攔截 Agent 工具被用於本機工具可直接完成的簡單操作。
"""

import json
import sys

hook_input = json.load(sys.stdin)
tool = hook_input.get("tool_name", "")

if tool != "Agent":
sys.exit(0)

tool_input = hook_input.get("tool_input", {})
prompt = tool_input.get("prompt", "").lower()
subagent_type = tool_input.get("subagent_type", "")

# Explore agent 一律攔截:本機程式碼探索用 Glob/Grep/Read 直接完成
if subagent_type == "Explore":
print(
"Explore agent 被攔截:本機程式碼探索應直接使用 Glob/Grep/Read 工具,"
"禁止透過子 Agent 中轉(CLAUDE.md 規則)。",
file=sys.stderr,
)
sys.exit(2)

# 簡單操作關鍵字(命中則攔截)
SIMPLE_PATTERNS = [
"read the following", "read file", "return full content",
"get the content", "fetch the file", "list files",
"search for", "find files", "grep for",
"讀取以下", "讀取檔案", "列出檔案",
"搜尋", "尋找檔案", "回傳完整內容",
]

# 複雜操作關鍵字(命中則跳過攔截)
COMPLEX_PATTERNS = [
"分析", "對比", "理解", "設計", "實作", "評估",
"規劃", "梳理", "報告",
"analyze", "compare", "design", "implement", "evaluate", "report",
]

complex_matched = [p for p in COMPLEX_PATTERNS if p in prompt]
matched = [p for p in SIMPLE_PATTERNS if p in prompt]

if matched and not complex_matched:
print(
f"Agent 被攔截:匹配關鍵字「{matched[0]}」,"
f"請直接用 Read/Glob/Grep 完成。",
file=sys.stderr,
)
sys.exit(2)

sys.exit(0)

設計重點:

  • Explore agent 一律攔截 — 簡單粗暴但有效,本機程式碼探索不需要子程序
  • 白名單機制 — 「讀取檔案並分析架構」這種複雜任務命中 分析 關鍵字,不會被誤攔
  • 中英雙語關鍵字 — 日常用中文下指令也不會漏掉

設定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"PreToolUse": [
{
"matcher": "Agent",
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/pre_tool_use_agent_guard.py"
}
]
}
]
}
}

matcher: "Agent" 讓這個 hook 只在呼叫 Agent 工具時觸發,不影響其他工具。


案例 2:C++ 檔案自動格式化

踩坑情境:讓 Claude Code 寫 C++ 程式碼,它產生的程式碼風格與專案不一致。每次都要手動跑 clang-format,或者提醒它「寫完後格式化」。加個 PostToolUse hook,寫完自動格式化,徹底不用管。

Hook 腳本 ~/.claude/hooks/clang-format.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
# PostToolUse hook: C++ 檔案修改後自動執行 clang-format

INPUT=$(cat)

FILE_PATH=$(echo "$INPUT" | python3 -c "
import json, sys
try:
data = json.load(sys.stdin)
print(data.get('tool_input', {}).get('file_path', ''))
except Exception:
print('')
" 2>/dev/null)

# 沒拿到路徑就結束
[ -z "$FILE_PATH" ] && exit 0

# 只處理 C++ 檔案
case "$FILE_PATH" in
*.cpp|*.cc|*.cxx|*.c|*.h|*.hpp|*.hh)
[ ! -f "$FILE_PATH" ] && exit 0
clang-format -i "$FILE_PATH" 2>/dev/null
if [ $? -eq 0 ]; then
echo "已自動格式化:$FILE_PATH"
fi
;;
esac

exit 0

設計重點:

  • 透過 stdin JSON 讀取 .tool_input.file_path — Claude Code 統一透過標準輸入把工具參數傳給 Hook 腳本
  • clang-format -i 直接原地修改 — 格式化結果靜默生效,不阻塞工作流
  • 格式化失敗靜默結束 — 不會因為 .clang-format 設定檔缺失而阻斷正常操作

案例 3:部落格文章截圖驗證

踩坑情境:讓 Claude Code 修改部落格文章,改完 push 上線才發現排版爆掉——程式碼區塊溢位、圖片沒載入、表格太寬。如果能在每次修改後自動截圖看一眼,就能在推送前發現問題。

Hook 腳本 專案/.claude/hooks/screenshot-hook.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
# PostToolUse Hook: 文章/設定修改後自動截圖驗證

PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"
INPUT=$(cat)

# 擷取 file_path(多種 fallback 方式)
FILE_PATH=""
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty' 2>/dev/null)
[ -z "$FILE_PATH" ] && FILE_PATH=$(echo "$INPUT" | jq -r '.. | objects | select(has("file_path")) | .file_path' 2>/dev/null | head -1)

[ -z "$FILE_PATH" ] && exit 0

# 只匹配部落格文章和設定檔
case "$FILE_PATH" in
*source/_posts/*|*_config*.yml)
echo "📸 正在產生預覽截圖..."
node "$PROJECT_DIR/.claude/hooks/screenshot-verify.js" "$FILE_PATH" 2>&1
;;
esac

screenshot-verify.js 用 puppeteer 截圖,會自動偵測並啟動 hexo server。這個腳本比較長,核心流程如下:

  1. 檢查 hexo server 是否正在執行(curl localhost:4000)
  2. 沒執行就用 hexo clean && hexo server 啟動
  3. puppeteer 開啟對應的文章頁面,進行全頁截圖
  4. 截圖儲存到 .claude-output/screenshots/,並將路徑輸出到工作階段

設計重點:

  • 路徑比對過濾 — 只對 source/_posts/* 和 _config*.yml 觸發,改別的檔案不會截圖
  • hexo server 自動管理 — 沒執行就自動啟動,不重複啟動
  • .claude-output/ 加入 .gitignore — 截圖是暫時驗證產物,不納入版本控制

案例 4:提交前 hexo 建置檢查

踩坑情境:文章 Front Matter 的 YAML 格式寫錯了一個縮排,push 上去才發現 GitHub Actions 建置失敗。加個 PreToolUse hook,在 git commit 前先跑一遍 hexo generate,建置沒過就不讓提交。

Hook 腳本 ~/.claude/hooks/pre-tool-use-bash-guard.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
# PreToolUse hook: git commit 前檢查 hexo 建置

INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""' 2>/dev/null)

# 只攔截 git commit
echo "$COMMAND" | grep -q 'git commit' || exit 0

PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"

# 執行 hexo generate 檢查建置
cd "$PROJECT_DIR"
hexo generate > /dev/null 2>&1

if [ $? -ne 0 ]; then
echo "hexo generate 失敗,請檢查文章格式後再提交。" >&2
exit 2
fi

exit 0

設計重點:

  • 只攔截 git commit — git add、git status 等不受影響
  • 建置失敗直接 block — 寫入 stderr 並以結束代碼 2 阻止提交(在 exit 2 協定下,Claude 會讀取 stderr 作為阻斷原因,並忽略 stdout)
  • hexo generate 輸出靜默 — 成功時不輸出任何東西,不干擾正常流程

四個 Hook 的設定彙整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
"hooks": {
"PreToolUse": [
{
"matcher": "Agent",
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/pre_tool_use_agent_guard.py"
}
]
},
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/pre-tool-use-bash-guard.sh"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "bash 專案路徑/.claude/hooks/screenshot-hook.sh"
}
]
},
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/clang-format.sh"
}
]
}
]
}
}
Hook 時機 matcher 作用
Agent 攔截 PreToolUse Agent 防止用 Agent 做本機工具就能完成的事
hexo 建置檢查 PreToolUse Bash git commit 前驗證建置
截圖驗證 PostToolUse Write|Edit 文章修改後自動截圖
clang-format PostToolUse Write|Edit C++ 檔案自動格式化

小結

Hooks 的核心價值:把踩過的坑變成自動化的防線。每個 hook 都對應一個真實的問題——Agent 濫用浪費時間、程式碼風格不一致、文章排版爆掉、建置失敗才發現。與其每次手動檢查,不如讓腳本自動處理。

寫 hook 時注意三點:

  • 攔截要精確 — matcher 和路徑比對越精確,誤攔就越少
  • 失敗要靜默 — hook 報錯不應該阻斷正常工作流(除非那本來就是它的目的)
  • 回饋要清晰 — block 時要告訴使用者為什麼攔、該怎麼做

系列導覽