Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Claude Code Hooks

Claude Code Hooks

Claude Code hooks areuser-defined shell commandsthat automatically execute at specific points in the Claude Code lifecycle.

With hooks, you can achieve precise control over Claude Code's behavior, ensuring that certain operations (such as code formatting and logging)are definitely triggeredrather than relying on the model to decide whether to execute them.

Typical Use Cases for Hooks

Hooks can help you implement many useful features. Common scenarios include:

Compared to constraining Claude's behavior through prompts, hooks areapplication-level hard rulesthat are enforced whenever the corresponding event is triggered, offering greater stability and reliability.

Important Security Warning

When hooks run, theydirectly use the credentials of the current system environment(such as environment variables and user permissions), which poses certain security risks:

Required Security Practices:

  1. Before registering a hook, review the logic and permissions of each command line by line
  2. Avoid running scripts from unknown sources in hooks
  3. For detailed security best practices, refer to the official documentation's Security considerations

Hook Event Type Description

Claude Code has several built-in lifecycle events, and you can bind hook commands to different events. Each event passes different context data and affects Claude's behavior in different ways.

Event Name Trigger Timing Core Role
PreToolUse Tool call, Can intercept tool execution (e.g., block modification of sensitive files) and feed adjustment suggestions back to Claude
PermissionRequest When a permission request dialog pops up Automatically approve or deny permission requests
PostToolUse Tool callAfter completion Perform post-actions (such as formatting code, logging)
UserPromptSubmit After the user submits a prompt, before Claude processes it Preprocess user input (such as supplementing context)
Notification When Claude sends a notification Customize notification methods (such as desktop pop-ups, SMS reminders)
Stop When Claude finishes responding Perform wrap-up work (such as cleaning up temporary files)
SubagentStop When a subagent task completes Process the subagent's execution results
PreCompact When context compaction is about to be executed Customize compaction rules
SessionStart When starting a new session or resuming an old one Initialize the session environment (such as loading project configuration)
SessionEnd When a session ends Save session data, clean up the environment

Quick Start: Implementing Command Logging

Below we take Record all Bash commands executed by Claude as an example, walk you through the configuration and use of hooks step by step.

Prerequisites

Installation jq tool (for parsing JSON data from the command line):

Step 1: Open the Hook Configuration Interface

In the Claude Code interactive interface, enter the slash command /hooks, press Enter, and select the event to bind - here we choose PreToolUse(triggered before tool calls, suitable for logging commands).

Step 2: Add an Event Matcher

The purpose of a matcher is to limit the hook's trigger conditionsso the hook command executes only when the specified tool is invoked.

  1. Choice + Add new matcher…
  2. Enter the matching keyword Bash, indicating the hook triggers only when Claude invokes the Bash tool

Tip: Enter * can matchall toolsto create a global hook

Step 3: Add the Hook Command

Choice + Add new hook…, enter the following command (function: extract the command content and description, write to a log file):

jq -r '"\(.tool_input.command) - \(.tool_input.description // "无描述信息")"' >> ~/.claude/bash-command-log.txt

Command description:

Step 4: Choose the Configuration Storage Location

Where the configuration is saved determines the hook's scope:

Here we choose User settings, to implement global command logging. After selecting, press Esc to exit the configuration interface; the hook is then registered.

