Claude Code hooks are handlers that run automatically at fixed points in a session: before a tool call (PreToolUse), after it (PostToolUse), when you submit a prompt (UserPromptSubmit), when Claude Code sends a notification (Notification), when Claude finishes responding (Stop) and at 28 other events. A handler can be a shell command, an HTTP endpoint, an MCP tool, a model prompt or a subagent. You define them under a hooks key in a settings file such as .claude/settings.json.
Anthropic’s official documentation is split in two: the hooks reference (every event, field and exit code) and the hooks guide (worked examples and troubleshooting). This page condenses both.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
]
}
}
Applies to: Claude Code 2.1.322 (changelog), hooks reference and guide as of November 11, 2026. Last checked: November 11, 2026.
The example above, from Anthropic’s hooks guide, runs Prettier on every file Claude edits or writes.
On this page
Why use hooks instead of instructions?
Anthropic’s guide describes hooks as deterministic control: an action always happens instead of depending on the model choosing to run it. Typical jobs from the docs are formatting files after edits, blocking commands before they run, sending a notification when Claude needs input, and injecting context at session start. For static project conventions that never change, the reference recommends CLAUDE.md instead, since it loads without running a script.
The reference states that the same hook events fire wherever Claude Code runs: the terminal, IDE extensions, the Desktop app and cloud sessions (hooks reference).
Where do hooks go?
Where you define a hook sets its scope (hook locations):
| Location | Scope | Shareable |
|---|---|---|
~/.claude/settings.json | All your projects | No, local to your machine |
.claude/settings.json | Single project | Yes, can be committed to the repo |
.claude/settings.local.json | Single project | No, gitignored when Claude Code saves a setting to it |
| Managed policy settings | Organization-wide | Yes, admin-controlled |
Plugin hooks/hooks.json | When the plugin is enabled | Yes, bundled with the plugin |
| Skill frontmatter | Rest of the session once the skill is invoked | Yes, defined in the skill file |
| Subagent frontmatter | While that subagent runs | Yes, defined in the subagent file |
Hook entries merge across levels instead of replacing each other. Hooks from settings files, managed settings and plugins also fire for tool calls inside subagents. Cloud sessions don’t read your local ~/.claude/settings.json, so hooks you keep only there don’t reach them.
Type /hooks in a session to open a read-only browser that labels each hook with its source and shows the full command and the file it came from; All events at the end of the list shows events with no hooks too. To change hooks, edit the JSON or ask Claude to do it; direct edits are normally picked up by the file watcher (/hooks menu). Plugin packaging is covered in our Claude Code plugins guide, and skill and subagent frontmatter in the skills and subagents guides.
How is a hook configured?
The configuration has three levels (configuration):
- A hook event, such as
PreToolUseorStop. - A matcher group that filters when it fires, such as “only for the Bash tool”.
- One or more hook handlers that run when the matcher matches.
There are five handler types (handler fields):
| Type | What runs | Default timeout |
|---|---|---|
command | A shell command or an executable; gets JSON on stdin, answers with exit codes and stdout | 600 s |
http | A POST of the JSON to a URL; answers with the response body | 600 s |
mcp_tool | A tool on a configured MCP server; its text output is read like command stdout | 600 s |
prompt | A single-turn evaluation by a Claude model | 30 s |
agent | A subagent that can use tools such as Read, Grep and Glob (experimental) | 60 s |
The 600-second default drops to 30 seconds on UserPromptSubmit, PreModelSwitch and PostModelSwitch, and to 10 seconds on MessageDisplay. SessionEnd hooks share a 1.5-second budget, which a longer per-hook timeout raises up to 60 seconds. All matching hooks run in parallel; when more than 12 of them are prompt or agent hooks, 12 run at once and the rest wait. An identical handler defined in more than one settings file runs once.
Exec form or shell form
A command hook without args runs in shell form: the command string goes to sh -c on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed. With args, it runs in exec form: command is spawned directly as an executable with no shell, so paths with spaces need no quoting (exec form and shell form). The reference’s plugin example:
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/scripts/format.js", "--fix"]
}
Use shell form when you need pipes, && or redirects, as in the Prettier example at the top.
Which hook events exist?
The hooks reference lists 33 events. The ones most setups use, with what exit code 2 does on each (exit code 2 per event):
| Event | When it fires | Exit code 2 |
|---|---|---|
SessionStart | A session begins or resumes | Shows stderr to you only |
UserPromptSubmit | You submit a prompt, before Claude processes it | Blocks the prompt |
PreToolUse | Before a tool call executes | Blocks the tool call |
PermissionRequest | A tool call needs a permission decision | Not honored; deny through JSON |
PostToolUse | After a tool call succeeds | Shows stderr to Claude; the tool already ran |
PostToolUseFailure | After a tool call fails | Shows stderr to Claude |
PostToolBatch | After a batch of parallel tool calls resolves | Stops the loop before the next model call |
Notification | Claude Code sends a notification | Ignored |
SubagentStart / SubagentStop | A subagent is spawned / finishes | Stop only: keeps the subagent working |
Stop | Claude finishes responding | Keeps Claude working |
PreCompact / PostCompact | Before / after context compaction | PreCompact only: blocks compaction |
PreModelSwitch / PostModelSwitch | Before / after the session’s model changes | Pre only: blocks the switch |
SessionEnd | A session terminates | Shows stderr to you only |
The full list also includes Setup, UserPromptExpansion, PermissionDenied, MessageDisplay, TaskCreated, TaskCompleted, StopFailure, TeammateIdle, InstructionsLoaded, ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove, Elicitation and ElicitationResult. Each has its own section in the reference with its input schema.
PreModelSwitch and PostModelSwitch require Claude Code v2.1.251 or later. PreModelSwitch runs for switches you or a client request, such as /model or the Model setting in /config; PostModelSwitch also runs after changes Claude Code makes on its own, such as an automatic model fallback or restoring the model on resume (PreModelSwitch, PostModelSwitch).
How does matcher syntax work?
The matcher value is read in one of three ways, depending on its characters (matcher patterns):
| Matcher value | Evaluated as | Example |
|---|---|---|
"*", "" or omitted | Match all | Fires on every occurrence of the event |
Only letters, digits, _, -, spaces, , and | | Exact string, or a list split by | or , | Bash; Edit|Write; Edit, Write |
| Any other character | Unanchored JavaScript regular expression | ^Notebook; mcp__memory__.* |
Because the regex path is unanchored, Edit.* also matches NotebookEdit; write ^Edit$ for a whole-string match. Matchers are case-sensitive. FileChanged and StopFailure use a narrower exact-match set (letters, digits, _ and | only).
What the matcher is compared against depends on the event: the tool name for PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest and PermissionDenied; startup, resume, clear, compact or fork for SessionStart; the notification type for Notification, such as permission_prompt or idle_prompt; manual or auto for compaction events; the agent type for SubagentStart and SubagentStop; the canonical model name, such as claude-opus-5, for the model-switch events. UserPromptSubmit, PostToolBatch, Stop, CwdChanged and several others have no matcher support, and a matcher there is silently ignored.
Since v2.1.314, a PreToolUse or PermissionRequest hook with a Bash matcher also runs on shell commands Claude starts with the Monitor tool, but its allow and updatedInput have no effect on them; a matcher such as Bash|Monitor gets the Monitor call’s own input (match Monitor commands).
MCP tools
MCP tools are named mcp__<server>__<tool>. To match every tool from one server, append .*: a bare mcp__memory is treated as an exact string and matches nothing (match MCP tools). Tools from a server bundled in a plugin carry the plugin name in the server segment, for example mcp__plugin_my-plugin_db__.*.
{
"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"
}
]
}
]
}
}
The memory server in that example is the reference Memory MCP Server. Server setup is covered in our Claude Code MCP guide.
The if field
On tool events, a handler can also take an if field in permission-rule syntax, such as "Bash(git *)" or "Edit(*.ts)", so the script only spawns when the tool call matches. It holds exactly one rule; for several conditions, define one handler per rule. On non-tool events, a handler with if set never runs. The reference notes that the filter is best-effort: when Claude Code can’t tell which commands a Bash input runs, it runs the hook anyway, so use the permission system rather than a hook to enforce a hard allow or deny (common fields).
What JSON does a hook receive?
Command hooks get JSON on stdin; HTTP hooks get the same JSON as the POST body. Every event includes session_id, transcript_path, cwd and hook_event_name, and most include permission_mode. Newer fields include scratchpad_dir (v2.1.257 or later) and an effort object on tool events. A PreToolUse hook for a Bash call receives (common input fields):
{
"session_id": "abc123",
"prompt_id": "550e8400-e29b-41d4-a716-446655440000",
"transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
"cwd": "/home/user/my-project",
"scratchpad_dir": "/tmp/claude-1000/-home-user-my-project/abc123/scratchpad",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "npm test",
"description": "Run test suite",
"timeout": 120000,
"run_in_background": false
},
"tool_use_id": "toolu_01ABC123..."
}
The mode labeled Manual in the interface arrives as "default". Inside a subagent the input also carries agent_id and agent_type. There is no $CLAUDE_MODEL variable; use a PostModelSwitch hook, which receives from_model and to_model, to follow model changes.
What do exit codes mean?
The outcome depends on the exit code and on what the hook printed to stdout. The reference’s table for events such as PreToolUse (exit code output):
| Stdout | Exit 0 | Exit 2 | Any other exit code |
|---|---|---|---|
| A JSON object that passes schema validation | Success; the fields apply | Blocks; the fields can’t override the block | Success; the exit code is ignored and the fields decide |
| JSON that can’t be parsed or fails validation | Non-blocking error | Blocks; stderr is the reason | Non-blocking error |
| Plain text, or nothing | Success | Blocks; stderr is the reason | Non-blocking error; the notice shows the first line of stderr |
A non-blocking error lets the action go ahead. That is why the docs warn about exit code 1: without valid JSON it doesn’t stop anything, even though 1 is the usual Unix failure code. “If your hook is meant to enforce a policy, use exit 2.” WorktreeCreate and WorktreeRemove fail on any non-zero exit. On PreToolUse, a timed-out hook doesn’t block the tool call either.
This script from the reference blocks rm commands by exiting 2:
#!/bin/bash
# Reads JSON input from stdin, checks the command
input=$(cat)
command=$(jq -r '.tool_input.command' <<<"$input")
if [[ "$command" == rm* ]]; then
echo "Blocked: rm commands are not allowed" >&2
exit 2 # Blocking error: tool call is prevented
fi
exit 0 # No decision: the normal permission flow applies
Make a failed hook block
Since v2.1.295, a command or http hook can set "onFailure": "block". A hook that can’t start, times out, exits with a code other than 0 or 2, gets a non-2xx HTTP status or prints invalid JSON then blocks the action the way exit 2 would; on PermissionRequest it denies the request (block the action when a hook fails). The field has no effect on Stop, SubagentStop, TaskCompleted, TeammateIdle or background hooks. The reference’s example:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/check-command.js"],
"onFailure": "block"
}
]
}
]
}
}
Without onFailure, the same missing script is a non-blocking error and the command runs.
What JSON can a hook return?
For finer control, exit 0 and print one JSON object on stdout, with nothing else around it. Universal fields include continue (set false to stop Claude entirely), stopReason, systemMessage (a warning shown to the user) and terminalSequence (an allowlisted escape sequence for desktop notifications). suppressOutput is still accepted but has no effect. additionalContext, systemMessage and plain stdout are each capped at 10,000 characters; longer output is saved to a file and Claude gets the path with a 2,000-character preview (JSON output).
Decision fields differ by event (decision control):
| Event | Decision fields |
|---|---|
PreToolUse | hookSpecificOutput.permissionDecision: allow, deny, ask or defer, plus permissionDecisionReason; updatedInput rewrites the tool’s arguments |
PermissionRequest | hookSpecificOutput.decision.behavior: allow or deny; updatedInput inside decision |
PreModelSwitch | permissionDecision (allow, deny or ask) or top-level decision: "block" |
UserPromptSubmit, PostToolUse, PostToolBatch, Stop, SubagentStop, PreCompact and others | Top-level decision: "block" with reason; PostToolUse can also replace the result with updatedToolOutput |
SessionStart, SubagentStart, PostModelSwitch | hookSpecificOutput.additionalContext; SessionStart also takes initialUserMessage, watchPaths, sessionTitle and reloadSkills; no blocking |
Notification, SessionEnd, PostCompact and others | None; side effects only |
A PreToolUse deny:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Database writes are not allowed"
}
}
Context for Claude goes in additionalContext:
{
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"additionalContext": "This file is generated. Edit src/schema.ts and run `bun generate` instead."
}
}
The reference advises writing that text as factual statements (“This repo uses bun test”) rather than imperative system instructions, which can trigger Claude’s prompt-injection defenses. If two PreToolUse hooks rewrite the same tool’s input, the guide says Claude Code doesn’t merge the rewrites or guarantee which one wins (limitations).
If a shell profile prints text on startup, it lands in front of your JSON and Claude Code reads the whole output as plain text. A field at the wrong level, such as permissionDecision at the top instead of inside hookSpecificOutput, is ignored without an error. The troubleshooting section covers both.
Examples from Anthropic’s docs
Desktop notification when Claude needs input
Add to ~/.claude/settings.json (macOS shown; the guide has Linux notify-send and Windows PowerShell versions):
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
}
]
}
]
}
}
The guide notes that osascript sends notifications through Script Editor; if Script Editor lacks notification permission, the command fails silently.
Block edits to protected files
-
Save this as
.claude/hooks/protect-files.sh:#!/bin/bash # protect-files.sh INPUT=$(cat) FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') # Normalize Windows backslash separators so the patterns below match FILE_PATH="${FILE_PATH//\\//}" PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/") for pattern in "${PROTECTED_PATTERNS[@]}"; do if [[ "$FILE_PATH" == *"$pattern"* ]]; then echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2 exit 2 fi done exit 0 -
Make it executable on macOS and Linux:
chmod +x .claude/hooks/protect-files.sh -
Register it in
.claude/settings.json:{ "hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" } ] } ] } }
Per the guide, Claude Code blocks the edit and passes the Blocked: message to Claude as feedback. The Bash examples need jq on your PATH.
Re-inject context after compaction
A SessionStart hook with the compact matcher adds its stdout to Claude’s context after every compaction (guide). More on compaction is in our compact and context guide.
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{
"type": "command",
"command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"
}
]
}
]
}
}
Ask a model whether work is finished
A prompt hook sends your prompt and the hook input to a Claude model, by default the model Claude Code uses for background work (set model to pick another). The model answers {"ok": true} or {"ok": false, "reason": "..."}. On Stop, a false answer feeds the reason back so Claude keeps working, unless the answer also sets "impossible": true, which lets the turn end (prompt-based hooks):
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."
}
]
}
]
}
}
On PreToolUse and PostToolUse, a false answer ends the turn by default; continueOnBlock: true returns the reason to Claude so it can adjust. The reference also points to the built-in /goal command as a shortcut for a session-scoped prompt-based Stop hook (Stop).
Security considerations
Warning
Anthropic’s reference states that “command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration.”
Points from the security section and hooks and permission modes:
- Workspace trust. In an interactive session, Claude Code holds back hooks from every settings file, including your own
~/.claude/settings.json, until you accept the workspace trust dialog. In a-por SDK session there is no dialog and the folder is treated as trusted, so hooks committed in a repository’s.claude/settings.jsonrun. Before scriptingclaude -pover a repository you didn’t write, the docs say to review its.claude/settings, start with--bare, or pass--settings '{"disableAllHooks": true}'. - Hooks tighten, they don’t loosen. A
PreToolUsedeny blocks the tool in every permission mode, includingbypassPermissionsand--dangerously-skip-permissions(see our guide to that flag for the safer modes). A hook returningallowdoesn’t override deny rules from settings, and in plan mode anallowfor a file edit gets the same prompt or block the edit would get without the hook. - Write defensive scripts. Validate inputs, quote shell variables (
"$VAR"), block..path traversal, use absolute paths or${CLAUDE_PROJECT_DIR}, and skip sensitive files such as.env,.git/and keys. - Watch the first run. A missing or non-executable script exits with a code like 127, which is non-blocking, so a mistyped path in
settings.jsonleaves a policy hook silently disabled. Set"onFailure": "block"on policy hooks so a hook that can’t start blocks instead. - Organization control. Admins can set
allowManagedHooksOnlyin managed settings to block user, project, local and plugin hooks (plugins force-enabled in managedenabledPluginsare exempt).disableAllHooksoutside managed settings can’t disable managed hooks.allowedHttpHookUrlslimits where HTTP hooks may send data, andhttpHookAllowedEnvVarslimits which environment variables reach hook headers.
To turn all hooks off, set "disableAllHooks": true. The value left after settings precedence wins, so a false in a project’s .claude/settings.json overrides a true in your user settings; --settings '{"disableAllHooks": true}' turns hooks off for one run whatever the project says. There is no switch to disable a single hook while keeping it in the file (disable or remove hooks).
How do I debug a hook?
-
Run
/hooksand confirm the hook appears under the right event. A hook in a skill’s frontmatter only shows after the skill has been invoked in the session. -
Pipe sample JSON into the script and check the exit code:
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh echo $? # Check the exit code -
Start Claude Code with
claude --debug-file /tmp/claude.logandtail -fthat file, or runclaude --debugand read~/.claude/debug/<session-id>.txt. Mid-session,/debugturns logging on and shows the log path. From v2.1.296, each command hook on tool events and several others leaves aHooks:line with its exit status and duration, which helps find a slow hook. SetCLAUDE_CODE_DEBUG_LOG_LEVEL=verbosefor matcher details (debug hooks). -
Press
Ctrl+Oto open the transcript view: a non-blocking error shows ahook errornotice, while a successful hook shows nothing unless its JSON surfaces something (check what a hook did).
Hooks in other agents work differently; compare Codex hooks, Cursor hooks and GitHub Copilot hooks. More configuration guides are in Skills & config and the Claude Code section.





