Claude Code Hooks

Explaining Claude Code Hooks and Subagent Hooks

As of Claude Code v2.1.92 | April 4, 2026

What You'll Learn

Why Hooks Matter

Hooks are one of the most powerful features introduced in Claude Code โ€” they let you run custom code at specific moments in Claude's workflow.

In This Video

๐Ÿ”ข
27 Hooks Explained Claude Code currently supports 27 hooks (as of v2.1.92)
๐ŸŽฏ
When Each Hook Triggers Learn the exact moment each hook fires in Claude's workflow
๐Ÿ’ก
Practical Use Cases Real-world examples of what you can build with each hook
๐Ÿ”Š
Voice Notifications Demo This repo integrates all 27 hooks with audio feedback

What Hooks Enable

The 27 Hooks

Claude Code v2.1.92 | April 4, 2026 โ€” More hooks may be added in future versions.

1 SessionStart
2 UserPromptSubmit
3 PreToolUse
4 PostToolUse
5 PostToolUseFailure
6 PermissionRequest
7 Notification
8 SubagentStart
9 SubagentStop
10 Stop
11 PreCompact
12 PostCompact
13 SessionEnd
14 Setup
15 TeammateIdle
16 TaskCompleted
17 TaskCreated
18 ConfigChange
19 WorktreeCreate
20 WorktreeRemove
21 InstructionsLoaded
22 Elicitation
23 ElicitationResult
24 StopFailure
25 CwdChanged
26 FileChanged
27 PermissionDenied

Hook Execution Flow

Hooks fire at specific points in Claude's workflow. Here's the execution order:

Separate trigger โ€” claude --init / --maintenance
Setup
โ†’ SessionStart Session begins or resumes
โ†“ UserPromptSubmit User sends a message
โ†“ PreToolUse Before each tool runs
โ†“ PermissionRequest If permission needed
โ†“ PostToolUse / PostToolUseFailure After tool completes
โ†“ SubagentStart โ†’ SubagentStop If subagent spawned
โ†“ Stop Claude finishes responding
โ†“ PreCompact If context needs compaction
โ†“ PostCompact After compaction completes
โ†’ SessionEnd Session terminates
Async โ€” Fire at any time during session
Notification TeammateIdle TaskCompleted TaskCreated ConfigChange WorktreeCreate WorktreeRemove InstructionsLoaded Elicitation ElicitationResult StopFailure PermissionDenied

Note: Setup fires separately via --init/--maintenance CLI flags. Notification, TeammateIdle, TaskCompleted, TaskCreated, ConfigChange, WorktreeCreate, WorktreeRemove, InstructionsLoaded, Elicitation, ElicitationResult, StopFailure, CwdChanged, FileChanged, and PermissionDenied hooks fire asynchronously at any point during the session โ€” they are not part of the sequential flow above.

1 SessionStart Cannot Block

When It Triggers

When you start Claude Code or resume an existing session. This is the first hook to fire.

How to Trigger

Run Claude Code from your terminal to start a new session:

$ claude

Or resume an existing session:

$ claude --resume
Trigger Sources: startup resume clear compact

Input Fields

model โ€” Model identifier (e.g., claude-sonnet-4-6)

agent_type โ€” Agent name if started with --agent flag (since v2.1.43)

Use Cases

๐Ÿ”Š
Voice: "Claude session started" Audio notification when Claude Code is ready
๐Ÿ“Š
Load Git Status Inject current branch, uncommitted changes into Claude's context
๐Ÿ”ง
Set Environment Variables Configure API keys, paths, or project-specific settings
๐Ÿ“
Load Project Memory Restore previous context or project-specific instructions
๐Ÿ”Š Sound: sessionstart.wav โ€” "Claude session started"
2 UserPromptSubmit Can Block

When It Triggers

When you submit a prompt, before Claude processes it. Fires once per user message.

How to Trigger

Type any prompt and press Enter:

> What is the weather in Karachi?

Or any other message to Claude:

> Help me fix the bug in my code

Use Cases

