hippo: This post is part of the Claude Code Official Docs Breakdown series. Hooks are the feature I use the most—and the one where I’ve hit the most pitfalls—because they give you deterministic control over Claude Code.


1. What Are Hooks?

Hooks are Claude Code’s event-driven guardrails. Think of them as the AI counterpart to Git Hooks: whenever Claude Code invokes a tool, receives a user prompt, or finishes a turn, it automatically triggers a shell command, HTTP request, or LLM prompt you configure.

The fundamental difference between Hooks and Skills is determinism:

  • Skills are probabilistic—Claude decides whether to apply them, and it can forget.
  • Hooks are deterministic—whenever the event fires and the matcher matches, the hook runs 100% of the time and cannot be bypassed.

Hooks span the entire Claude Code lifecycle:

  • Pre-tool interception and approval: Block destructive commands or auto-approve trusted permissions.
  • Post-tool verification and auditing: Run tests, capture screenshots for visual checks, or log tool executions.
  • Session lifecycle callbacks: Inject context on startup, send notifications when a task finishes, or persist state before context compaction.

2. Official Docs Deep Dive

2.1 Configuration Locations and Structure

Hooks are defined in JSON settings files using three nested layers: select an event -> filter with a matcher -> define one or more handlers.

Where you place the configuration determines its scope:

Location Scope Shareable
~/.claude/settings.json All your projects No (local machine only)
.claude/settings.json Single project Yes (committable to Git)
.claude/settings.local.json Single project No (gitignored)
Managed policy settings Organization-wide Yes (admin-controlled)
Plugin hooks/hooks.json While the plugin is enabled Yes (bundled with the plugin)
Skill or agent frontmatter While the component is active Yes (defined in the component file)

A complete settings.json hooks configuration example:

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
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-dangerous.sh",
"timeout": 30
}
]
}
],
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/notify.sh"
}
]
}
]
}
}

Configuration Fields:

Common fields (supported by all hook types):

Field Type Required Description
type string Yes Handler type: command, http, prompt, or agent
if string No Permission-rule syntax filter, e.g. "Bash(git *)" matches only git commands. Valid on tool events only
matcher string No Regular expression controlling when the hook triggers. "*" or empty matches everything
timeout number No Timeout in seconds. Defaults: 600 for command, 30 for prompt, 60 for agent
statusMessage string No Custom spinner message displayed while the hook runs
once boolean No When true, runs at most once per session (Skills only)

Command-hook-specific fields:

Field Type Required Description
command string Yes Shell command to execute
async boolean No When true, runs in the background without blocking
shell string No Shell to use: "bash" (default) or "powershell"

Matcher rules: matcher is a regular expression string. "Bash" matches the Bash tool, "Edit|Write" matches either Edit or Write, "mcp__.*" matches all MCP tools, and "*" or an empty string matches everything.

What matcher matches against depends on the event type:

Event Type Matcher Target
PreToolUse / PostToolUse / PostToolUseFailure Tool name (e.g., Bash, Edit, mcp__memory__create_entities)
PermissionRequest / PermissionDenied Tool name
SubagentStart / SubagentStop Agent type name (e.g., Explore or a custom agent name)
Notification Notification type (e.g., permission_prompt, idle_prompt)
PreCompact / PostCompact Trigger source (manual or auto)
SessionStart Startup reason (startup, resume, clear, compact)
SessionEnd Exit reason (clear, resume, logout, etc.)
ConfigChange Configuration source (user_settings, project_settings, etc.)
FileChanged Filename (e.g., .envrc)
StopFailure Error type
Stop / UserPromptSubmit / TaskCreated / TaskCompleted / TeammateIdle / WorktreeCreate / WorktreeRemove No matcher support

Reference project scripts with the $CLAUDE_PROJECT_DIR environment variable so paths remain valid regardless of working directory changes.

2.2 Complete Hook Event Reference

Claude Code supports 26 Hook events spanning the full lifecycle from session startup to shutdown:

