如需包含範例的快速入門指南,請參閱 Claude Code hooks 入門

設定

Claude Code hooks 在您的設定檔案中進行設定:

  • ~/.claude/settings.json - 使用者設定
  • .claude/settings.json - 專案設定
  • .claude/settings.local.json - 本地專案設定(不提交)
  • 企業管理政策設定

結構

Hooks 按匹配器組織,每個匹配器可以有多個 hooks:

{
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolPattern",
        "hooks": [
          {
            "type": "command",
            "command": "your-command-here"
          }
        ]
      }
    ]
  }
}
  • matcher:匹配工具名稱的模式,區分大小寫(僅適用於 PreToolUsePostToolUse
    • 簡單字串完全匹配:Write 僅匹配 Write 工具
    • 支援正規表達式:Edit|WriteNotebook.*
    • 使用 * 匹配所有工具。您也可以使用空字串("")或將 matcher 留空。
  • hooks:當模式匹配時要執行的命令陣列
    • type:目前僅支援 "command"
    • command:要執行的 bash 命令(可以使用 $CLAUDE_PROJECT_DIR 環境變數)
    • timeout:(可選)命令應該執行多長時間(以秒為單位),超過時間後取消該特定命令。

對於像 UserPromptSubmitNotificationStopSubagentStop 這樣不使用匹配器的事件,您可以省略匹配器欄位:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "/path/to/prompt-validator.py"
          }
        ]
      }
    ]
  }
}

專案特定的 Hook 腳本

您可以使用環境變數 CLAUDE_PROJECT_DIR(僅在 Claude Code 產生 hook 命令時可用)來引用儲存在專案中的腳本,確保無論 Claude 的當前目錄如何,它們都能正常工作:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/check-style.sh"
          }
        ]
      }
    ]
  }
}

Hook 事件

PreToolUse

在 Claude 建立工具參數之後、處理工具呼叫之前執行。

常見匹配器:

  • Task - 代理任務
  • Bash - Shell 命令
  • Glob - 檔案模式匹配
  • Grep - 內容搜尋
  • Read - 檔案讀取
  • EditMultiEdit - 檔案編輯
  • Write - 檔案寫入
  • WebFetchWebSearch - 網路操作

PostToolUse

在工具成功完成後立即執行。

識別與 PreToolUse 相同的匹配器值。

Notification

當 Claude Code 發送通知時執行。通知在以下情況下發送:

  1. Claude 需要您的許可才能使用工具。例如:“Claude needs your permission to use Bash”
  2. 提示輸入已閒置至少 60 秒。“Claude is waiting for your input”

UserPromptSubmit

當使用者提交提示時、Claude 處理之前執行。這允許您根據提示/對話添加額外的上下文、驗證提示或阻止某些類型的提示。

Stop

當主要的 Claude Code 代理完成回應時執行。如果停止是由於使用者中斷而發生的,則不會執行。

SubagentStop

當 Claude Code 子代理(Task 工具呼叫)完成回應時執行。

PreCompact

在 Claude Code 即將執行壓縮操作之前執行。

匹配器:

  • manual - 從 /compact 呼叫
  • auto - 從自動壓縮呼叫(由於上下文視窗已滿)

Hook 輸入

Hooks 透過 stdin 接收包含會話資訊和事件特定資料的 JSON 資料:

{
  // 通用欄位
  session_id: string
  transcript_path: string  // 對話 JSON 的路徑
  cwd: string              // 呼叫 hook 時的當前工作目錄

  // 事件特定欄位
  hook_event_name: string
  ...
}

PreToolUse 輸入

tool_input 的確切架構取決於工具。

{
  "session_id": "abc123",
  "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
  "cwd": "/Users/...",
  "hook_event_name": "PreToolUse",
  "tool_name": "Write",
  "tool_input": {
    "file_path": "/path/to/file.txt",
    "content": "file content"
  }
}

PostToolUse 輸入

tool_inputtool_response 的確切架構取決於工具。

{
  "session_id": "abc123",
  "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
  "cwd": "/Users/...",
  "hook_event_name": "PostToolUse",
  "tool_name": "Write",
  "tool_input": {
    "file_path": "/path/to/file.txt",
    "content": "file content"
  },
  "tool_response": {
    "filePath": "/path/to/file.txt",
    "success": true
  }
}

Notification 輸入

{
  "session_id": "abc123",
  "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
  "cwd": "/Users/...",
  "hook_event_name": "Notification",
  "message": "Task completed successfully"
}

UserPromptSubmit 輸入