๐Ÿ”Š
Voice: "Processing your request" Audio confirmation that your prompt was received
โœ…
Validate Prompt Content Block harmful, spam, or unauthorized requests
๐Ÿ“Ž
Inject Dynamic Context Add relevant docs, git history, or environment info based on keywords
๐Ÿ“ˆ
Usage Tracking Log prompts for analytics or rate limiting
๐Ÿ”Š Sound: userpromptsubmit.wav โ€” "Processing your request"
3 PreToolUse Can Block

When It Triggers

After Claude creates tool parameters but before the tool executes. Fires for every tool call (Bash, Edit, Write, Read, etc.).

How to Trigger

Ask Claude to do anything that requires a tool:

> Read the README.md file
> Run npm test
> Create a commit with message "fix bug"

Use Cases

๐Ÿ”Š
Voice: "Ding" (tool starting) Short audio cue when Claude is about to use a tool
๐Ÿ›ก๏ธ
Block Dangerous Commands Prevent rm -rf /, DROP TABLE, or other destructive operations
โœ๏ธ
Modify Tool Inputs Sanitize paths, normalize commands, add default flags
๐ŸŽต
Special Sound for Git Commits Play different sound when git commit is detected
๐Ÿ”Š Sound: pretooluse.wav โ€” "Ding" | pretooluse-git-committing.wav for commits
4 PostToolUse Cannot Block

When It Triggers

Immediately after a tool completes successfully. Does NOT fire if the tool fails.

How to Trigger

Ask Claude to perform any successful tool operation:

> Read the package.json file
> List all files in the .claude project folder

Fires after the tool completes without errors.

Use Cases

๐Ÿ”Š
Voice: "Dong" (tool completed) Short audio cue confirming tool execution succeeded
๐ŸŽจ
Auto-Format Code Run Prettier, Black, or gofmt after file edits
๐Ÿงช
Run Tests Automatically Execute test suite after code changes
๐Ÿ“Š
Log Successful Operations Track what tools were used and their results
๐Ÿ”Š Sound: posttooluse.wav โ€” "Dong"
5 PostToolUseFailure Cannot Block

When It Triggers

Immediately after a tool call fails (error or non-zero exit code). Does NOT fire if the tool succeeds.

How to Trigger

Ask Claude to run a Bash command that exits with non-zero status:

> Run the command: false
> Run the command: ls /nonexistent/path/xyz

Fires when Bash exits with non-zero code (e.g., exit code 1 or 2).

Use Cases

๐Ÿ”Š
Voice: "Tool failed" Audio alert when something goes wrong
๐Ÿšจ
Send Failure Alerts Notify via Slack, email, or desktop notification on errors
๐Ÿ”
Analyze Error Patterns Log failures for debugging and monitoring
๐Ÿ’ก
Provide Recovery Context Inject helpful information to help Claude recover
๐Ÿ”Š Sound: posttoolusefailure.wav โ€” "Tool failed"
6 PermissionRequest Can Block

When It Triggers

When a permission dialog is about to be shown. Fires once per permission prompt, allowing you to auto-approve or auto-deny.

How to Trigger

Ask Claude to run a command that requires permission approval:

> Create a directory ABC on project root
> Run the build script

Claude will show a permission dialog before running the command.

Use Cases

๐Ÿ”Š
Voice: "Permission required" Alert when Claude needs your approval for an action
โœ…
Auto-Approve Safe Commands Skip permission dialog for trusted operations like npm test
๐Ÿšซ
Auto-Deny Dangerous Operations Block sensitive actions without showing dialog
๐Ÿ“‹
Audit Permission Requests Log all permission requests for compliance
๐Ÿ”Š Sound: permissionrequest.wav โ€” "Permission required"
7 Notification Cannot Block

When It Triggers

When Claude Code sends system notifications (permission prompts, idle alerts, auth success). Fires asynchronously, outside the main agentic loop.

How to Trigger

Triggered automatically by system events:

โ€ข Leave Claude idle for a while โ†’ idle_prompt
โ€ข Claude asks for permission โ†’ permission_prompt
โ€ข Successfully authenticate โ†’ auth_success
Notification Types: permission_prompt idle_prompt auth_success elicitation_dialog

Use Cases

๐Ÿ”Š
Voice: "Notification" Audio cue for system notifications
๐Ÿ–ฅ๏ธ
Desktop Notifications Route notifications to macOS/Windows notification center
๐Ÿ’ฌ
External Integrations Send to Slack, Discord, or webhook endpoints
๐Ÿ”Š Sound: notification.wav โ€” System notification sound
8 SubagentStart Cannot Block