Event Trigger Matcher Target Can Block Typical Use Case
SessionStart Session starts or resumes startup/resume/clear/compact No Inject context, export env vars
InstructionsLoaded CLAUDE.md or rule files load session_start/nested_traversal, etc. No Audit logging, compliance tracking
UserPromptSubmit Before user prompt is processed No matcher Yes Inject context, filter sensitive input
PreToolUse Before a tool executes Tool name Yes Block dangerous commands, auto-approve
PermissionRequest When a permission prompt appears Tool name Yes Auto-allow or auto-deny permissions
PermissionDenied When auto mode denies a tool Tool name No (can retry) Retry a denied tool call
PostToolUse After a tool succeeds Tool name No (can send feedback) Run tests, log actions
PostToolUseFailure After a tool fails Tool name No (can send feedback) Error alerts, corrective feedback
Notification When user attention is needed permission_prompt/idle_prompt, etc. No Send desktop or Feishu notifications
SubagentStart When a subagent starts Agent type name No Inject context into a subagent
SubagentStop When a subagent finishes Agent type name Yes Verify subagent task completion
TaskCreated When TaskCreate creates a task No matcher Yes Enforce task naming conventions
TaskCompleted When a task is marked completed No matcher Yes Require passing tests before closing
Stop When the main agent finishes a turn No matcher Yes Completion alerts, quality checks
StopFailure Turn ends due to an API error Error type No (output ignored) Log failures, trigger alerts
TeammateIdle An agent-team teammate is about to go idle No matcher Yes Enforce quality gates
ConfigChange A configuration file changes user_settings/project_settings, etc. Yes Audit configuration changes
CwdChanged Working directory changes No matcher No Auto-load direnv environment
FileChanged A watched file changes on disk Filename (e.g., .envrc) No Hot-reload environment variables
WorktreeCreate When creating a worktree No matcher Yes (returns path) Custom VCS working copy setup
WorktreeRemove When removing a worktree No matcher No Clean up VCS state
PreCompact Before context compaction manual/auto No Snapshot critical context
PostCompact After context compaction manual/auto No Log compaction summary
Elicitation When an MCP server requests user input MCP server name Yes Programmatically answer MCP forms
ElicitationResult After user answers an MCP elicitation MCP server name Yes Modify or block the response
SessionEnd When the session ends clear/resume/logout, etc. No Cleanup, save session metrics

Events that do not support matchers (such as Stop and SessionEnd) fire on every occurrence. If you attach a matcher to them, it is silently ignored.

2.3 Hook Input: Reading JSON from stdin

Every command hook receives a JSON payload on stdin. Your script reads stdin and extracts the fields it needs, typically with jq.

Common input fields:

Field Description
session_id Current session identifier
transcript_path Path to the conversation transcript JSON
cwd Current working directory
permission_mode Active permission mode: default, plan, acceptEdits, auto, dontAsk, or bypassPermissions
hook_event_name Name of the triggered event
agent_id Unique subagent ID (present only when triggered inside a subagent)
agent_type Agent name, such as "Explore" or a custom agent name

Individual events include additional fields. Here is a PreToolUse example:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
# .claude/hooks/block-rm.sh
# Read JSON from stdin and extract the command to execute
COMMAND=$(jq -r '.tool_input.command')

if echo "$COMMAND" | grep -q 'rm -rf'; then
# Output written to stderr is fed back to Claude as an error message
echo "Blocked: rm -rf commands are not allowed" >&2
exit 2 # Exit code 2 = block
fi

exit 0 # Exit code 0 = allow

This script runs before every Bash tool invocation. Its stdin JSON looks like this:

1
2
3
4
5
6
7
8
9
10
{
"session_id": "abc123",
"transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
"cwd": "/home/user/my-project",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "rm -rf /tmp/build"
}
}

PostToolUse adds tool_response (the tool’s result), while Stop adds stop_hook_active (an infinite-loop guard flag) and last_assistant_message (Claude’s final reply text).

2.4 Two Output Modes: Exit Codes vs. JSON

Your hook’s output mechanism determines how finely you can control Claude Code’s behavior.

Simple mode: Exit codes

Exit Code Meaning Effect
0 Success Execution proceeds. If stdout contains JSON, it is parsed
2 Block stderr is fed back to Claude. Exact blocking behavior varies by event
Other Non-blocking error stderr is shown in verbose mode; execution continues

Exit code 2 behaves differently across events—make sure you know which events actually block:

