Claude Code hooks: all events, exit codes, PreToolUse and PermissionRequest JSON, examples
How do I run a command automatically when Claude Code edits a file?
Add a hooks block to .claude/settings.json (project) or ~/.claude/settings.json (user). A PostToolUse hook with matcher "Edit|Write" runs after every file edit; a PreToolUse hook that exits with code 2 blocks the action and sends its stderr back as the reason. Type /hooks in Claude Code to see what is configured. For finer control, print JSON with hookSpecificOutput.permissionDecision set to allow, deny, ask or defer, or answer permission prompts for you with a PermissionRequest hook.
Compare: hooks in every AI coding agent →
Format every file Claude edits
.claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
]
}
}Block edits to protected files
Hooks receive the tool call as JSON on stdin. Exit 2 to block with a reason on stderr; exit 0 makes no decision, so the normal permission flow still applies. Make the script executable with chmod +x.
.claude/hooks/protect-files.sh
#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
for pattern in ".env" "package-lock.json" ".git/"; do
if [[ "$FILE_PATH" == *"$pattern"* ]]; then
echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
exit 2
fi
done
exit 0.claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }
]
}
]
}
}Other useful events
- Notification: fires when Claude is waiting for input or permission; pair it with a desktop notification command.
- SessionStart with matcher "compact": re-inject key context after the conversation is compacted.
- Hooks are deterministic: use them for rules that must always hold, and CLAUDE.md for guidance.
Every hook event
- Session: SessionStart (start or resume), Setup (--init-only, or --init and --maintenance in -p mode), SessionEnd.
- Prompts: UserPromptSubmit (before Claude reads your prompt, can block it) and UserPromptExpansion (when a typed command expands into a prompt, can block).
- Tools: PreToolUse (before a tool runs, can block), PermissionRequest (a call needs a permission decision), PermissionDenied (auto mode denied a call), PostToolUse (after a tool succeeds), PostToolUseFailure (after it fails), PostToolBatch (after a batch of parallel tool calls, can stop the loop).
- Turn end: Stop (Claude finished responding; blocking makes it continue) and StopFailure (the turn ended on an API error).
- Subagents and tasks: SubagentStart, SubagentStop, TaskCreated, TaskCompleted, TeammateIdle.
- Context: InstructionsLoaded (CLAUDE.md or .claude/rules/*.md loaded), PreCompact, PostCompact, PreModelSwitch, PostModelSwitch.
- Environment: ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove.
- Other: Notification, MessageDisplay, Elicitation and ElicitationResult (an MCP server asks you for input).
Exit codes: 0, 2 and everything else
- Exit 0: success. If stdout is a single JSON object, Claude Code applies its fields. Plain text stdout is added as context only for UserPromptSubmit, UserPromptExpansion, SessionStart and PostModelSwitch.
- Exit 2: block. On events that can block, the action stops, for example a PreToolUse hook blocks the tool call and a UserPromptSubmit hook rejects the prompt. Stderr is sent to Claude as the reason.
- Any other exit code, including 1, is a non-blocking error: the action goes ahead and a hook error notice appears in the transcript. Use exit 2 to enforce a policy.
- Set "onFailure": "block" on a command or http hook (Claude Code 2.1.295 or later) so that a hook that crashes, times out or cannot start also blocks the action.
PreToolUse JSON: allow, deny, ask or defer
Instead of an exit code, a PreToolUse hook can exit 0 and print JSON. permissionDecision takes allow, deny, ask or defer, and permissionDecisionReason explains it. updatedInput replaces the tool arguments before the call runs, and additionalContext adds a note for Claude next to the tool result.
PreToolUse hook output (stdout)
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Database writes are not allowed"
}
}- PostToolUse and Stop use a top-level "decision": "block" with a reason. After PostToolUse the tool has already run, so the block is feedback for Claude. On Stop it makes Claude keep working.
- Fields that work on every event: continue (false stops Claude after the hook), stopReason (shown to you when continue is false) and systemMessage (a warning shown to you).
- Exit 2 blocks even if the JSON says allow.
- When several PreToolUse hooks match, the most restrictive answer wins, in the order deny, defer, ask, allow. additionalContext from every hook is passed to Claude.
- defer only works in non-interactive mode (claude -p). It ends the turn with the tool call preserved, so an Agent SDK wrapper can collect input and resume.
- permissionDecision belongs inside hookSpecificOutput. At the top level it is ignored without an error; claude --debug logs "Hook JSON output had unrecognized keys".
Auto-approve permission prompts with PermissionRequest
A PermissionRequest hook runs when Claude Code is about to show you a permission prompt. If it prints a decision with behavior allow, Claude Code answers the prompt for you and the transcript shows "Allowed by PermissionRequest hook". Exit code 2 is not honored on this event; deny through the decision object instead. This example only approves ExitPlanMode, the prompt shown when a plan is ready.
~/.claude/settings.json
{
"hooks": {
"PermissionRequest": [
{
"matcher": "ExitPlanMode",
"hooks": [
{
"type": "command",
"command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"
}
]
}
]
}
}- decision.behavior is allow or deny. With allow you can also return updatedInput to change the tool arguments, for example to run npm run lint instead.
- To switch permission mode as you approve, add updatedPermissions with a setMode entry, such as {"type": "setMode", "mode": "acceptEdits", "destination": "session"}. destination session applies it to the current session only.
- setMode to bypassPermissions only works if the session started with bypass available (--dangerously-skip-permissions, --permission-mode bypassPermissions, --allow-dangerously-skip-permissions or permissions.defaultMode bypassPermissions in user, --settings or managed settings) and it is not disabled by permissions.disableBypassPermissionsMode. Claude Code never saves it as defaultMode.
- Keep the matcher narrow. An empty matcher or .* approves every prompt, including file writes and shell commands.
- In claude -p, PermissionRequest hooks still run outside dontAsk mode, and a call that no hook decides and nothing else can answer is denied.
What a hook can and cannot override
- A PreToolUse deny blocks the tool in every permission mode, including bypassPermissions and --dangerously-skip-permissions. PreToolUse hooks run before any permission mode check, so this is how to enforce a rule people cannot switch off by changing mode.
- A hook allow does not get past deny rules from settings, including managed deny lists, and ask rules still prompt.
- A hook allow also cannot skip the prompt for reads from network paths, MCP tools marked requiresUserInteraction, or connector tools your organization set to ask.
- In plan mode, a PreToolUse allow on a file edit gets the same prompt, block or approval the edit would get with no hook, until you approve the plan or switch modes.
Matchers and the if field
- "*", an empty string or no matcher: matches every tool.
- Letters, digits, _, -, spaces, commas and |: an exact tool name or a list, such as Edit|Write.
- Anything else is an unanchored JavaScript regex, such as ^Notebook or mcp__memory__.*. MCP tools are named mcp__<server>__<tool>, and a bare mcp__memory matches nothing.
- if: one permission rule such as "Bash(git *)" or "Edit(*.ts)", checked on tool events only. The hook runs only when the call matches. There is no && or || in if; add a separate handler for each condition.
.claude/settings.json: run a check only before git commands
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(git *)",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-git.sh"
}
]
}
]
}
}Hook types and timeouts
- command: runs a shell command (or an exec form with args). Default timeout 600 seconds.
- http: POSTs the event to a url, with optional headers. Default timeout 600 seconds.
- mcp_tool: calls a tool on a connected MCP server, with input such as "${tool_input.file_path}". Default timeout 600 seconds.
- prompt: asks a model to decide, with $ARGUMENTS for the event input. Default timeout 30 seconds.
- agent (experimental): like prompt, but runs a subagent that can use tools such as Read, Grep and Glob. Default timeout 60 seconds.
- Claude Code lowers the command, http and mcp_tool default to 30 seconds on UserPromptSubmit, PreModelSwitch and PostModelSwitch.
Where hooks live
- ~/.claude/settings.json: all your projects.
- .claude/settings.json: one project, shared through the repo.
- .claude/settings.local.json: one project, not committed.
- Managed policy settings: the whole organization.
- A plugin's hooks/hooks.json while the plugin is enabled, and the frontmatter of a skill or subagent.
- Hooks from every level are merged. /hooks opens a read-only list of configured hooks and shows where each is defined.
- Useful variables: CLAUDE_PROJECT_DIR (the project root where the session started), CLAUDE_PLUGIN_ROOT and CLAUDE_EFFORT.
Sources
More Claude Code guides
- How to allow Claude Code to run all commands: permission modes, allow rules and skip permissions
- Claude Code permissions: allow, ask and deny rules, rule syntax and allowed tools
- Claude Code telemetry and data retention: what is sent and how to turn it off
- CLAUDE.md: where it goes, how it loads, and how it works with AGENTS.md
- Claude Code subagents: create one, limit its tools, and call it
- Add MCP servers to Claude Code (claude mcp add, .mcp.json, scopes)
- Claude Code custom slash commands and skills (SKILL.md)
- Claude Code settings.json: file locations, precedence, and key settings
- Claude Code plugins and marketplaces: install, create, and share
- Claude Code headless mode: claude -p, --output-format json, --bare and CI flags
- Claude Code statusline: custom status bar in settings.json with context %, cost and git branch
- Claude Code /model: switch models, aliases (opus, sonnet, haiku, opusplan), ANTHROPIC_MODEL and effort
- Claude Code /cost and /usage: check token spend, usage limits and reduce costs
- Claude Code VS Code extension: install, shortcuts, settings and /ide (works in Cursor too)
- MCP 2026-07-28 Migration Guide: Stateless Protocol, No Sessions, server/discover, MRTR, and SDK v2 Upgrade
- Subagents and Custom Agents Compared: Claude Code vs Codex vs Cursor vs Gemini CLI vs GitHub Copilot (2026)
- Allow all commands in any AI coding agent: Cursor, Claude Code, Codex, Gemini CLI, Copilot CLI and 7 more (2026)
- How to deploy a remote MCP server (Streamable HTTP): Cloudflare Workers, Vercel, Railway and more (2026)
- Claude Code sandbox: /sandbox, sandbox.enabled, allowedDomains, excludedCommands and strict mode
Reviewed Oct 21, 2026. Settings change often; the linked vendor docs are the source of truth.
Built an MCP server? Get it listed everywhere →
Shipping an Android app? Google Play needs 12 testers for 14 days first. Get them with Tester Exchange →