When It Triggers

When a subagent is spawned via the Task tool. Can happen multiple times per session (subagents can spawn subagents). Includes agent_id (unique identifier) and agent_type (agent name).

How to Trigger

Ask Claude to perform a task that spawns a subagent:

> Use Explore agent to read the README.md file
> Search for all API endpoints in this project

Claude will spawn an Explore, Plan, or Bash agent to help.

Input Fields: agent_id agent_type
Agent Types: Bash Explore Plan CustomAgentName

Use Cases

๐Ÿ”Š
Voice: "Subagent started" Audio notification when a subagent begins work
๐Ÿ›ก๏ธ
Inject Security Guidelines Add security rules to subagent context
๐Ÿ“Š
Monitor Subagent Spawning Track which agents are created and when
๐Ÿ“
Add Project Context Inject project-specific instructions into subagents
๐Ÿ”Š Sound: subagentstart.wav โ€” "Subagent started"
9 SubagentStop Can Block

When It Triggers

When a subagent finishes responding. Can be blocked to force the subagent to continue working. Includes agent_id, agent_type, last_assistant_message (since v2.1.47), and agent_transcript_path.

How to Trigger

Fires automatically when a subagent completes its task:

> Explore the codebase and find where authentication is handled

After the Explore agent finishes searching, SubagentStop fires.

Input Fields: agent_id agent_type last_assistant_message agent_transcript_path
Agent Types: Bash Explore Plan CustomAgentName

Use Cases

๐Ÿ”Š
Voice: "Subagent completed" Audio notification when subagent finishes
โœ…
Verify Task Completion Check if subagent actually completed its assigned task
๐Ÿ”„
Force Continuation Block stopping if quality checks fail
๐Ÿ“ˆ
Log Completion Metrics Track subagent performance and duration
๐Ÿ”Š Sound: subagentstop.wav โ€” "Subagent completed"
10 Stop Can Block

When It Triggers

When Claude finishes responding and is ready to stop. Does NOT fire on user interrupts (Ctrl+C). Includes last_assistant_message field with Claude's final response text (since v2.1.47).

How to Trigger

Simply wait for Claude to finish responding to any prompt:

> Explain how this function works

When Claude completes its response and returns to the prompt, Stop fires.

Note: Does NOT fire if you press Ctrl+C to interrupt.

Use Cases

๐Ÿ”Š
Voice: "Task completed" Audio confirmation that Claude finished responding
๐Ÿงช
Verify Tests Pass Block stopping until all tests pass
๐Ÿ“‹
Check Task List Prevent stopping if there are unfinished tasks
๐Ÿ“
Analyze Last Response Use last_assistant_message to log or validate Claude's final output
๐Ÿ”Š Sound: stop.wav โ€” "Task completed"
11 PreCompact Cannot Block

When It Triggers

Before context compaction occurs โ€” either automatically when context window fills up, or when user runs /compact.

How to Trigger

Manually run the compact command:

> /compact

Or automatically when context window fills up after a long conversation.

Trigger Types: manual auto

Use Cases

๐Ÿ”Š
Voice: "Compacting context" Audio alert before context is compressed
๐Ÿ’พ
Preserve Critical Context Save important information before it's compacted
๐Ÿ“Š
Monitor Context Usage Track how often context fills up
๐Ÿ“
Re-Inject Guidelines Add project rules to be included after compaction
๐Ÿ”Š Sound: precompact.wav โ€” "Compacting context"
12 PostCompact Cannot Block

When It Triggers

After context compaction completes โ€” either automatically when context window fills up, or after user runs /compact. Use this to react to the new compacted state.

How to Trigger

Fires automatically after any compaction:

> /compact    โ† Triggers PreCompact then PostCompact

Or automatically after auto-compact when context window fills up.

Trigger Types: manual auto

Use Cases

๐Ÿ”Š
Voice: "Context compacted" Audio confirmation that compaction finished
๐Ÿ“‹
Log Compact Summary Save the generated conversation summary for audit
๐Ÿ”„
Update External State Sync external tools with the new compacted context
๐Ÿ“Š
Track Compaction Frequency Monitor how often context fills up and gets compressed
๐Ÿ”Š Sound: postcompact.wav โ€” "Context compacted"
13 SessionEnd Cannot Block