Hook Event Can Block? Effect of Exit Code 2
PreToolUse Yes Blocks the tool call
PermissionRequest Yes Denies the permission request
UserPromptSubmit Yes Blocks the prompt and removes it from context
Stop Yes Prevents Claude from stopping; forces it to keep working
SubagentStop Yes Prevents the subagent from stopping
TeammateIdle Yes Prevents the teammate from going idle; keeps it working
TaskCreated Yes Rolls back task creation
TaskCompleted Yes Prevents the task from being marked completed
ConfigChange Yes Blocks the configuration change (except policy_settings)
Elicitation Yes Rejects the MCP elicitation
ElicitationResult Yes Blocks the response (action becomes decline)
WorktreeCreate Yes Any non-zero exit fails worktree creation
PostToolUse No Shows stderr to Claude
PostToolUseFailure No Shows stderr to Claude
PermissionDenied No Exit code and stderr ignored (return JSON retry: true to retry)
Notification No Shows stderr to the user only
SubagentStart No Shows stderr to the user only
SessionStart No Shows stderr to the user only
SessionEnd No Shows stderr to the user only
CwdChanged / FileChanged No Shows stderr to the user only
PreCompact / PostCompact No Shows stderr to the user only
StopFailure No Output and exit code ignored
WorktreeRemove No Failures logged in debug mode only
InstructionsLoaded No Exit code ignored

Advanced mode: JSON output

Exit with 0 and print JSON to stdout for granular control:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
# Fine-grained PreToolUse control using JSON output
COMMAND=$(jq -r '.tool_input.command')

if echo "$COMMAND" | grep -q 'rm -rf'; then
# Output JSON with hookSpecificOutput to control PreToolUse behavior
jq -n '{
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "Destructive command blocked by hook"
}
}'
else
exit 0 # No output = allow
fi

Common JSON output fields:

Field Default Description
continue true When false, Claude stops processing entirely after the hook
stopReason None Message shown to the user when continue is false
suppressOutput false When true, hides stdout from verbose-mode output
systemMessage None Warning message displayed to the user

Decision fields vary by event: PreToolUse uses hookSpecificOutput.permissionDecision (allow/deny/ask/defer), Stop uses top-level decision: "block", and PostToolUse uses top-level decision: "block" together with reason.

Output character limit: Hook output injected into context (additionalContext, systemMessage, or plain stdout) is capped at 10,000 characters. Anything longer is saved to a file and replaced with a preview and the file path.

2.5 The if Field: Permission-Rule Filtering

Beyond filtering by tool name with matcher, you can add a secondary filter with if using permission rule syntax to match both tool names and arguments:

  • "Bash(git *)" matches only git commands
  • "Edit(*.ts)" matches only TypeScript file edits
  • "Bash(rm *)" matches only commands starting with rm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(rm *)",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-rm.sh"
}
]
}
]
}
}

if is valid only on tool events (PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, PermissionDenied). A hook with if attached to any other event will never run.

2.6 Hooks for MCP Tools

Tools exposed by MCP (Model Context Protocol) servers are treated just like built-in tools in Hooks, using the naming format mcp__<server>__<tool>.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__memory__.*",
"hooks": [
{
"type": "command",
"command": "echo 'Memory operation: '$(jq -r '.tool_name') >> ~/mcp-operations.log"
}
]
},
{
"matcher": "mcp__.*__write.*",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-mcp-write.sh"
}
]
}
]
}
}
  • mcp__memory__.* matches every tool on the memory server.
  • mcp__.*__write.* matches any tool containing write on any MCP server.
  • Configuration is identical to built-in tools, and matcher remains a regular expression.

2.7 Elicitation: Handling MCP Server User Prompts

When an MCP server needs user input mid-tool-call (such as filling out a form or completing authentication), Claude Code opens an interactive dialog by default. With Elicitation and ElicitationResult, your hook can respond programmatically and bypass the dialog entirely.

  • Elicitation: Fires when an MCP server requests input; the hook can return accept, decline, or cancel.
  • ElicitationResult: Fires after the user responds and before the result returns to the MCP server; the hook can modify or block the response.

Here, matcher matches the MCP server name. In form mode, requested_schema provides the form schema; in URL mode, url provides the browser authentication link.

2.8 Hooks Inside Skills and Subagents

Beyond settings.json, you can define hooks directly in the frontmatter of Skills and subagents. These hooks are scoped strictly to the component’s lifecycle—they run while the component is active and clean up automatically when it finishes.

For subagents, Stop hooks are automatically converted to SubagentStop, since that is the event triggered when a subagent completes.

1
2
3
4
5
6
7
8
9
10
---
name: secure-operations
description: Perform operations with security checks
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/security-check.sh"
---

3. hippo’s Field Notes

hippo: Here are the Hook configurations I actually run in production, along with lessons learned the hard way.

3.1 Why I Rely on Hooks

