Configuration
Claude Code hooks are configured in your settings files:~/.claude/settings.json- User settings.claude/settings.json- Project settings.claude/settings.local.json- Local project settings (not committed)- Enterprise managed policy settings
Structure
Hooks are organized by matchers, where each matcher can have multiple hooks:- matcher: Pattern to match tool names, case-sensitive (only applicable for
PreToolUseandPostToolUse)- Simple strings match exactly:
Writematches only the Write tool - Supports regex:
Edit|WriteorNotebook.* - Use
*to match all tools. You can also use empty string ("") or leavematcherblank.
- Simple strings match exactly:
- hooks: Array of hooks to execute when the pattern matches
type: Hook execution type -"command"for bash commands or"prompt"for LLM-based evaluationcommand: (Fortype: "command") The bash command to execute (can use$CLAUDE_PROJECT_DIRenvironment variable)prompt: (Fortype: "prompt") The prompt to send to the LLM for evaluationtimeout: (Optional) How long a hook should run, in seconds, before canceling that specific hook
UserPromptSubmit, Stop, and SubagentStop
that don’t use matchers, you can omit the matcher field:
Project-Specific Hook Scripts
You can use the environment variableCLAUDE_PROJECT_DIR (only available when
Claude Code spawns the hook command) to reference scripts stored in your project,
ensuring they work regardless of Claude’s current directory:
Plugin hooks
Plugins can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled. How plugin hooks work:- Plugin hooks are defined in the plugin’s
hooks/hooks.jsonfile or in a file given by a custom path to thehooksfield. - When a plugin is enabled, its hooks are merged with user and project hooks
- Multiple hooks from different sources can respond to the same event
- Plugin hooks use the
${CLAUDE_PLUGIN_ROOT}environment variable to reference plugin files
Plugin hooks use the same format as regular hooks with an optional
description field to explain the hook’s purpose.Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.
${CLAUDE_PLUGIN_ROOT}: Absolute path to the plugin directory${CLAUDE_PROJECT_DIR}: Project root directory (same as for project hooks)- All standard environment variables are available
Prompt-Based Hooks
In addition to bash command hooks (type: "command"), Claude Code supports prompt-based hooks (type: "prompt") that use an LLM to evaluate whether to allow or block an action. Prompt-based hooks are currently only supported for Stop and SubagentStop hooks, where they enable intelligent, context-aware decisions.
How prompt-based hooks work
Instead of executing a bash command, prompt-based hooks:- Send the hook input and your prompt to a fast LLM (Haiku)
- The LLM responds with structured JSON containing a decision
- Claude Code processes the decision automatically
Configuration
type: Must be"prompt"prompt: The prompt text to send to the LLM- Use
$ARGUMENTSas a placeholder for the hook input JSON - If
$ARGUMENTSis not present, input JSON is appended to the prompt
- Use
timeout: (Optional) Timeout in seconds (default: 30 seconds)
Response schema
The LLM must respond with JSON containing:decision:"approve"allows the action,"block"prevents itreason: Explanation shown to Claude when decision is"block"continue: (Optional) Iffalse, stops Claude’s execution entirelystopReason: (Optional) Message shown whencontinueis falsesystemMessage: (Optional) Additional message shown to the user
Supported hook events
Prompt-based hooks work with any hook event, but are most useful for:- Stop: Intelligently decide if Claude should continue working
- SubagentStop: Evaluate if a subagent has completed its task
- UserPromptSubmit: Validate user prompts with LLM assistance
- PreToolUse: Make context-aware permission decisions
Example: Intelligent Stop hook
Example: SubagentStop with custom logic
Comparison with bash command hooks
| Feature | Bash Command Hooks | Prompt-Based Hooks |
|---|---|---|
| Execution | Runs bash script | Queries LLM |
| Decision logic | You implement in code | LLM evaluates context |
| Setup complexity | Requires script file | Just configure prompt |
| Context awareness | Limited to script logic | Natural language understanding |
| Performance | Fast (local execution) | Slower (API call) |
| Use case | Deterministic rules | Context-aware decisions |
Best practices
- Be specific in prompts: Clearly state what you want the LLM to evaluate
- Include decision criteria: List the factors the LLM should consider
- Test your prompts: Verify the LLM makes correct decisions for your use cases
- Set appropriate timeouts: Default is 30 seconds, adjust if needed
- Use for complex decisions: Bash hooks are better for simple, deterministic rules
Hook Events
PreToolUse
Runs after Claude creates tool parameters and before processing the tool call. Common matchers:Task- Subagent tasks (see subagents documentation)Bash- Shell commandsGlob- File pattern matchingGrep- Content searchRead- File readingEdit- File editingWrite- File writingWebFetch,WebSearch- Web operations
PermissionRequest
Runs when the user is shown a permission dialog. Use PermissionRequest decision control to allow or deny on behalf of the user. Recognizes the same matcher values as PreToolUse.PostToolUse
Runs immediately after a tool completes successfully. Recognizes the same matcher values as PreToolUse.Notification
Runs when Claude Code sends notifications. Supports matchers to filter by notification type. Common matchers:permission_prompt- Permission requests from Claude Codeidle_prompt- When Claude is waiting for user input (after 60+ seconds of idle time)auth_success- Authentication success notificationselicitation_dialog- When Claude Code needs input for MCP tool elicitation
UserPromptSubmit
Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts.Stop
Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt.SubagentStop
Runs when a Claude Code subagent (Task tool call) has finished responding.PreCompact
Runs before Claude Code is about to run a compact operation. Matchers:manual- Invoked from/compactauto- Invoked from auto-compact (due to full context window)
SessionStart
Runs when Claude Code starts a new session or resumes an existing session (which currently does start a new session under the hood). Useful for loading in development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables. Matchers:startup- Invoked from startupresume- Invoked from--resume,--continue, or/resumeclear- Invoked from/clearcompact- Invoked from auto or manual compact.
Persisting environment variables
SessionStart hooks have access to theCLAUDE_ENV_FILE environment variable, which provides a file path where you can persist environment variables for subsequent bash commands.
Example: Setting individual environment variables
nvm use), capture and persist all changes by diffing the environment:
CLAUDE_ENV_FILE is only available for SessionStart hooks. Other hook types do not have access to this variable.SessionEnd
Runs when a Claude Code session ends. Useful for cleanup tasks, logging session statistics, or saving session state. Thereason field in the hook input will be one of:
clear- Session cleared with /clear commandlogout- User logged outprompt_input_exit- User exited while prompt input was visibleother- Other exit reasons
Hook Input
Hooks receive JSON data via stdin containing session information and event-specific data:PreToolUse Input
The exact schema fortool_input depends on the tool.
PostToolUse Input
The exact schema fortool_input and tool_response depends on the tool.
Notification Input
UserPromptSubmit Input
Stop and SubagentStop Input
stop_hook_active is true when Claude Code is already continuing as a result of
a stop hook. Check this value or process the transcript to prevent Claude Code
from running indefinitely.
PreCompact Input
Formanual, custom_instructions comes from what the user passes into
/compact. For auto, custom_instructions is empty.
SessionStart Input
SessionEnd Input
Hook Output
There are two mutually-exclusive ways for hooks to return output back to Claude Code. The output communicates whether to block and any feedback that should be shown to Claude and the user.Simple: Exit Code
Hooks communicate status through exit codes, stdout, and stderr:- Exit code 0: Success.
stdoutis shown to the user in verbose mode (ctrl+o), except forUserPromptSubmitandSessionStart, where stdout is added to the context. JSON output instdoutis parsed for structured control (see Advanced: JSON Output). - Exit code 2: Blocking error. Only
stderris used as the error message and fed back to Claude. The format is[command]: {stderr}. JSON instdoutis not processed for exit code 2. See per-hook-event behavior below. - Other exit codes: Non-blocking error.
stderris shown to the user in verbose mode (ctrl+o) with formatFailed with non-blocking status code: {stderr}. Ifstderris empty, it showsNo stderr output. Execution continues.
Exit Code 2 Behavior
| Hook Event | Behavior |
|---|---|
PreToolUse | Blocks the tool call, shows stderr to Claude |
PostToolUse | Shows stderr to Claude (tool already ran) |
Notification | N/A, shows stderr to user only |
UserPromptSubmit | Blocks prompt processing, erases prompt, shows stderr to user only |
Stop | Blocks stoppage, shows stderr to Claude |
SubagentStop | Blocks stoppage, shows stderr to Claude subagent |
PreCompact | N/A, shows stderr to user only |
SessionStart | N/A, shows stderr to user only |
SessionEnd | N/A, shows stderr to user only |
Advanced: JSON Output
Hooks can return structured JSON instdout for more sophisticated control.
Common JSON Fields
All hook types can include these optional fields:continue is false, Claude stops processing after the hooks run.
- For
PreToolUse, this is different from"permissionDecision": "deny", which only blocks a specific tool call and provides automatic feedback to Claude. - For
PostToolUse, this is different from"decision": "block", which provides automated feedback to Claude. - For
UserPromptSubmit, this prevents the prompt from being processed. - For
StopandSubagentStop, this takes precedence over any"decision": "block"output. - In all cases,
"continue" = falsetakes precedence over any"decision": "block"output.
stopReason accompanies continue with a reason shown to the user, not shown
to Claude.
PreToolUse Decision Control
PreToolUse hooks can control whether a tool call proceeds.
"allow"bypasses the permission system.permissionDecisionReasonis shown to the user but not to Claude."deny"prevents the tool call from executing.permissionDecisionReasonis shown to Claude."ask"asks the user to confirm the tool call in the UI.permissionDecisionReasonis shown to the user but not to Claude.
updatedInput:
updatedInputallows you to modify the tool’s input parameters before the tool executes.- This is most useful with
"permissionDecision": "allow"to modify and approve tool calls.
The
decision and reason fields are deprecated for PreToolUse hooks.
Use hookSpecificOutput.permissionDecision and
hookSpecificOutput.permissionDecisionReason instead. The deprecated fields
"approve" and "block" map to "allow" and "deny" respectively.PermissionRequest Decision Control
PermissionRequest hooks can allow or deny permission requests shown to the user.
- For
"behavior": "allow"you can also optionally pass in an"updatedInput"that modifies the tool’s input parameters before the tool executes. - For
"behavior": "deny"you can also optionally pass in a"message"string that tells the model why the permission was denied, and a boolean"interrupt"which will stop Claude.
PostToolUse Decision Control
PostToolUse hooks can provide feedback to Claude after tool execution.
"block"automatically prompts Claude withreason.undefineddoes nothing.reasonis ignored."hookSpecificOutput.additionalContext"adds context for Claude to consider.
UserPromptSubmit Decision Control
UserPromptSubmit hooks can control whether a user prompt is processed and add context.
Adding context (exit code 0):
There are two ways to add context to the conversation:
- Plain text stdout (simpler): Any non-JSON text written to stdout is added as context. This is the easiest way to inject information.
-
JSON with
additionalContext(structured): Use the JSON format below for more control. TheadditionalContextfield is added as context.
additionalContext is added more discretely.
Blocking prompts:
"decision": "block"prevents the prompt from being processed. The submitted prompt is erased from context."reason"is shown to the user but not added to context."decision": undefined(or omitted) allows the prompt to proceed normally.
The JSON format is not required for simple use cases. To add context, you can
just print plain text to stdout with exit code 0. Use JSON when you need to
block prompts or want more structured control.
Stop/SubagentStop Decision Control
Stop and SubagentStop hooks can control whether Claude must continue.
"block"prevents Claude from stopping. You must populatereasonfor Claude to know how to proceed.undefinedallows Claude to stop.reasonis ignored.
SessionStart Decision Control
SessionStart hooks allow you to load in context at the start of a session.
"hookSpecificOutput.additionalContext"adds the string to the context.- Multiple hooks’
additionalContextvalues are concatenated.
SessionEnd Decision Control
SessionEnd hooks run when a session ends. They cannot block session termination
but can perform cleanup tasks.
Exit Code Example: Bash Command Validation
JSON Output Example: UserPromptSubmit to Add Context and Validation
For
UserPromptSubmit hooks, you can inject context using either method:- Plain text stdout with exit code 0: Simplest approach—just print text
- JSON output with exit code 0: Use
"decision": "block"to reject prompts, oradditionalContextfor structured context injection
stderr for the error message. To block using
JSON (with a custom reason), use "decision": "block" with exit code 0.JSON Output Example: PreToolUse with Approval
Working with MCP Tools
Claude Code hooks work seamlessly with Model Context Protocol (MCP) tools. When MCP servers provide tools, they appear with a special naming pattern that you can match in your hooks.MCP Tool Naming
MCP tools follow the patternmcp__<server>__<tool>, for example:
mcp__memory__create_entities- Memory server’s create entities toolmcp__filesystem__read_file- Filesystem server’s read file toolmcp__github__search_repositories- GitHub server’s search tool
Configuring Hooks for MCP Tools
You can target specific MCP tools or entire MCP servers:Examples
Security Considerations
Disclaimer
USE AT YOUR OWN RISK: Claude Code hooks execute arbitrary shell commands on your system automatically. By using hooks, you acknowledge that:- You are solely responsible for the commands you configure
- Hooks can modify, delete, or access any files your user account can access
- Malicious or poorly written hooks can cause data loss or system damage
- Anthropic provides no warranty and assumes no liability for any damages resulting from hook usage
- You should thoroughly test hooks in a safe environment before production use
Security Best Practices
Here are some key practices for writing more secure hooks:- Validate and sanitize inputs - Never trust input data blindly
- Always quote shell variables - Use
"$VAR"not$VAR - Block path traversal - Check for
..in file paths - Use absolute paths - Specify full paths for scripts (use “$CLAUDE_PROJECT_DIR” for the project path)
- Skip sensitive files - Avoid
.env,.git/, keys, etc.
Configuration Safety
Direct edits to hooks in settings files don’t take effect immediately. Claude Code:- Captures a snapshot of hooks at startup
- Uses this snapshot throughout the session
- Warns if hooks are modified externally
- Requires review in
/hooksmenu for changes to apply
Hook Execution Details
- Timeout: 60-second execution limit by default, configurable per command.
- A timeout for an individual command does not affect the other commands.
- Parallelization: All matching hooks run in parallel
- Deduplication: Multiple identical hook commands are deduplicated automatically
- Environment: Runs in current directory with Claude Code’s environment
- The
CLAUDE_PROJECT_DIRenvironment variable is available and contains the absolute path to the project root directory (where Claude Code was started) - The
CLAUDE_CODE_REMOTEenvironment variable indicates whether the hook is running in a remote (web) environment ("true") or local CLI environment (not set or empty). Use this to run different logic based on execution context.
- The
- Input: JSON via stdin
- Output:
- PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o)
- Notification/SessionEnd: Logged to debug only (
--debug) - UserPromptSubmit/SessionStart: stdout added as context for Claude
Debugging
Basic Troubleshooting
If your hooks aren’t working:- Check configuration - Run
/hooksto see if your hook is registered - Verify syntax - Ensure your JSON settings are valid
- Test commands - Run hook commands manually first
- Check permissions - Make sure scripts are executable
- Review logs - Use
claude --debugto see hook execution details
- Quotes not escaped - Use
\"inside JSON strings - Wrong matcher - Check tool names match exactly (case-sensitive)
- Command not found - Use full paths for scripts
Advanced Debugging
For complex hook issues:- Inspect hook execution - Use
claude --debugto see detailed hook execution - Validate JSON schemas - Test hook input/output with external tools
- Check environment variables - Verify Claude Code’s environment is correct
- Test edge cases - Try hooks with unusual file paths or inputs
- Monitor system resources - Check for resource exhaustion during hook execution
- Use structured logging - Implement logging in your hook scripts
Debug Output Example
Useclaude --debug to see hook execution details:
- Which hook is running
- Command being executed
- Success/failure status
- Output or error messages