When It Triggers

When a session terminates. This is the last hook to fire โ€” cannot prevent session from ending.

How to Trigger

End the session in any of these ways:

> /clear    โ† Clears conversation and ends session
> exit      โ† Type exit at the prompt
Press Ctrl+D or Ctrl+C to exit
End Reasons: clear resume logout prompt_input_exit bypass_permissions_disabled other

Use Cases

๐Ÿ”Š
Voice: "Session ended" Audio farewell when closing Claude Code
๐Ÿงน
Cleanup Operations Delete temporary files, close connections
๐Ÿ“Š
Log Session Statistics Record session duration, tools used, etc.
๐Ÿ’พ
Save Session State Archive transcript or project state
๐Ÿ”Š Sound: sessionend.wav โ€” "Session ended"
14 Setup Cannot Block

When It Triggers

When Claude Code runs the /setup command for project initialization. Rarely used compared to other hooks.

How to Trigger

Run setup hooks without starting interactive mode:

$ claude --init-only

Note: claude --init does NOT trigger the Setup hook.

Use Cases

๐Ÿ”Š
Voice: "Setup initiated" Audio notification when project setup begins
๐Ÿ“ฆ
Install Dependencies Run npm install, pip install, etc.
โš™๏ธ
Configure Project Set up MCP servers, linters, formatters
โœ…
Validate Environment Check required tools and versions are installed
๐Ÿ”Š Sound: setup.wav โ€” "Setup initiated"
15 TeammateIdle Can Block

When It Triggers

When a teammate agent becomes idle in an experimental agent teams session. Requires the agent teams feature to be enabled. Includes teammate_name and team_name input fields (since v2.1.33).

How to Trigger

Enable agent teams and start a multi-agent session:

$ CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude

When a teammate agent finishes its current work and becomes idle, this hook fires.

Use Cases

๐Ÿ”Š
Voice: "Teammate idle" Audio notification when a teammate agent is waiting for work
๐Ÿ“‹
Auto-Assign Tasks Automatically queue the next task for the idle teammate
๐Ÿ“Š
Monitor Team Utilization Track idle time across agents for workload balancing
๐Ÿ””
Notify Orchestrator Alert the main agent that a teammate is available
๐Ÿ”Š Sound: teammateidle.wav โ€” "Teammate idle"
16 TaskCompleted Can Block

When It Triggers

When a background task completes in an experimental agent teams session. Requires the agent teams feature to be enabled. Includes task_id, task_subject, and task_description input fields (since v2.1.33).

How to Trigger

Enable agent teams and run background tasks:

$ CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude

When a background task finishes execution, this hook fires.

Use Cases

๐Ÿ”Š
Voice: "Task completed" Audio notification when a background task finishes
โœ…
Verify Task Results Run validation checks on the completed task output
๐Ÿ”„
Trigger Follow-Up Tasks Automatically start dependent tasks in a pipeline
๐Ÿ“ˆ
Log Completion Metrics Track task duration, success rate, and throughput
๐Ÿ”Š Sound: taskcompleted.wav โ€” "Task completed"
17 TaskCreated Can Block

When It Triggers

Runs when a task is being created via the TaskCreate tool. Fires in experimental agent teams sessions when a teammate creates a new task.

How to Trigger

Fires when a teammate creates a task via TaskCreate:

$ CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude

When a teammate uses the TaskCreate tool, this hook fires before the task is finalized.

Input Fields

task_id โ€” Unique identifier for the task

task_subject โ€” Subject line of the task

task_description โ€” Full description of the task

teammate_name โ€” Name of the teammate creating the task

team_name โ€” Name of the team

Use Cases

๐Ÿ“
Enforce Task Naming Conventions Validate that task subjects follow team naming standards
โœ…
Validate Task Descriptions Ensure task descriptions contain required fields or minimum detail
๐Ÿšซ
Prevent Unauthorized Task Creation Block task creation from unauthorized teammates or teams
๐Ÿ”Š Sound: taskcreated.wav โ€” "Task created"

Added in v2.1.84

18 ConfigChange Can Block