Put a safety rule in CLAUDE.md and Claude may forget it; enforce it with a Hook and it runs 100% of the time.

Take blocking rm -rf as an example:

  • Written in CLAUDE.md: ~70% compliance (Claude can still “forget”).
  • Enforced with a Hook: 100% (a hard runtime barrier).

For safety rules, determinism beats probability every time.

3.2 My Production Hook Setup

Here is a simplified version of the .claude/settings.json I use in this blog repository:

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
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-dangerous.sh"
}
]
},
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(git commit *)",
"command": "cd $CLAUDE_PROJECT_DIR && hexo clean && hexo generate 2>&1 | tail -5 || { echo 'Hexo build failed; commit blocked' >&2; exit 2; }"
}
]
}
],
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/notify.sh"
},
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/feishu-notify.sh"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/screenshot-hook.sh"
}
]
}
]
}
}

What each hook does:

  • PreToolUse (Bash): Blocks destructive commands such as rm -rf and git push --force.
  • PreToolUse (git commit): Runs hexo generate before committing and blocks the commit if the build fails.
  • Stop: Fires both a desktop notification and a Feishu notification when a turn finishes (both hooks run in parallel).
  • PostToolUse (Write|Edit): Captures a screenshot after file edits to verify how the blog renders.

When to Use a Hook vs. a Skill:

Scenario Use Hook Use Skill
Safety rules (cannot be bypassed) Yes No
Mandatory pre-commit test/build gates Yes No
Writing-style guidelines No Yes
Publishing workflow definitions No Yes (can pair with a Hook trigger)

3.3 Core Principle: Block-at-Submit, Not Block-at-Write

Let Claude finish its full plan and run unified verification at the final git commit gate, instead of interrupting it on every file edit.

The reasoning is simple: a single task often touches 5–10 files. Running a full build after every Write or Edit is slow and breaks Claude’s momentum. Letting Claude complete all edits and validating once at git commit is far faster and cleaner.


4. FAQ

Q: Where should Hook scripts live?
A: Put them in .claude/hooks/ and invoke them via "$CLAUDE_PROJECT_DIR"/.claude/hooks/xxx.sh. Always quote the path in case it contains spaces.

Q: In what order do multiple matching Hooks execute?
A: All matching hooks run in parallel, and identical commands are automatically deduplicated by command string.

Q: What happens when a Hook times out?
A: Command hooks default to a 600-second timeout. You can specify a shorter timeout in your configuration:

1
2
3
4
5
{
"type": "command",
"command": "long-running-script.sh",
"timeout": 120
}

When a hook times out, it is canceled and treated as a non-blocking error, so Claude continues execution.

Q: How do I debug Hooks?
A: Launch with claude --debug to inspect hook execution logs (matched hooks, exit codes, and outputs). You can also press Ctrl+O to toggle verbose mode and watch live progress.

Q: Why aren’t my config changes taking effect?
A: Claude Code snapshots its configuration on startup. Direct edits to settings.json are usually picked up automatically by the file watcher; if not, run /hooks inside Claude Code to open the hook inspector and verify the active configuration.


5. Security Considerations

Hooks execute arbitrary shell commands, so use them with care. The official docs highlight five security best practices:

  1. Validate and sanitize inputs: Never blindly trust JSON coming from stdin.
  2. Always quote shell variables: Use "$VAR" instead of $VAR.
  3. Prevent path traversal: Reject file paths containing ...
  4. Use absolute paths: Reference project scripts through "$CLAUDE_PROJECT_DIR".
  5. Skip sensitive files: Avoid reading or processing .env, .git/, or credential files inside hooks.

To temporarily disable all hooks, set "disableAllHooks": true in your settings file. Enterprise administrators can set allowManagedHooksOnly to block user-level and project-level hooks.


6. Summary

Hooks are Claude Code’s deterministic guardrails—rules in CLAUDE.md can be forgotten, whereas Hooks execute 100% of the time. Once you know the 26 event types, 4 handler types (command/http/prompt/agent), 2 output modes (exit codes and JSON), if permission-rule filtering, and configuration scopes, you can make Claude Code both capable and safe.

Next: Creating Custom Subagents — How to create isolated subagents with dedicated context.


Hands-On Case Study

Claude Code Hooks in Practice: Automated Task-Completion Notifications — Building desktop and Feishu notifications with a Stop hook, complete with real-world pitfalls.


Series Navigation


Based on the official Hooks Reference - Claude Code Docs documentation.

Last updated: 2026-04-08