{
  "session_id": "abc123",
  "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
  "cwd": "/Users/...",
  "hook_event_name": "UserPromptSubmit",
  "prompt": "Write a function to calculate the factorial of a number"
}

Stop 和 SubagentStop 輸入

當 Claude Code 已經因為 stop hook 而繼續時,stop_hook_active 為 true。檢查此值或處理記錄以防止 Claude Code 無限期執行。

{
  "session_id": "abc123",
  "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
  "hook_event_name": "Stop",
  "stop_hook_active": true
}

PreCompact 輸入

對於 manualcustom_instructions 來自使用者傳遞給 /compact 的內容。對於 autocustom_instructions 為空。

{
  "session_id": "abc123",
  "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
  "hook_event_name": "PreCompact",
  "trigger": "manual",
  "custom_instructions": ""
}

Hook 輸出

有兩種方式讓 hooks 將輸出返回給 Claude Code。輸出傳達是否阻止以及應該向 Claude 和使用者顯示的任何回饋。

簡單:退出代碼

Hooks 透過退出代碼、stdout 和 stderr 傳達狀態:

  • 退出代碼 0:成功。stdout 在記錄模式(CTRL-R)中向使用者顯示,除了 UserPromptSubmit,其中 stdout 被添加到上下文中。
  • 退出代碼 2:阻止錯誤。stderr 被回饋給 Claude 自動處理。請參閱下面的每個 hook 事件行為。
  • 其他退出代碼:非阻止錯誤。stderr 向使用者顯示,執行繼續。

提醒:如果退出代碼為 0,Claude Code 不會看到 stdout,除了 UserPromptSubmit hook,其中 stdout 被注入為上下文。

退出代碼 2 行為

Hook 事件行為
PreToolUse阻止工具呼叫,向 Claude 顯示 stderr
PostToolUse向 Claude 顯示 stderr(工具已經執行)
NotificationN/A,僅向使用者顯示 stderr
UserPromptSubmit阻止提示處理,清除提示,僅向使用者顯示 stderr
Stop阻止停止,向 Claude 顯示 stderr
SubagentStop阻止停止,向 Claude 子代理顯示 stderr
PreCompactN/A,僅向使用者顯示 stderr

進階:JSON 輸出

Hooks 可以在 stdout 中返回結構化 JSON 以進行更複雜的控制:

通用 JSON 欄位

所有 hook 類型都可以包含這些可選欄位:

{
  "continue": true, // Claude 是否應該在 hook 執行後繼續(預設:true)
  "stopReason": "string" // 當 continue 為 false 時顯示的訊息
  "suppressOutput": true, // 在記錄模式中隱藏 stdout(預設:false)
}

如果 continue 為 false,Claude 在 hooks 執行後停止處理。

  • 對於 PreToolUse,這與 "permissionDecision": "deny" 不同,後者只阻止特定的工具呼叫並向 Claude 提供自動回饋。
  • 對於 PostToolUse,這與 "decision": "block" 不同,後者向 Claude 提供自動回饋。
  • 對於 UserPromptSubmit,這防止提示被處理。
  • 對於 StopSubagentStop,這優先於任何 "decision": "block" 輸出。
  • 在所有情況下,"continue" = false 優先於任何 "decision": "block" 輸出。

stopReason 伴隨 continue 提供向使用者顯示的原因,不向 Claude 顯示。

PreToolUse 決策控制

PreToolUse hooks 可以控制工具呼叫是否繼續。

  • "allow" 繞過許可系統。permissionDecisionReason 向使用者顯示但不向 Claude 顯示。(已棄用的 "approve" 值 + reason 具有相同行為。
  • "deny" 防止工具呼叫執行。permissionDecisionReason 向 Claude 顯示。("block" 值 + reason 具有相同行為。
  • "ask" 要求使用者在 UI 中確認工具呼叫。permissionDecisionReason 向使用者顯示但不向 Claude 顯示。
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow" | "deny" | "ask",
    "permissionDecisionReason": "My reason here (shown to user)"
  },
  "decision": "approve" | "block" | undefined, // 對 PreToolUse 已棄用但仍支援
  "reason": "Explanation for decision" // 對 PreToolUse 已棄用但仍支援
}

PostToolUse 決策控制

PostToolUse hooks 可以控制工具呼叫是否繼續。

  • "block" 自動用 reason 提示 Claude。
  • undefined 什麼都不做。reason 被忽略。
{
  "decision": "block" | undefined,
  "reason": "Explanation for decision"
}

UserPromptSubmit 決策控制