When It Triggers

When a configuration file changes during a session. Detects changes to user settings, project settings, local settings, policy settings, and skills. Includes optional file_path input field with the path to the modified config file (since v2.1.49).

How to Trigger

Modify any Claude Code configuration file while a session is active:

Edit .claude/settings.json while Claude is running
Change user settings via ~/.claude/settings.json

The hook fires when Claude detects the config file has been modified.

Config Sources: user_settings project_settings local_settings policy_settings skills

Use Cases

๐Ÿ”Š
Voice: "Config changed" Audio notification when configuration is modified
๐Ÿ›ก๏ธ
Audit Config Changes Log and validate configuration modifications for security
๐Ÿ”„
Auto-Reload Settings Trigger reloads or re-initialization when config changes
๐Ÿšซ
Block Unsafe Changes Prevent unauthorized config modifications (except policy_settings)
๐Ÿ”Š Sound: configchange.wav โ€” "Config changed"
19 WorktreeCreate Can Block

When It Triggers

When agent worktree isolation creates worktrees, enabling custom VCS setup. This hook fires during the worktree creation process for agents that use isolation: worktree in their definitions (since v2.1.50).

How to Trigger

Use an agent configured with worktree isolation:

claude --agent my-isolated-agent (with isolation: worktree)

The hook fires when Claude creates a new git worktree for the agent's isolated workspace.

Use Cases

๐Ÿ”Š
Voice: "Worktree created" Audio notification when a worktree is set up for an agent
๐Ÿ”ง
Custom VCS Setup Run setup scripts (install deps, configure git hooks) in the new worktree
๐Ÿ“‹
Log Worktree Activity Track which agents create worktrees and when
๐Ÿ”—
Symlink Dependencies Symlink node_modules or other large directories to save disk space
๐Ÿ”Š Sound: worktreecreate.wav โ€” "Worktree created"
20 WorktreeRemove Cannot Block

When It Triggers

When agent worktree isolation removes worktrees, enabling custom VCS teardown. This hook fires during the worktree removal process when agents with isolation: worktree finish their work (since v2.1.50).

How to Trigger

Triggered automatically when an isolated agent's worktree is cleaned up:

Agent completes work and worktree is removed

The hook fires when Claude removes a git worktree that was created for an agent's isolated workspace.

Use Cases

๐Ÿ”Š
Voice: "Worktree removed" Audio notification when a worktree is cleaned up
๐Ÿงน
Custom VCS Teardown Clean up temporary files, remove symlinks, or archive logs
๐Ÿ“‹
Log Cleanup Events Track when worktrees are removed for auditing
๐Ÿ’พ
Reclaim Disk Space Trigger garbage collection or cache cleanup after worktree removal
๐Ÿ”Š Sound: worktreeremove.wav โ€” "Worktree removed"
21 InstructionsLoaded Cannot Block

When It Triggers