Step 5: Verify the Hook Configuration

  1. Enter the /hooks command again to view the list of configured hooks
  2. Or directly open the configuration file ~/.claude/settings.jsonand you will see configuration content like the following:
    {
    
    "hooks": {
    
    "PreToolUse": [
    
    {
    
    "matcher": "Bash",
    
    "hooks": [
    
    {
    
    "type": "command",
    
    "command": "jq -r '"\(.tool_input.command) - \(.tool_input.description // "无描述信息")"' >> ~/.claude/bash-command-log.txt"
    
    }
    
    ]
    
    }
    
    ]
    
    }
    
    }

Step 6: Test the Hook

  1. Enter a command in Claude Code:帮我执行 ls 命令
  2. After execution, view the log file in the terminal:
    cat ~/.claude/bash-command-log.txt
  3. If the following content appears in the log, the hook is configured successfully:
    ls - Lists files and directories

Practical Hook Examples

Below are several commonly used hook configurations that you can copy directly or modify as needed.

For complete example code, refer to the official repository:bash Command Validator Example

Example 1: Automatically Format TypeScript Files

Function: After editing/writing .ts files, automatically use prettier Format Code

{

  "hooks": {

    "PostToolUse": [

      {

        "matcher": "Edit|Write", // 匹配“编辑”和“写入”工具

        "hooks": [

          {

            "type": "command",

            "command": "jq -r '.tool_input.file_path' | { read file_path; if echo \"$file_path\" | grep -q '\\.ts$'; then npx prettier --write \"$file_path\"; fi; }"

          }

        ]

      }

    ]

  }

}

Example 2: Automatically Fix Markdown File Formatting

Function: Automatically add language tags to code blocks without them and clean up extra blank lines

Step 1: Add the Hook Configuration

{

  "hooks": {

    "PostToolUse": [

      {

        "matcher": "Edit|Write",

        "hooks": [

          {

            "type": "command",

            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"

          }

        ]

      }

    ]

  }

}

Step 2: Create the Formatting Script

Create a new file in the project directory .claude/hooks/markdown_formatter.py, paste the following code:

Example

#!/usr/bin/env python3

"""
Markdown formatting tool: automatically add code block language tags and clean up extra blank lines
"""

import

json

import

sys

import

re

import

os

def

detect_language

(

code

)

:

   

"""Automatically detect the programming language based on code content"""

   

code

=

code

.

strip

(

)

   

Detect JSON

   

if

re

.

search

(

r

'^\s*[{[]'

,

code

)

:

       

try

:

            json.

loads

(

code

)

           

return

'json'

       

except

:

           

pass

   

Detect Python

   

if

re

.

search

(

r

'^\sdef\s+\w+\s('

,

code

,

re

.

M

)

or

re

.

search

(

r

'^\s*(import|from)\s+\w+'

,

code

,

re

.

M

)

:

       

return

'python'

   

Detect JavaScript/TypeScript

   

if

re

.

search

(

r

'\b(function\s+\w+\s*(|const\s+\w+\s*=)'

,

code

)

or

re

.

search

(

r

'=>|console.(log|error)'

,

code

)

:

       

return

'javascript'

   

Detect Bash

   

if

re

.

search

(

r

'^#!.*\b(bash|sh)\b'

,

code

,

re

.

M

)

or

re

.

search

(

r

'\b(if|then|fi|for|in|do|done)\b'

,

code

)

:

       

return

'bash'

   

Default text format

   

return

'text'

def

format_markdown

(

content

)

:

   

"""Format Markdown content"""

   

Add language to untagged code blocks

    fence_pattern

=

r

'(?ms)^([ \t]{0,3})([^\n]*)\n(.*?)(\n\1)\s*$'

   

def

add_lang

(

match

)

:

        indent

,

info

,

body

,

closing

=

match.

groups

(

)

       

if

not

info.

strip

(

)

:

            lang

=

detect_language

(

body

)

           

return

f

"{indent}```{lang}\n{body}{closing}\n"

       

return

match.

group

(

0

)

    content

=

re

.

sub

(

fence_pattern

,

add_lang

,

content

)

   

Clean up extra blank lines (only content outside code blocks)

    content

=

re

.

sub

(

r

'\n{3,}'

,

'\n\n'

,

content

)

   

return

content.

rstrip

(

)

'\n'

if

name

==

"main"

:

   

try

:

       

Read the JSON data passed by Claude

        input_data

=

json.

load

(

sys

.

stdin

)

        file_path

=

input_data.

get

(

'tool_input'

,

{

}

)

.

get

(

'file_path'

,

''

)

       

Only process .md/.mdx files

       

if

not

file_path.

endswith

(

(

'.md'

,

'.mdx'

)

)

:

           

sys

.

exit

(

0

)

       

Read and format the file

       

if

os

.

path

.

exists

(

file_path

)

:

           

with

open

(

file_path

,

'r'

,

encoding

=

'utf-8'

)

as

f:

                content

=

f.

read

(

)

            formatted_content

=

format_markdown

(

content

)

           

Write only when the content changes

           

if

formatted_content

!=

content:

               

with

open

(

file_path

,

'w'

,

encoding

=

'utf-8'

)

as

f:

                    f.

write

(

formatted_content

)

               

print

(

f

"Formatted Markdown file: {file_path}"

)

   

except

Exception

as

e:

       

print

(

f

"Formatting failed: {e}"

,

file

=

sys

.

stderr

)

       

sys

.

exit

(

1

)

Step 3: Grant Execute Permission to the Script

chmod +x .claude/hooks/markdown_formatter.py

Example 3: Send a Desktop Notification When Claude Waits for Input

Function: Automatically pop up a desktop reminder when Claude needs user input (for Linux/macOS)

{

  "hooks": {

    "Notification": [

      {

        "matcher": "", // 匹配所有通知事件

        "hooks": [

          {

            "type": "command",

            "command": "notify-send 'Claude Code 提示' '请你输入指令或确认权限'"

          }

        ]

      }

    ]

  }

}

Example 4: Forbid Modifying Sensitive Files

Function: Prevent Claude from editing .env、package-lock.json and other sensitive files

{

  "hooks": {

    "PreToolUse": [

      {

        "matcher": "Edit|Write",

        "hooks": [

          {

            "type": "command",

            "command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', 'package-lock.json', '.git/']) else 0)\""

          }

        ]

      }

    ]

  }

}

Note: When the script returns a status code 2 , Claude Code will intercept this tool call, thereby preventing the file modification.


Claude Code Hooks Reference Manual

Configuration file paths

Configuration Levels File path Scope
User level ~/.claude/settings.json All projects
Project-level .claude/settings.json Current projects
Local Project Level (Not Committed) .claude/settings.local.json Current project, not under version control
Managed Policy Level Path specified by the administrator Unified enterprise/team management

Core Configuration Structure

Hooks are organized byevent + matcher, and support command(execute shell commands) and prompt(invoke LLM for decision-making) as two types.

{

  "hooks": {

    "【钩子事件名】": [

      {

        "matcher": "【工具匹配规则】", // 部分事件可省略

        "hooks": [

          {

            "type": "command/prompt",

            "command": "【Shell 命令】", // type=command 时必填

            "prompt": "【LLM 提示词】",  // type=prompt 时必填

            "timeout": 30 // 可选,超时时间(秒)

          }

        ]

      }

    ]

  }

}

Matcher Rules (Only for Tool-Type Events)

Matching Rules Example Description
Exact match Write Match only Write Tool
Multiple-tool matching Edit | Write Matches Edit or Write Tool
Prefix matching Notebook.* Match all tools that start with Notebook the given prefix
Full match * / Empty string Match all tools

Special Configuration Tips

Scenario Configuration method Example
Reference Scripts Within the Project Use Environment Variables $CLAUDE_PROJECT_DIR "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
Plugin Hooks Configuration Inside Plugins hooks/hooks.json, use ${CLAUDE_PLUGIN_ROOT} Reference Plugin Files "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh"
Component-Level Hooks (Skill/Agent) Defined in the component frontmatter, scoped only to the component lifecycle See belowExtended ConfigurationTables

Extended Configuration (Skill/Agent/Slash Commands)

Extended configuration allows embedding Hooks configuration directly in the definitions of Skills, Agents, or custom slash commands. These Hooks take effect only when the corresponding component is activated and running, and are automatically cleaned up after the component finishes, without affecting the global session.

Supported Hook Events

Only supports PreToolUse、PostToolUse、Stop three types of events, consistent with global Hooks functionality, but scoped only to the lifecycle of the current Skill/slash command.

Specific Configuration Options

Complete configuration example

---

# Skill/Slash command basic information

name: secure-operations

description: 执行Shell命令前先做安全校验的工具

# Hooks Configuration Section

hooks:

  PreToolUse:

    # Matcher: Only intercept Bash tool calls

    - matcher: "Bash"

      hooks:

        - type: "command"

          # Security validation script to execute

          command: "./scripts/security-check.sh"

          # Execute only once per session

          once: true

          # Timeout time (seconds), to prevent script freezing

          timeout: 15

---

Hooks Configuration in Agents

Supported Hook Events

Also only supports PreToolUse、PostToolUse、Stop three types of events, scoped only to the task execution period of the subagent.

Specific Configuration Options

No additional specific configuration options; does not support once: true(Hooks trigger every time the Agent executes a task).

Complete configuration example

---

# Agent's basic information

name: code-reviewer

description: 自动审查代码修改并运行代码检查的子代理

# Hooks Configuration Section

hooks:

  PostToolUse:

    # Matcher: Intercept Edit or Write tools

    - matcher: "Edit|Write"

      hooks:

        - type: "command"

          # Code checking script, execute lint validation

          command: "./scripts/run-linter.sh"

          # Timeout (seconds)

          timeout: 30

---

Notes:

  1. Matcher rules for component-internal Hooks are exactly the same as global Hooks: they support exact matching (e.g. "Write"), multiple-tool matching (e.g. "Edit|Write"), wildcard matching ("*"), and are case-sensitive;
  2. Component-internal Hooks and global Hooks run in parallel: if both global and component-internal Hooks are configured for the same event, both types run together when triggered without conflict;
  3. Configuration format requirement: component-internal Hooks must be written in the frontmatter (--- delimited region), follow YAML syntax, and incorrect indentation will invalidate the configuration;
  4. Script path recommendation: prefer relative paths (e.g. ./scripts/xxx.sh), or use the $CLAUDE_PROJECT_DIR environment variable to specify an absolute path, ensuring components can find the script from any directory.

Hook Events - Tool-Type Events (Support Matchers)

Event Name Trigger Timing Common Matchers Core Role
PreToolUse Tool callBefore Bash/Edit/Write/Read Intercept tool execution, modify input parameters, automatically approve/deny permissions
PermissionRequest When a permission request dialog pops up Same as PreToolUse Automatically handle permission requests without manual user confirmation
PostToolUse Tool callAfter success Same as PreToolUse Perform post-actions (such as code formatting, logging)
Notification When Claude sends a notification permission_prompt/idle_prompt/auth_success Customize notification methods (such as desktop pop-ups, email reminders)
PreCompact Before context compaction is executed manual(manual trigger) /auto(automatic trigger) Customize compaction rules, back up important context

Hook Events - Session/Task-Type Events (No Matchers)

Event Name Trigger Timing Core Role
UserPromptSubmit After the user submits a prompt, before Claude processes it Validate the legitimacy of the prompt, supplement context information
Stop When the main Agent finishes responding (not triggered by user interruption) Intelligently determine whether to continue executing the task
SubagentStop When a sub-Agent task completes Evaluate the sub-task result and decide whether to terminate
SessionStart When starting/resuming a session Initialize the environment, load project configuration, set persistent environment variables
SessionEnd When a session ends Clean up temporary files, record session logs, save working state

Comparison of hook types

Claude Code supports two hook types to meet different scenario needs.

Feature command Type (command hook) prompt Type (prompt hook)
Execution method Run Shell commands/scripts Call an LLM (default Haiku model) to make intelligent decisions
Decision logic Based on code logicDeterministic judgment Based on contextFlexible semantic judgment
Configuration difficulty Requires writing scripts; high barrier to entry Only requires writing a prompt; simple and easy to get started
Response speed Fast (local execution) Slower (requires an API call)
Applicable scenarios Code formatting, logging, permission blocking, and other fixed rules Task-completion evaluation, complex intent judgment, and other flexible scenarios
Core configuration command + timeout prompt + timeout(can reference $ARGUMENTS placeholders)

Input and Output -- Hook Input (JSON passed via stdin)

All hooks receive common fields; some events include specific fields.

Field type Common fields Description
Basic information session_id Unique session identifier
transcript_path Conversation history file path
cwd Current working directory when the hook executes
permission_mode Current permission mode (default/plan/acceptEdits, etc.)
hook_event_name Name of the currently triggered hook event

Examples of event-specific fields

Event Name Specific fields Example
PreToolUse tool_name/tool_input {"tool_name":"Write","tool_input":{"file_path":"/test.txt"}}
UserPromptSubmit prompt {"prompt":"帮我写一个排序函数"}
SessionEnd reason {"reason":"clear/logout/other"}

Hook output (two methods)

Method 1: exit code (simple scenarios)

Convey execution status through the exit code,stdout/stderr for feedback purposes.

Exit code Meaning Behavior description
0 Execution successful stdout Can return JSON for advanced control; some events (such as UserPromptSubmit) will add stdout to the context
2 Block operation Use only stderr Fed back to Claude as an error message,prevent the current event from continuing
Other non-zero values Non-blocking error stderr Only shown in verbose mode (ctrl+o), does not affect event execution

Behavior of exit code 2 in each event

Event Name Triggered behavior
PreToolUse Block tool calls and show Claude stderr
UserPromptSubmit Block prompt processing and erase user input
Stop Prevent Claude from stopping, force it to continue working
PostToolUse/Notification Only display stderr, does not affect already-completed operations

Method 2: JSON output (advanced scenarios)

When the exit code is 0 , you can use stdout to return JSON for fine-grained control; the core fields are as follows:

Common JSON fields Purpose
continue: true/false Whether to allow the event to continue (false takes precedence over other rules)
stopReason continue=false , the reason shown to the user
systemMessage Warning message shown to the user

Examples of event-specific JSON fields

Event Name Specific fields Example
PreToolUse permissionDecision(allow/deny/ask) {"hookSpecificOutput":{"permissionDecision":"allow","updatedInput":{"file_path":"/new.txt"}}}
UserPromptSubmit decision: block/undefined {"decision":"block","reason":"提示包含敏感信息"}
PostToolUse additionalContext {"hookSpecificOutput":{"additionalContext":"文件已格式化完成"}}

Hooks configuration for MCP tools

MCP tools can integrate seamlessly with Hooks, matched through specific naming rules.

MCP tool naming rules

mcp__<服务器名>__<工具名>

Example:mcp__github__search_repositories、mcp__filesystem__read_file

Matching examples

{

  "hooks": {

    "PreToolUse": [

      {

        "matcher": "mcp__memory__.*", // 匹配 memory 服务器的所有工具

        "hooks": [{"type": "command", "command": "echo '内存操作日志' >> log.txt"}]

      },

      {

        "matcher": "mcp__.*__write.*", // 匹配所有服务器的写操作工具

        "hooks": [{"type": "command", "command": "./validate-write.py"}]

      }

    ]

  }

}


Security and debugging

Security best practices

Security essentials Specific actions
Input validation Strictly validate tool_input file paths and command arguments in ... to prevent path traversal (such as ../)
variable reference using ... in Shell commands "$VAR" instead of $VAR, to avoid argument injection
Least privilege Grant hook scripts only necessary permissions; avoid using sudo and other high-risk commands
Sensitive file exclusion Block operations on .env、.gitand secret/key files
Command review Before registering a hook, manually execute the command to verify the logic and confirm no malicious behavior

Debugging tips

Problem Type Troubleshooting steps
Hook not taking effect 1. Run /hooks command to check whether the configuration is registered
2. Verify that the JSON syntax is correct
3. Check that the matcher rules match the tool name (case-sensitive)
Command execution failed 1. Manually run the hook command to confirm it executes properly
2. Check whether the script has executable permission (chmod +x script.sh)
3. Invoke the script using an absolute path to avoid environment variable issues
View detailed logs Add the ... parameter when starting Claude Code --debug parameter to view the entire hook execution process

Reference: for the complete functional description of hooks, see the official hooks reference documentation。