UserPromptSubmit hooks 可以控制使用者提示是否被處理。

  • "block" 防止提示被處理。提交的提示從上下文中清除。"reason" 向使用者顯示但不添加到上下文中。
  • undefined 允許提示正常進行。"reason" 被忽略。
  • "hookSpecificOutput.additionalContext" 如果未被阻止,將字串添加到上下文中。
{
  "decision": "block" | undefined,
  "reason": "Explanation for decision",
  "hookSpecificOutput": {
    "hookEventName": "UserPromptSubmit",
    "additionalContext": "My additional context here"
  }
}

Stop/SubagentStop 決策控制

StopSubagentStop hooks 可以控制 Claude 是否必須繼續。

  • "block" 防止 Claude 停止。您必須填充 reason 讓 Claude 知道如何繼續。
  • undefined 允許 Claude 停止。reason 被忽略。
{
  "decision": "block" | undefined,
  "reason": "Must be provided when Claude is blocked from stopping"
}

退出代碼範例:Bash 命令驗證

#!/usr/bin/env python3
import json
import re
import sys

# 將驗證規則定義為 (正規表達式模式, 訊息) 元組的列表
VALIDATION_RULES = [
    (
        r"\bgrep\b(?!.*\|)",
        "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
    ),
    (
        r"\bfind\s+\S+\s+-name\b",
        "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
    ),
]


def validate_command(command: str) -> list[str]:
    issues = []
    for pattern, message in VALIDATION_RULES:
        if re.search(pattern, command):
            issues.append(message)
    return issues


try:
    input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
    print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
    sys.exit(1)

tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
command = tool_input.get("command", "")

if tool_name != "Bash" or not command:
    sys.exit(1)

# 驗證命令
issues = validate_command(command)

if issues:
    for message in issues:
        print(f"• {message}", file=sys.stderr)
    # 退出代碼 2 阻止工具呼叫並向 Claude 顯示 stderr
    sys.exit(2)

JSON 輸出範例:UserPromptSubmit 添加上下文和驗證

對於 UserPromptSubmit hooks,您可以使用任一方法注入上下文:

  • 退出代碼 0 與 stdout:Claude 看到上下文(UserPromptSubmit 的特殊情況)
  • JSON 輸出:提供對行為的更多控制
#!/usr/bin/env python3
import json
import sys
import re
import datetime

# 從 stdin 載入輸入
try:
    input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
    print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
    sys.exit(1)

prompt = input_data.get("prompt", "")

# 檢查敏感模式
sensitive_patterns = [
    (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
]

for pattern, message in sensitive_patterns:
    if re.search(pattern, prompt):
        # 使用 JSON 輸出以特定原因阻止
        output = {
            "decision": "block",
            "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
        }
        print(json.dumps(output))
        sys.exit(0)

# 將當前時間添加到上下文
context = f"Current time: {datetime.datetime.now()}"
print(context)

"""
以下也是等效的:
print(json.dumps({
  "hookSpecificOutput": {
    "hookEventName": "UserPromptSubmit",
    "additionalContext": context,
  },
}))
"""

# 允許提示繼續進行並添加額外上下文
sys.exit(0)

JSON 輸出範例:PreToolUse 與批准

#!/usr/bin/env python3
import json
import sys

# 從 stdin 載入輸入
try:
    input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
    print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
    sys.exit(1)

tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})

# 範例:自動批准文件檔案的檔案讀取
if tool_name == "Read":
    file_path = tool_input.get("file_path", "")
    if file_path.endswith((".md", ".mdx", ".txt", ".json")):
        # 使用 JSON 輸出自動批准工具呼叫
        output = {
            "decision": "approve",
            "reason": "Documentation file auto-approved",
            "suppressOutput": True  # 不在記錄模式中顯示
        }
        print(json.dumps(output))
        sys.exit(0)

# 對於其他情況,讓正常的許可流程繼續
sys.exit(0)

與 MCP 工具協作

Claude Code hooks 與模型上下文協定(MCP)工具無縫協作。當 MCP 伺服器提供工具時,它們以特殊的命名模式出現,您可以在 hooks 中匹配。

MCP 工具命名

MCP 工具遵循模式 mcp__<server>__<tool>,例如:

  • mcp__memory__create_entities - Memory 伺服器的建立實體工具
  • mcp__filesystem__read_file - Filesystem 伺服器的讀取檔案工具
  • mcp__github__search_repositories - GitHub 伺服器的搜尋工具

為 MCP 工具設定 Hooks