When CLAUDE.md or .claude/rules/*.md files are loaded into context. This fires whenever instructions are read, including at session start and after instruction reloads (since v2.1.69).

How to Trigger

Triggered automatically when Claude Code loads instruction files:

Start a session with CLAUDE.md or .claude/rules/*.md present

The hook fires each time instructions are loaded or reloaded into context.

Use Cases

๐Ÿ”Š
Voice: "Instructions loaded" Audio notification when project instructions are loaded
๐Ÿ“
Log Instruction Loads Track when and which instruction files are loaded for auditing
๐Ÿ”„
Validate Instructions Check that loaded instructions meet organizational standards
๐Ÿ“Š
Monitor Instruction Changes Detect when instructions change between sessions or reloads
๐Ÿ”Š Sound: instructionsloaded.wav โ€” "Instructions loaded"
22 Elicitation Can Block

When It Triggers

When an MCP server requests user input during a tool call. Allows you to intercept, modify, or block elicitation requests before the user sees them.

How to Trigger

Use an MCP server that sends elicitation requests (e.g. @blizzy/mcp-elicit):

"Use the elicit_boolean tool to ask me if I like pizza" โ†’ Elicitation hook fires
Matcher: MCP server name

Use Cases

๐Ÿ”Š
Voice: "MCP input requested" Audio alert when an MCP server needs user input
๐Ÿ›ก๏ธ
Filter Sensitive Requests Block or modify elicitation requests from untrusted servers
๐Ÿ“
Audit MCP Interactions Log all elicitation requests for compliance tracking
๐Ÿ”Š Sound: elicitation.wav โ€” "MCP input requested"
23 ElicitationResult Can Block

When It Triggers

After a user responds to an MCP elicitation, before the response is sent back to the server. Allows you to intercept, modify, or block the user's response.

How to Trigger

User responds to an MCP elicitation dialog (e.g. the pizza question above):

User clicks Yes/No โ†’ ElicitationResult hook fires โ†’ Response sent to server
Matcher: MCP server name

Use Cases

๐Ÿ”Š
Voice: "Response submitted" Audio confirmation when user responds to an MCP elicitation
๐Ÿ”’
Sanitize Responses Strip sensitive data before it's sent to the MCP server
๐Ÿ“Š
Track User Decisions Log accept/decline/cancel actions for analytics
๐Ÿ”Š Sound: elicitationresult.wav โ€” "Response submitted"
24 StopFailure Cannot Block

When It Triggers

When the turn ends due to an API error (rate limit, auth failure, etc.). Unlike Stop, this fires on error conditions rather than successful completion. Introduced in v2.1.78 to prevent infinite loops when stop hooks re-feed blocking errors to the model.

How to Trigger

API error occurs during Claude's response (rate limit exceeded, authentication failure, network error):

Claude processing โ†’ API error โ†’ StopFailure hook fires

Use Cases

๐Ÿ”Š
Voice: "Stop failure" Audio alert when a turn ends due to an API error
๐Ÿ“Š
Error Tracking Log API failures for monitoring rate limits and auth issues
๐Ÿ””
Alert on Failures Send desktop notification when API errors interrupt work
๐Ÿ”Š Sound: stopfailure.wav โ€” "Stop failure"
25 CwdChanged Cannot Block

When It Triggers

When the working directory changes during a session. Designed for reactive environment management โ€” for example, automatically loading environment variables via direnv when Claude navigates to a different project directory. Introduced in v2.1.83.

How to Trigger

Claude changes the current working directory during a session:

Claude navigates to new directory โ†’ CwdChanged hook fires

Use Cases

๐Ÿ”Š
Voice: "Directory changed" Audio alert when Claude moves to a different directory
๐ŸŒ
Environment Reload Automatically reload .env files or direnv when changing directories
๐Ÿ“‚
Context Awareness Load project-specific rules or configurations based on current directory
๐Ÿ”Š Sound: cwdchanged.wav โ€” "Directory changed"
26 FileChanged Cannot Block

When It Triggers

When files change during a session. Designed for reactive environment management โ€” for example, automatically reloading configuration when a .env file is modified by an external process. Introduced in v2.1.83 alongside CwdChanged.

How to Trigger

A watched file changes during a Claude Code session:

File modified externally โ†’ FileChanged hook fires

Use Cases

๐Ÿ”Š
Voice: "File changed" Audio alert when a watched file is modified
๐Ÿ”„
Hot Reload Automatically reload environment variables or config when files change
๐Ÿ“
Change Logging Track file modifications for audit or debugging purposes
๐Ÿ”Š Sound: filechanged.wav โ€” "File changed"
27 PermissionDenied Cannot Block

When It Triggers

Fires after the auto mode classifier denies a tool call. Your hook can return {retry: true} to tell the model it can retry the operation. Introduced in v2.1.88.

How to Trigger

A tool call is denied by the auto mode classifier:

Auto mode denies tool โ†’ PermissionDenied hook fires

Use Cases

๐Ÿ”Š
Voice: "Permission denied" Audio alert when auto mode blocks a tool call
๐Ÿ”„
Auto-Retry Logic Return {retry: true} to let the model retry with a different approach
๐Ÿ“Š
Denial Tracking Log denied tool calls for security auditing and permission tuning
๐Ÿ”Š Sound: permissiondenied.wav โ€” "Permission denied"

Agent Hooks (Bonus)

Claude Code 2.1.0 introduced support for agent-specific hooks defined in agent frontmatter files. These hooks only run within the agent's lifecycle.

Supported Agent Hooks

Agent frontmatter hooks support 6 of 27 hooks: PreToolUse, PostToolUse, PermissionRequest, PostToolUseFailure, Stop, and SubagentStop.

How to Trigger

Run the demo agent included in this repository:

> /agents claude-code-hook-agent

This agent fetches Dubai weather and triggers all 6 agent hooks.

The 6 Agent Hooks

๐Ÿ””
PreToolUse Fires before the agent uses any tool (Read, Bash, WebFetch, etc.)
โœ…
PostToolUse Fires after the agent's tool call completes successfully
๐Ÿ”
PermissionRequest Fires when a tool requires user permission
โŒ
PostToolUseFailure Fires after a tool call fails
๐Ÿ
Stop Fires when the agent finishes its task and returns control
๐Ÿ”š
SubagentStop Fires when a subagent completes its work

Agent Configuration Example (all 6 hooks)

# .claude/agents/my-agent.md --- name: my-agent hooks: PreToolUse: - matcher: ".*" hooks: - type: command command: python3 .claude/hooks/scripts/hooks.py --agent=my-agent PostToolUse: - matcher: ".*" hooks: - type: command command: python3 .claude/hooks/scripts/hooks.py --agent=my-agent PermissionRequest: - matcher: ".*" hooks: - type: command command: python3 .claude/hooks/scripts/hooks.py --agent=my-agent PostToolUseFailure: - matcher: ".*" hooks: - type: command command: python3 .claude/hooks/scripts/hooks.py --agent=my-agent Stop: - hooks: - type: command command: python3 .claude/hooks/scripts/hooks.py --agent=my-agent SubagentStop: - hooks: - type: command command: python3 .claude/hooks/scripts/hooks.py --agent=my-agent ---
๐Ÿ”Š Sounds: agent_pretooluse.wav, agent_posttooluse.wav, agent_permissionrequest.wav, agent_posttoolusefailure.wav, agent_stop.wav, agent_subagentstop.wav

Configuration

Hooks are configured in .claude/settings.json and can be individually enabled/disabled.

Hook Configuration in settings.json

// .claude/settings.json { "hooks": { "SessionStart": [{ "hooks": [{ "type": "command", "command": "python3 .claude/hooks/scripts/hooks.py", "timeout": 5000, "async": true, "once": true }] }] } }

Disable All Hooks

// .claude/settings.local.json (git-ignored) { "disableAllHooks": true }

Disable Individual Hooks

// .claude/hooks/config/hooks-config.local.json { "disablePreToolUseHook": true, "disablePostToolUseHook": true, "disableLogging": true }

Summary

Session Lifecycle

SessionStart โ€” First hook, loads context

SessionEnd โ€” Last hook, cleanup

PreCompact โ€” Before context compression

PostCompact โ€” After context compression

Setup โ€” Project initialization

ConfigChange โ€” Config file modified

WorktreeCreate โ€” Agent worktree created

WorktreeRemove โ€” Agent worktree removed

InstructionsLoaded โ€” Instructions loaded into context

Elicitation โ€” MCP server requests input

ElicitationResult โ€” User responds to MCP

StopFailure โ€” Turn ends due to API error

CwdChanged โ€” Working directory changes

FileChanged โ€” Files change during session

User Interaction

UserPromptSubmit โ€” Before processing prompt

Notification โ€” System alerts

PermissionRequest โ€” Permission dialogs

PermissionDenied โ€” Auto mode denial

Tool Execution

PreToolUse โ€” Before tool runs

PostToolUse โ€” After success

PostToolUseFailure โ€” After failure

Agents & Completion

SubagentStart โ€” Subagent spawned

SubagentStop โ€” Subagent finished

Stop โ€” Claude ready to stop

TeammateIdle โ€” Teammate agent idle

TaskCompleted โ€” Background task done

TaskCreated โ€” Task being created

Hooks That Can Block Execution

These hooks can prevent actions from proceeding:

UserPromptSubmit PreToolUse PermissionRequest SubagentStop Stop TeammateIdle TaskCompleted TaskCreated ConfigChange WorktreeCreate Elicitation ElicitationResult

Repository: github.com/shanraisshan/claude-code-hooks

Documentation: code.claude.com/docs/en/hooks

1 / 34
โ† โ†’ or Space to navigate