您可以針對特定的 MCP 工具或整個 MCP 伺服器:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "mcp__memory__.*",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
          }
        ]
      },
      {
        "matcher": "mcp__.*__write.*",
        "hooks": [
          {
            "type": "command",
            "command": "/home/user/scripts/validate-mcp-write.py"
          }
        ]
      }
    ]
  }
}

範例

如需包括程式碼格式化、通知和檔案保護的實用範例,請參閱入門指南中的更多範例

安全考量

免責聲明

使用風險自負:Claude Code hooks 會在您的系統上自動執行任意 shell 命令。透過使用 hooks,您承認:

  • 您對您設定的命令負全責
  • Hooks 可以修改、刪除或存取您的使用者帳戶可以存取的任何檔案
  • 惡意或編寫不當的 hooks 可能導致資料遺失或系統損壞
  • Anthropic 不提供保證並對因使用 hook 而導致的任何損害不承擔責任
  • 您應該在生產使用之前在安全環境中徹底測試 hooks

在將任何 hook 命令添加到您的設定之前,請務必檢查並理解它們。

安全最佳實務

以下是編寫更安全 hooks 的一些關鍵實務:

  1. 驗證和清理輸入 - 永遠不要盲目信任輸入資料
  2. 總是引用 shell 變數 - 使用 "$VAR" 而不是 $VAR
  3. 阻止路徑遍歷 - 檢查檔案路徑中的 ..
  4. 使用絕對路徑 - 為腳本指定完整路徑(使用 $CLAUDE_PROJECT_DIR 作為專案路徑)
  5. 跳過敏感檔案 - 避免 .env.git/、金鑰等

設定安全

直接編輯設定檔案中的 hooks 不會立即生效。Claude Code:

  1. 在啟動時擷取 hooks 的快照
  2. 在整個會話中使用此快照
  3. 如果 hooks 被外部修改則發出警告
  4. 需要在 /hooks 選單中檢查才能應用變更

這防止惡意的 hook 修改影響您當前的會話。

Hook 執行詳細資訊

  • 逾時:預設 60 秒執行限制,每個命令可設定。
    • 個別命令的逾時不會影響其他命令。
  • 平行化:所有匹配的 hooks 平行執行
  • 環境:在當前目錄中使用 Claude Code 的環境執行
    • CLAUDE_PROJECT_DIR 環境變數可用,包含專案根目錄的絕對路徑
  • 輸入:透過 stdin 的 JSON
  • 輸出
    • PreToolUse/PostToolUse/Stop:進度在記錄中顯示(Ctrl-R)
    • Notification:僅記錄到除錯(--debug

除錯

基本故障排除

如果您的 hooks 無法正常工作:

  1. 檢查設定 - 執行 /hooks 查看您的 hook 是否已註冊
  2. 驗證語法 - 確保您的 JSON 設定有效
  3. 測試命令 - 首先手動執行 hook 命令
  4. 檢查權限 - 確保腳本可執行
  5. 檢查日誌 - 使用 claude --debug 查看 hook 執行詳細資訊

常見問題:

  • 引號未轉義 - 在 JSON 字串內使用 \"
  • 錯誤的匹配器 - 檢查工具名稱完全匹配(區分大小寫)
  • 找不到命令 - 為腳本使用完整路徑

進階除錯

對於複雜的 hook 問題:

  1. 檢查 hook 執行 - 使用 claude --debug 查看詳細的 hook 執行
  2. 驗證 JSON 架構 - 使用外部工具測試 hook 輸入/輸出
  3. 檢查環境變數 - 驗證 Claude Code 的環境是否正確
  4. 測試邊緣情況 - 嘗試使用異常檔案路徑或輸入的 hooks
  5. 監控系統資源 - 檢查 hook 執行期間的資源耗盡
  6. 使用結構化日誌 - 在您的 hook 腳本中實作日誌記錄

除錯輸出範例

使用 claude --debug 查看 hook 執行詳細資訊:

[DEBUG] Executing hooks for PostToolUse:Write
[DEBUG] Getting matching hook commands for PostToolUse with query: Write
[DEBUG] Found 1 hook matchers in settings
[DEBUG] Matched 1 hooks for query "Write"
[DEBUG] Found 1 hook commands to execute
[DEBUG] Executing hook command: <Your command> with timeout 60000ms
[DEBUG] Hook command completed with status 0: <Your stdout>

進度訊息出現在記錄模式(Ctrl-R)中,顯示:

  • 正在執行哪個 hook
  • 正在執行的命令
  • 成功/失敗狀態
  • 輸出或錯誤訊息