4 4
5# Hooks reference5# Hooks reference
6 6
7> Reference for Claude Code hook events, configuration schema, JSON input/output formats, exit codes, async hooks, prompt hooks, and MCP tool hooks.7> Reference for Claude Code hook events, configuration schema, JSON input/output formats, exit codes, async hooks, HTTP hooks, prompt hooks, and MCP tool hooks.
8 8
9<Tip>9<Tip>
10 For a quickstart guide with examples, see [Automate workflows with hooks](/en/hooks-guide).10 For a quickstart guide with examples, see [Automate workflows with hooks](/en/hooks-guide).
11</Tip>11</Tip>
12 12
13Hooks are user-defined shell commands or LLM prompts that execute automatically at specific points in Claude Code's lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks and MCP tool hooks. If you're setting up hooks for the first time, start with the [guide](/en/hooks-guide) instead.13Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code's lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you're setting up hooks for the first time, start with the [guide](/en/hooks-guide) instead.
14 14
15## Hook lifecycle15## Hook lifecycle
16 16
17Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, this arrives on stdin. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:17Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:
18 18
19<div style={{maxWidth: "500px", margin: "0 auto"}}>19<div style={{maxWidth: "500px", margin: "0 auto"}}>
20 <Frame>20 <Frame>
21 <img src="https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=5c25fedbc3db6f8882af50c3cc478c32" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop to SessionEnd" data-og-width="8876" width="8876" data-og-height="12492" height="12492" data-path="images/hooks-lifecycle.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=280&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=62406fcd5d4a189cc8842ee1bd946b84 280w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=560&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=fa3049022a6973c5f974e0f95b28169d 560w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=840&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=bd2890897db61a03160b93d4f972ff8e 840w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=1100&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=7ae8e098340479347135e39df4a13454 1100w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=1650&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=848a8606aab22c2ccaa16b6a18431e32 1650w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=2500&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=f3a9ef7feb61fa8fe362005aa185efbc 2500w" />21 <img src="https://mintcdn.com/claude-code/lBsitdsGyD9caWJQ/images/hooks-lifecycle.svg?fit=max&auto=format&n=lBsitdsGyD9caWJQ&q=85&s=be3486ef2cf2563eb213b6cbbce93982" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCompleted) to PostCompact and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, and InstructionsLoaded as standalone async events" width="520" height="1100" data-path="images/hooks-lifecycle.svg" />
22 </Frame>22 </Frame>
23</div>23</div>
24 24
25The table below summarizes when each event fires. The [Hook events](#hook-events) section documents the full input schema and decision control options for each one.25The table below summarizes when each event fires. The [Hook events](#hook-events) section documents the full input schema and decision control options for each one.
26 26
27| Event | When it fires |27| Event | When it fires |
28| :------------------- | :--------------------------------------------------- |28| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |
29| `SessionStart` | When a session begins or resumes |29| `SessionStart` | When a session begins or resumes |
30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |
31| `PreToolUse` | Before a tool call executes. Can block it |31| `PreToolUse` | Before a tool call executes. Can block it |
36| `SubagentStart` | When a subagent is spawned |36| `SubagentStart` | When a subagent is spawned |
37| `SubagentStop` | When a subagent finishes |37| `SubagentStop` | When a subagent finishes |
38| `Stop` | When Claude finishes responding |38| `Stop` | When Claude finishes responding |
39| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |
40| `TaskCompleted` | When a task is being marked as completed |
41| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |
42| `ConfigChange` | When a configuration file changes during a session |
43| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |
44| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |
39| `PreCompact` | Before context compaction |45| `PreCompact` | Before context compaction |
46| `PostCompact` | After context compaction completes |
47| `Elicitation` | When an MCP server requests user input during a tool call |
48| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |
40| `SessionEnd` | When a session terminates |49| `SessionEnd` | When a session terminates |
41 50
42### How a hook resolves51### How a hook resolves
61}70}
62```71```
63 72
64The script reads the JSON input from stdin, extracts the command, and blocks it if it contains `rm -rf`:73The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:
65 74
66```bash theme={null}75```bash theme={null}
67#!/bin/bash76#!/bin/bash
69COMMAND=$(jq -r '.tool_input.command')78COMMAND=$(jq -r '.tool_input.command')
70 79
71if echo "$COMMAND" | grep -q 'rm -rf'; then80if echo "$COMMAND" | grep -q 'rm -rf'; then
72 echo '{"decision":"block","reason":"Destructive command blocked by hook"}'81 jq -n '{
82 hookSpecificOutput: {
83 hookEventName: "PreToolUse",
84 permissionDecision: "deny",
85 permissionDecisionReason: "Destructive command blocked by hook"
86 }
87 }'
73else88else
74 exit 0 # allow the command89 exit 0 # allow the command
75fi90fi
78Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:93Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
79 94
80<Frame>95<Frame>
81 <img src="https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=7c13f51ffcbc37d22a593b27e2f2de72" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" data-og-width="780" width="780" data-og-height="290" height="290" data-path="images/hook-resolution.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=280&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=36a39a07e8bc1995dcb4639e09846905 280w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=560&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=6568d90c596c7605bbac2c325b0a0c86 560w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=840&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=255a6f68b9475a0e41dbde7b88002dad 840w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=1100&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=dcecf8d5edc88cd2bc49deb006d5760d 1100w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=1650&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=04fe51bf69ae375e9fd517f18674e35f 1650w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=2500&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=b1b76e0b77fddb5c7fa7bf302dacd80b 2500w" />96 <img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/hook-resolution.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=ad667ee6d86ab2276aa48a4e73e220df" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" width="780" height="290" data-path="images/hook-resolution.svg" />
82</Frame>97</Frame>
83 98
84<Steps>99<Steps>
98 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:113 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:
99 114
100 ```json theme={null}115 ```json theme={null}
101 { "decision": "block", "reason": "Destructive command blocked by hook" }116 {
117 "hookSpecificOutput": {
118 "hookEventName": "PreToolUse",
119 "permissionDecision": "deny",
120 "permissionDecisionReason": "Destructive command blocked by hook"
121 }
122 }
102 ```123 ```
103 124
104 If the command had been safe (like `npm test`), the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.125 If the command had been safe (like `npm test`), the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.
122See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.143See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.
123 144
124<Note>145<Note>
125 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, prompt, or agent that runs. "Hook" on its own refers to the general feature.146 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, prompt, or agent that runs. "Hook" on its own refers to the general feature.
126</Note>147</Note>
127 148
128### Hook locations149### Hook locations
145The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field:166The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field:
146 167
147| Event | What the matcher filters | Example matcher values |168| Event | What the matcher filters | Example matcher values |
148| :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------- |169| :-------------------------------------------------------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |
149| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |170| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
150| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |171| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |
151| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |172| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |
153| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |174| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |
154| `PreCompact` | what triggered compaction | `manual`, `auto` |175| `PreCompact` | what triggered compaction | `manual`, `auto` |
155| `SubagentStop` | agent type | same values as `SubagentStart` |176| `SubagentStop` | agent type | same values as `SubagentStart` |
156| `UserPromptSubmit`, `Stop` | no matcher support | always fires on every occurrence |177| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |
178| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded` | no matcher support | always fires on every occurrence |
157 179
158The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.180The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.
159 181
177}199}
178```200```
179 201
180`UserPromptSubmit` and `Stop` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.202`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `InstructionsLoaded` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
181 203
182#### Match MCP tools204#### Match MCP tools
183 205
225 247
226### Hook handler fields248### Hook handler fields
227 249
228Each object in the inner `hooks` array is a hook handler: the shell command, LLM prompt, or agent that runs when the matcher matches. There are three types:250Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, LLM prompt, or agent that runs when the matcher matches. There are four types:
229 251
230* **[Command hooks](#command-hook-fields)** (`type: "command"`): run a shell command. Your script receives the event's [JSON input](#hook-input-and-output) on stdin and communicates results back through exit codes and stdout.252* **[Command hooks](#command-hook-fields)** (`type: "command"`): run a shell command. Your script receives the event's [JSON input](#hook-input-and-output) on stdin and communicates results back through exit codes and stdout.
253* **[HTTP hooks](#http-hook-fields)** (`type: "http"`): send the event's JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same [JSON output format](#json-output) as command hooks.
231* **[Prompt hooks](#prompt-and-agent-hook-fields)** (`type: "prompt"`): send a prompt to a Claude model for single-turn evaluation. The model returns a yes/no decision as JSON. See [Prompt-based hooks](#prompt-based-hooks).254* **[Prompt hooks](#prompt-and-agent-hook-fields)** (`type: "prompt"`): send a prompt to a Claude model for single-turn evaluation. The model returns a yes/no decision as JSON. See [Prompt-based hooks](#prompt-based-hooks).
232* **[Agent hooks](#prompt-and-agent-hook-fields)** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. See [Agent-based hooks](#agent-based-hooks).255* **[Agent hooks](#prompt-and-agent-hook-fields)** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. See [Agent-based hooks](#agent-based-hooks).
233 256
237 260
238| Field | Required | Description |261| Field | Required | Description |
239| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |262| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
240| `type` | yes | `"command"`, `"prompt"`, or `"agent"` |263| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |
241| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |264| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |
242| `statusMessage` | no | Custom spinner message displayed while the hook runs |265| `statusMessage` | no | Custom spinner message displayed while the hook runs |
243| `once` | no | If `true`, runs only once per session then is removed. Skills only, not agents. See [Hooks in skills and agents](#hooks-in-skills-and-agents) |266| `once` | no | If `true`, runs only once per session then is removed. Skills only, not agents. See [Hooks in skills and agents](#hooks-in-skills-and-agents) |
251| `command` | yes | Shell command to execute |274| `command` | yes | Shell command to execute |
252| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |275| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |
253 276
277#### HTTP hook fields
278
279In addition to the [common fields](#common-fields), HTTP hooks accept these fields:
280
281| Field | Required | Description |
282| :--------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
283| `url` | yes | URL to send the POST request to |
284| `headers` | no | Additional HTTP headers as key-value pairs. Values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in `allowedEnvVars` are resolved |
285| `allowedEnvVars` | no | List of environment variable names that may be interpolated into header values. References to unlisted variables are replaced with empty strings. Required for any env var interpolation to work |
286
287Claude Code sends the hook's [JSON input](#hook-input-and-output) as the POST request body with `Content-Type: application/json`. The response body uses the same [JSON output format](#json-output) as command hooks.
288
289Error handling differs from command hooks: non-2xx responses, connection failures, and timeouts all produce non-blocking errors that allow execution to continue. To block a tool call or deny a permission, return a 2xx response with a JSON body containing `decision: "block"` or a `hookSpecificOutput` with `permissionDecision: "deny"`.
290
291This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
292
293```json theme={null}
294{
295 "hooks": {
296 "PreToolUse": [
297 {
298 "matcher": "Bash",
299 "hooks": [
300 {
301 "type": "http",
302 "url": "http://localhost:8080/hooks/pre-tool-use",
303 "timeout": 30,
304 "headers": {
305 "Authorization": "Bearer $MY_TOKEN"
306 },
307 "allowedEnvVars": ["MY_TOKEN"]
308 }
309 ]
310 }
311 ]
312 }
313}
314```
315
254#### Prompt and agent hook fields316#### Prompt and agent hook fields
255 317
256In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:318In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:
260| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |322| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |
261| `model` | no | Model to use for evaluation. Defaults to a fast model |323| `model` | no | Model to use for evaluation. Defaults to a fast model |
262 324
263All matching hooks run in parallel, and identical handlers are deduplicated automatically. Handlers run in the current directory with Claude Code's environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.325All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code's environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
264 326
265### Reference scripts by path327### Reference scripts by path
266 328
348 410
349### The `/hooks` menu411### The `/hooks` menu
350 412
351Type `/hooks` in Claude Code to open the interactive hooks manager, where you can view, add, and delete hooks without editing settings files directly. For a step-by-step walkthrough, see [Set up your first hook](/en/hooks-guide#set-up-your-first-hook) in the guide.413Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook's command, prompt, or URL.
414
415The menu displays all four hook types: `command`, `prompt`, `agent`, and `http`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:
352 416
353Each hook in the menu is labeled with a bracket prefix indicating its source:417* `User`: from `~/.claude/settings.json`
418* `Project`: from `.claude/settings.json`
419* `Local`: from `.claude/settings.local.json`
420* `Plugin`: from a plugin's `hooks/hooks.json`
421* `Session`: registered in memory for the current session
422* `Built-in`: registered internally by Claude Code
354 423
355* `[User]`: from `~/.claude/settings.json`424Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.
356* `[Project]`: from `.claude/settings.json`
357* `[Local]`: from `.claude/settings.local.json`
358* `[Plugin]`: from a plugin's `hooks/hooks.json`, read-only
359 425
360### Disable or remove hooks426### Disable or remove hooks
361 427
362To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it.428To remove a hook, delete its entry from the settings JSON file.
363 429
364To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file or use the toggle in the `/hooks` menu. There is no way to disable an individual hook while keeping it in the configuration.430To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration.
365 431
366Direct edits to hooks in settings files don't take effect immediately. Claude Code captures a snapshot of hooks at startup and uses it throughout the session. This prevents malicious or accidental hook modifications from taking effect mid-session without your review. If hooks are modified externally, Claude Code warns you and requires review in the `/hooks` menu before changes apply.432The `disableAllHooks` setting respects the managed settings hierarchy. If an administrator has configured hooks through managed policy settings, `disableAllHooks` set in user, project, or local settings cannot disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks.
433
434Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
367 435
368## Hook input and output436## Hook input and output
369 437
370Hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. This section covers fields and behavior common to all events. Each event's section under [Hook events](#hook-events) includes its specific input schema and decision control options.438Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event's section under [Hook events](#hook-events) includes its specific input schema and decision control options.
371 439
372### Common input fields440### Common input fields
373 441
374All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section:442All hook events receive these fields as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.
375 443
376| Field | Description |444| Field | Description |
377| :---------------- | :--------------------------------------------------------------------------------------------------------------------------------- |445| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
378| `session_id` | Current session identifier |446| `session_id` | Current session identifier |
379| `transcript_path` | Path to conversation JSON |447| `transcript_path` | Path to conversation JSON |
380| `cwd` | Current working directory when the hook is invoked |448| `cwd` | Current working directory when the hook is invoked |
381| `permission_mode` | Current [permission mode](/en/iam#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |449| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |
382| `hook_event_name` | Name of the event that fired |450| `hook_event_name` | Name of the event that fired |
383 451
452When running with `--agent` or inside a subagent, two additional fields are included:
453
454| Field | Description |
455| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
456| `agent_id` | Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls. |
457| `agent_type` | Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent's type takes precedence over the session's `--agent` value. |
458
384For example, a `PreToolUse` hook for a Bash command receives this on stdin:459For example, a `PreToolUse` hook for a Bash command receives this on stdin:
385 460
386```json theme={null}461```json theme={null}
403 478
404The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.479The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.
405 480
406**Exit 0** means success. Claude Code parses stdout for [JSON output fields](#json-output) like `decision` or `reason`. JSON output is only processed on exit 0. For most events, stdout is only shown in verbose mode (`Ctrl+O`). The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on.481**Exit 0** means success. Claude Code parses stdout for [JSON output fields](#json-output). JSON output is only processed on exit 0. For most events, stdout is only shown in verbose mode (`Ctrl+O`). The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on.
407 482
408**Exit 2** means a blocking error. Claude Code ignores stdout and any JSON in it. Instead, stderr text is fed back to Claude as an error message. The effect depends on the event: `PreToolUse` blocks the tool call, `UserPromptSubmit` rejects the prompt, and so on. See [exit code 2 behavior](#exit-code-2-behavior-per-event) for the full list.483**Exit 2** means a blocking error. Claude Code ignores stdout and any JSON in it. Instead, stderr text is fed back to Claude as an error message. The effect depends on the event: `PreToolUse` blocks the tool call, `UserPromptSubmit` rejects the prompt, and so on. See [exit code 2 behavior](#exit-code-2-behavior-per-event) for the full list.
409 484
429Exit code 2 is the way a hook signals "stop, don't do this." The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn't happened yet) and others represent things that already happened or can't be prevented.504Exit code 2 is the way a hook signals "stop, don't do this." The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn't happened yet) and others represent things that already happened or can't be prevented.
430 505
431| Hook event | Can block? | What happens on exit 2 |506| Hook event | Can block? | What happens on exit 2 |
432| :------------------- | :--------- | :-------------------------------------------------------- |507| :------------------- | :--------- | :---------------------------------------------------------------------------- |
433| `PreToolUse` | Yes | Blocks the tool call |508| `PreToolUse` | Yes | Blocks the tool call |
434| `PermissionRequest` | Yes | Denies the permission |509| `PermissionRequest` | Yes | Denies the permission |
435| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |510| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
436| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |511| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
437| `SubagentStop` | Yes | Prevents the subagent from stopping |512| `SubagentStop` | Yes | Prevents the subagent from stopping |
513| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |
514| `TaskCompleted` | Yes | Prevents the task from being marked as completed |
515| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |
438| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |516| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
439| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |517| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
440| `Notification` | No | Shows stderr to user only |518| `Notification` | No | Shows stderr to user only |
442| `SessionStart` | No | Shows stderr to user only |520| `SessionStart` | No | Shows stderr to user only |
443| `SessionEnd` | No | Shows stderr to user only |521| `SessionEnd` | No | Shows stderr to user only |
444| `PreCompact` | No | Shows stderr to user only |522| `PreCompact` | No | Shows stderr to user only |
523| `PostCompact` | No | Shows stderr to user only |
524| `Elicitation` | Yes | Denies the elicitation |
525| `ElicitationResult` | Yes | Blocks the response (action becomes decline) |
526| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |
527| `WorktreeRemove` | No | Failures are logged in debug mode only |
528| `InstructionsLoaded` | No | Exit code is ignored |
529
530### HTTP response handling
531
532HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:
533
534* **2xx with an empty body**: success, equivalent to exit code 0 with no output
535* **2xx with a plain text body**: success, the text is added as context
536* **2xx with a JSON body**: success, parsed using the same [JSON output](#json-output) schema as command hooks
537* **Non-2xx status**: non-blocking error, execution continues
538* **Connection failure or timeout**: non-blocking error, execution continues
539
540Unlike command hooks, HTTP hooks cannot signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.
445 541
446### JSON output542### JSON output
447 543
448You must choose one approach per hook, not both: either use exit codes alone for signaling, or exit 0 and print JSON for structured control. Claude Code only processes JSON on exit 0. If you exit 2, any JSON is ignored.544Exit codes let you allow or block, but JSON output gives you finer-grained control. Instead of exiting with code 2 to block, exit 0 and print a JSON object to stdout. Claude Code reads specific fields from that JSON to control behavior, including [decision control](#decision-control) for blocking, allowing, or escalating to the user.
449 545
450Instead of relying on exit codes alone, hooks can print JSON to stdout on exit 0. Claude Code reads specific fields from this JSON to decide what to do next.546<Note>
547 You must choose one approach per hook, not both: either use exit codes alone for signaling, or exit 0 and print JSON for structured control. Claude Code only processes JSON on exit 0. If you exit 2, any JSON is ignored.
548</Note>
451 549
452Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide.550Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide.
453 551
454The JSON object has two parts:552The JSON object supports three kinds of fields:
455 553
456* **Top-level fields** like `continue` and `decision` work across all events. These are listed in the table below.554* **Universal fields** like `continue` work across all events. These are listed in the table below.
457* **`hookSpecificOutput`** is a nested object for event-specific fields like `permissionDecision` or `additionalContext`. It requires a `hookEventName` field set to the event name, like `"PreToolUse"` or `"Stop"`. Each event's decision control section under [Hook events](#hook-events) documents what fields go here.555* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.
556* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.
458 557
459| Field | Default | Description |558| Field | Default | Description |
460| :--------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------- |559| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |
461| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over event-specific fields like `decision` or `permissionDecision` |560| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |
462| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |561| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |
463| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |562| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |
464| `systemMessage` | none | Warning message shown to the user |563| `systemMessage` | none | Warning message shown to the user |
465 564
466This example uses a top-level field to stop Claude:565To stop Claude entirely regardless of event type:
467 566
468```json theme={null}567```json theme={null}
469{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }568{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
470```569```
471 570
472This example uses `hookSpecificOutput` to deny a PreToolUse tool call:571#### Decision control
473 572
474```json theme={null}573Not every event supports blocking or controlling behavior through JSON. The events that do each use a different set of fields to express that decision. Use this table as a quick reference before writing a hook:
475{574
575| Events | Decision pattern | Key fields |
576| :------------------------------------------------------------------------------------ | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
577| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |
578| TeammateIdle, TaskCompleted | Exit code or `continue: false` | Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior |
579| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |
580| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |
581| WorktreeCreate | stdout path | Hook prints absolute path to created worktree. Non-zero exit fails creation |
582| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |
583| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |
584| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded | None | No decision control. Used for side effects like logging or cleanup |
585
586Here are examples of each pattern in action:
587
588<Tabs>
589 <Tab title="Top-level decision">
590 Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, and `ConfigChange`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
591
592 ```json theme={null}
593 {
594 "decision": "block",
595 "reason": "Test suite must pass before proceeding"
596 }
597 ```
598 </Tab>
599
600 <Tab title="PreToolUse">
601 Uses `hookSpecificOutput` for richer control: allow, deny, or escalate to the user. You can also modify tool input before it runs or inject additional context for Claude. See [PreToolUse decision control](#pretooluse-decision-control) for the full set of options.
602
603 ```json theme={null}
604 {
476 "hookSpecificOutput": {605 "hookSpecificOutput": {
477 "hookEventName": "PreToolUse",606 "hookEventName": "PreToolUse",
478 "permissionDecision": "deny",607 "permissionDecision": "deny",
479 "permissionDecisionReason": "Database writes are not allowed"608 "permissionDecisionReason": "Database writes are not allowed"
480 }609 }
481}610 }
482```611 ```
612 </Tab>
613
614 <Tab title="PermissionRequest">
615 Uses `hookSpecificOutput` to allow or deny a permission request on behalf of the user. When allowing, you can also modify the tool's input or apply permission rules so the user isn't prompted again. See [PermissionRequest decision control](#permissionrequest-decision-control) for the full set of options.
616
617 ```json theme={null}
618 {
619 "hookSpecificOutput": {
620 "hookEventName": "PermissionRequest",
621 "decision": {
622 "behavior": "allow",
623 "updatedInput": {
624 "command": "npm run lint"
625 }
626 }
627 }
628 }
629 ```
630 </Tab>
631</Tabs>
483 632
484For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](/en/hooks-guide#what-you-can-automate) in the guide and the [Bash command validator reference implementation](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py).633For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](/en/hooks-guide#what-you-can-automate) in the guide and the [Bash command validator reference implementation](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py).
485 634
491 640
492Runs when Claude Code starts a new session or resumes an existing session. Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables. For static context that does not require a script, use [CLAUDE.md](/en/memory) instead.641Runs when Claude Code starts a new session or resumes an existing session. Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables. For static context that does not require a script, use [CLAUDE.md](/en/memory) instead.
493 642
494SessionStart runs on every session, so keep these hooks fast.643SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported.
495 644
496The matcher value corresponds to how the session was initiated:645The matcher value corresponds to how the session was initiated:
497 646
514 "permission_mode": "default",663 "permission_mode": "default",
515 "hook_event_name": "SessionStart",664 "hook_event_name": "SessionStart",
516 "source": "startup",665 "source": "startup",
517 "model": "claude-sonnet-4-5-20250929"666 "model": "claude-sonnet-4-6"
518}667}
519```668```
520 669
578 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.727 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.
579</Note>728</Note>
580 729
730### InstructionsLoaded
731
732Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes.
733
734InstructionsLoaded does not support matchers and fires on every load occurrence.
735
736#### InstructionsLoaded input
737
738In addition to the [common input fields](#common-input-fields), InstructionsLoaded hooks receive these fields:
739
740| Field | Description |
741| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
742| `file_path` | Absolute path to the instruction file that was loaded |
743| `memory_type` | Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"` |
744| `load_reason` | Why the file was loaded: `"session_start"`, `"nested_traversal"`, `"path_glob_match"`, `"include"`, or `"compact"`. The `"compact"` value fires when instruction files are re-loaded after a compaction event |
745| `globs` | Path glob patterns from the file's `paths:` frontmatter, if any. Present only for `path_glob_match` loads |
746| `trigger_file_path` | Path to the file whose access triggered this load, for lazy loads |
747| `parent_file_path` | Path to the parent instruction file that included this one, for `include` loads |
748
749```json theme={null}
750{
751 "session_id": "abc123",
752 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
753 "cwd": "/Users/my-project",
754 "permission_mode": "default",
755 "hook_event_name": "InstructionsLoaded",
756 "file_path": "/Users/my-project/CLAUDE.md",
757 "memory_type": "Project",
758 "load_reason": "session_start"
759}
760```
761
762#### InstructionsLoaded decision control
763
764InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
765
581### UserPromptSubmit766### UserPromptSubmit
582 767
583Runs when the user submits a prompt, before Claude processes it. This allows you768Runs when the user submits a prompt, before Claude processes it. This allows you
636 821
637### PreToolUse822### PreToolUse
638 823
639Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Task`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).824Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).
640 825
641Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.826Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.
642 827
726| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |911| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |
727| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |912| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |
728 913
729##### Task914##### Agent
730 915
731Spawns a [subagent](/en/sub-agents).916Spawns a [subagent](/en/sub-agents).
732 917
739 924
740#### PreToolUse decision control925#### PreToolUse decision control
741 926
742`PreToolUse` hooks can control whether a tool call proceeds. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return a `hookSpecificOutput` object with these event-specific fields:927`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: three outcomes (allow, deny, or ask) plus the ability to modify tool input before execution.
743 928
744| Field | Description |929| Field | Description |
745| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |930| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
746| `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm |931| `permissionDecision` | `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. [Deny and ask rules](/en/permissions#manage-permissions) still apply when a hook returns `"allow"` |
747| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |932| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |
748| `updatedInput` | Modifies the tool's input parameters before execution. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user |933| `updatedInput` | Modifies the tool's input parameters before execution. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user |
749| `additionalContext` | String added to Claude's context before the tool executes |934| `additionalContext` | String added to Claude's context before the tool executes |
750 935
936When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
937
751```json theme={null}938```json theme={null}
752{939{
753 "hookSpecificOutput": {940 "hookSpecificOutput": {
763```950```
764 951
765<Note>952<Note>
766 The `decision` and `reason` fields are deprecated for PreToolUse hooks.953 PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.
767 Use `hookSpecificOutput.permissionDecision` and
768 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields
769 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.
770</Note>954</Note>
771 955
772### PermissionRequest956### PermissionRequest
793 "description": "Remove node_modules directory"977 "description": "Remove node_modules directory"
794 },978 },
795 "permission_suggestions": [979 "permission_suggestions": [
796 { "type": "toolAlwaysAllow", "tool": "Bash" }980 {
981 "type": "addRules",
982 "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],
983 "behavior": "allow",
984 "destination": "localSettings"
985 }
797 ]986 ]
798}987}
799```988```
803`PermissionRequest` hooks can allow or deny permission requests. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return a `decision` object with these event-specific fields:992`PermissionRequest` hooks can allow or deny permission requests. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return a `decision` object with these event-specific fields:
804 993
805| Field | Description |994| Field | Description |
806| :------------------- | :------------------------------------------------------------------------------------------------------------- |995| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
807| `behavior` | `"allow"` grants the permission, `"deny"` denies it |996| `behavior` | `"allow"` grants the permission, `"deny"` denies it |
808| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |997| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |
809| `updatedPermissions` | For `"allow"` only: applies permission rule updates, equivalent to the user selecting an "always allow" option |998| `updatedPermissions` | For `"allow"` only: array of [permission update entries](#permission-update-entries) to apply, such as adding an allow rule or changing the session permission mode |
810| `message` | For `"deny"` only: tells Claude why the permission was denied |999| `message` | For `"deny"` only: tells Claude why the permission was denied |
811| `interrupt` | For `"deny"` only: if `true`, stops Claude |1000| `interrupt` | For `"deny"` only: if `true`, stops Claude |
812 1001
824}1013}
825```1014```
826 1015
1016#### Permission update entries
1017
1018The `updatedPermissions` output field and the [`permission_suggestions` input field](#permissionrequest-input) both use the same array of entry objects. Each entry has a `type` that determines its other fields, and a `destination` that controls where the change is written.
1019
1020| `type` | Fields | Effect |
1021| :------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1022| `addRules` | `rules`, `behavior`, `destination` | Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"` |
1023| `replaceRules` | `rules`, `behavior`, `destination` | Replaces all rules of the given `behavior` at the `destination` with the provided `rules` |
1024| `removeRules` | `rules`, `behavior`, `destination` | Removes matching rules of the given `behavior` |
1025| `setMode` | `mode`, `destination` | Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan` |
1026| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |
1027| `removeDirectories` | `directories`, `destination` | Removes working directories |
1028
1029The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.
1030
1031| `destination` | Writes to |
1032| :---------------- | :---------------------------------------------- |
1033| `session` | in-memory only, discarded when the session ends |
1034| `localSettings` | `.claude/settings.local.json` |
1035| `projectSettings` | `.claude/settings.json` |
1036| `userSettings` | `~/.claude/settings.json` |
1037
1038A hook can echo one of the `permission_suggestions` it received as its own `updatedPermissions` output, which is equivalent to the user selecting that "always allow" option in the dialog.
1039
827### PostToolUse1040### PostToolUse
828 1041
829Runs immediately after a tool completes successfully.1042Runs immediately after a tool completes successfully.
984 1197
985### SubagentStart1198### SubagentStart
986 1199
987Runs when a Claude Code subagent is spawned via the Task tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).1200Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).
988 1201
989#### SubagentStart input1202#### SubagentStart input
990 1203
1023 1236
1024#### SubagentStop input1237#### SubagentStop input
1025 1238
1026In addition to the [common input fields](#common-input-fields), SubagentStop hooks receive `stop_hook_active`, `agent_id`, `agent_type`, and `agent_transcript_path`. The `agent_type` field is the value used for matcher filtering. The `transcript_path` is the main session's transcript, while `agent_transcript_path` is the subagent's own transcript stored in a nested `subagents/` folder.1239In addition to the [common input fields](#common-input-fields), SubagentStop hooks receive `stop_hook_active`, `agent_id`, `agent_type`, `agent_transcript_path`, and `last_assistant_message`. The `agent_type` field is the value used for matcher filtering. The `transcript_path` is the main session's transcript, while `agent_transcript_path` is the subagent's own transcript stored in a nested `subagents/` folder. The `last_assistant_message` field contains the text content of the subagent's final response, so hooks can access it without parsing the transcript file.
1027 1240
1028```json theme={null}1241```json theme={null}
1029{1242{
1035 "stop_hook_active": false,1248 "stop_hook_active": false,
1036 "agent_id": "def456",1249 "agent_id": "def456",
1037 "agent_type": "Explore",1250 "agent_type": "Explore",
1038 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl"1251 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
1252 "last_assistant_message": "Analysis complete. Found 3 potential issues..."
1039}1253}
1040```1254```
1041 1255
1048 1262
1049#### Stop input1263#### Stop input
1050 1264
1051In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active`. This field 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.1265In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active` and `last_assistant_message`. The `stop_hook_active` field 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. The `last_assistant_message` field contains the text content of Claude's final response, so hooks can access it without parsing the transcript file.
1052 1266
1053```json theme={null}1267```json theme={null}
1054{1268{
1057 "cwd": "/Users/...",1271 "cwd": "/Users/...",
1058 "permission_mode": "default",1272 "permission_mode": "default",
1059 "hook_event_name": "Stop",1273 "hook_event_name": "Stop",
1060 "stop_hook_active": true1274 "stop_hook_active": true,
1275 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1061}1276}
1062```1277```
1063 1278
1077}1292}
1078```1293```
1079 1294
1295### TeammateIdle
1296
1297Runs when an [agent team](/en/agent-teams) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist.
1298
1299When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
1300
1301#### TeammateIdle input
1302
1303In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
1304
1305```json theme={null}
1306{
1307 "session_id": "abc123",
1308 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1309 "cwd": "/Users/...",
1310 "permission_mode": "default",
1311 "hook_event_name": "TeammateIdle",
1312 "teammate_name": "researcher",
1313 "team_name": "my-project"
1314}
1315```
1316
1317| Field | Description |
1318| :-------------- | :-------------------------------------------- |
1319| `teammate_name` | Name of the teammate that is about to go idle |
1320| `team_name` | Name of the team |
1321
1322#### TeammateIdle decision control
1323
1324TeammateIdle hooks support two ways to control teammate behavior:
1325
1326* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.
1327* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1328
1329This example checks that a build artifact exists before allowing a teammate to go idle:
1330
1331```bash theme={null}
1332#!/bin/bash
1333
1334if [ ! -f "./dist/output.js" ]; then
1335 echo "Build artifact missing. Run the build before stopping." >&2
1336 exit 2
1337fi
1338
1339exit 0
1340```
1341
1342### TaskCompleted
1343
1344Runs when a task is being marked as completed. This fires in two situations: when any agent explicitly marks a task as completed through the TaskUpdate tool, or when an [agent team](/en/agent-teams) teammate finishes its turn with in-progress tasks. Use this to enforce completion criteria like passing tests or lint checks before a task can close.
1345
1346When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks do not support matchers and fire on every occurrence.
1347
1348#### TaskCompleted input
1349
1350In addition to the [common input fields](#common-input-fields), TaskCompleted hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.
1351
1352```json theme={null}
1353{
1354 "session_id": "abc123",
1355 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1356 "cwd": "/Users/...",
1357 "permission_mode": "default",
1358 "hook_event_name": "TaskCompleted",
1359 "task_id": "task-001",
1360 "task_subject": "Implement user authentication",
1361 "task_description": "Add login and signup endpoints",
1362 "teammate_name": "implementer",
1363 "team_name": "my-project"
1364}
1365```
1366
1367| Field | Description |
1368| :----------------- | :------------------------------------------------------ |
1369| `task_id` | Identifier of the task being completed |
1370| `task_subject` | Title of the task |
1371| `task_description` | Detailed description of the task. May be absent |
1372| `teammate_name` | Name of the teammate completing the task. May be absent |
1373| `team_name` | Name of the team. May be absent |
1374
1375#### TaskCompleted decision control
1376
1377TaskCompleted hooks support two ways to control task completion:
1378
1379* **Exit code 2**: the task is not marked as completed and the stderr message is fed back to the model as feedback.
1380* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1381
1382This example runs tests and blocks task completion if they fail:
1383
1384```bash theme={null}
1385#!/bin/bash
1386INPUT=$(cat)
1387TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
1388
1389# Run the test suite
1390if ! npm test 2>&1; then
1391 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
1392 exit 2
1393fi
1394
1395exit 0
1396```
1397
1398### ConfigChange
1399
1400Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
1401
1402ConfigChange hooks fire for changes to settings files, managed policy settings, and skill files. The `source` field in the input tells you which type of configuration changed, and the optional `file_path` field provides the path to the changed file.
1403
1404The matcher filters on the configuration source:
1405
1406| Matcher | When it fires |
1407| :----------------- | :---------------------------------------- |
1408| `user_settings` | `~/.claude/settings.json` changes |
1409| `project_settings` | `.claude/settings.json` changes |
1410| `local_settings` | `.claude/settings.local.json` changes |
1411| `policy_settings` | Managed policy settings change |
1412| `skills` | A skill file in `.claude/skills/` changes |
1413
1414This example logs all configuration changes for security auditing:
1415
1416```json theme={null}
1417{
1418 "hooks": {
1419 "ConfigChange": [
1420 {
1421 "hooks": [
1422 {
1423 "type": "command",
1424 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
1425 }
1426 ]
1427 }
1428 ]
1429 }
1430}
1431```
1432
1433#### ConfigChange input
1434
1435In addition to the [common input fields](#common-input-fields), ConfigChange hooks receive `source` and optionally `file_path`. The `source` field indicates which configuration type changed, and `file_path` provides the path to the specific file that was modified.
1436
1437```json theme={null}
1438{
1439 "session_id": "abc123",
1440 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1441 "cwd": "/Users/...",
1442 "permission_mode": "default",
1443 "hook_event_name": "ConfigChange",
1444 "source": "project_settings",
1445 "file_path": "/Users/.../my-project/.claude/settings.json"
1446}
1447```
1448
1449#### ConfigChange decision control
1450
1451ConfigChange hooks can block configuration changes from taking effect. Use exit code 2 or a JSON `decision` to prevent the change. When blocked, the new settings are not applied to the running session.
1452
1453| Field | Description |
1454| :--------- | :--------------------------------------------------------------------------------------- |
1455| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |
1456| `reason` | Explanation shown to the user when `decision` is `"block"` |
1457
1458```json theme={null}
1459{
1460 "decision": "block",
1461 "reason": "Configuration changes to project settings require admin approval"
1462}
1463```
1464
1465`policy_settings` changes cannot be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect.
1466
1467### WorktreeCreate
1468
1469When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](/en/sub-agents#choose-the-subagent-scope), Claude Code creates an isolated working copy using `git worktree`. If you configure a WorktreeCreate hook, it replaces the default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial.
1470
1471The hook must print the absolute path to the created worktree directory on stdout. Claude Code uses this path as the working directory for the isolated session.
1472
1473This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
1474
1475```json theme={null}
1476{
1477 "hooks": {
1478 "WorktreeCreate": [
1479 {
1480 "hooks": [
1481 {
1482 "type": "command",
1483 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
1484 }
1485 ]
1486 }
1487 ]
1488 }
1489}
1490```
1491
1492The hook reads the worktree `name` from the JSON input on stdin, checks out a fresh copy into a new directory, and prints the directory path. The `echo` on the last line is what Claude Code reads as the worktree path. Redirect any other output to stderr so it doesn't interfere with the path.
1493
1494#### WorktreeCreate input
1495
1496In addition to the [common input fields](#common-input-fields), WorktreeCreate hooks receive the `name` field. This is a slug identifier for the new worktree, either specified by the user or auto-generated (for example, `bold-oak-a3f2`).
1497
1498```json theme={null}
1499{
1500 "session_id": "abc123",
1501 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1502 "cwd": "/Users/...",
1503 "hook_event_name": "WorktreeCreate",
1504 "name": "feature-auth"
1505}
1506```
1507
1508#### WorktreeCreate output
1509
1510The hook must print the absolute path to the created worktree directory on stdout. If the hook fails or produces no output, worktree creation fails with an error.
1511
1512WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook's success or failure determines the outcome. Only `type: "command"` hooks are supported.
1513
1514### WorktreeRemove
1515
1516The cleanup counterpart to [WorktreeCreate](#worktreecreate). This hook fires when a worktree is being removed, either when you exit a `--worktree` session and choose to remove it, or when a subagent with `isolation: "worktree"` finishes. For git-based worktrees, Claude handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk.
1517
1518Claude Code passes the path that WorktreeCreate printed on stdout as `worktree_path` in the hook input. This example reads that path and removes the directory:
1519
1520```json theme={null}
1521{
1522 "hooks": {
1523 "WorktreeRemove": [
1524 {
1525 "hooks": [
1526 {
1527 "type": "command",
1528 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
1529 }
1530 ]
1531 }
1532 ]
1533 }
1534}
1535```
1536
1537#### WorktreeRemove input
1538
1539In addition to the [common input fields](#common-input-fields), WorktreeRemove hooks receive the `worktree_path` field, which is the absolute path to the worktree being removed.
1540
1541```json theme={null}
1542{
1543 "session_id": "abc123",
1544 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1545 "cwd": "/Users/...",
1546 "hook_event_name": "WorktreeRemove",
1547 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
1548}
1549```
1550
1551WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only. Only `type: "command"` hooks are supported.
1552
1080### PreCompact1553### PreCompact
1081 1554
1082Runs before Claude Code is about to run a compact operation.1555Runs before Claude Code is about to run a compact operation.
1104}1577}
1105```1578```
1106 1579
1580### PostCompact
1581
1582Runs after Claude Code completes a compact operation. Use this event to react to the new compacted state, for example to log the generated summary or update external state.
1583
1584The same matcher values apply as for `PreCompact`:
1585
1586| Matcher | When it fires |
1587| :------- | :------------------------------------------------- |
1588| `manual` | After `/compact` |
1589| `auto` | After auto-compact when the context window is full |
1590
1591#### PostCompact input
1592
1593In addition to the [common input fields](#common-input-fields), PostCompact hooks receive `trigger` and `compact_summary`. The `compact_summary` field contains the conversation summary generated by the compact operation.
1594
1595```json theme={null}
1596{
1597 "session_id": "abc123",
1598 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1599 "cwd": "/Users/...",
1600 "permission_mode": "default",
1601 "hook_event_name": "PostCompact",
1602 "trigger": "manual",
1603 "compact_summary": "Summary of the compacted conversation..."
1604}
1605```
1606
1607PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
1608
1107### SessionEnd1609### SessionEnd
1108 1610
1109Runs when a Claude Code session ends. Useful for cleanup tasks, logging session1611Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
1136 1638
1137SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.1639SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
1138 1640
1641SessionEnd hooks have a default timeout of 1.5 seconds. This applies to both session exit and `/clear`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.
1642
1643```bash theme={null}
1644CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
1645```
1646
1647### Elicitation
1648
1649Runs when an MCP server requests user input mid-task. By default, Claude Code shows an interactive dialog for the user to respond. Hooks can intercept this request and respond programmatically, skipping the dialog entirely.
1650
1651The matcher field matches against the MCP server name.
1652
1653#### Elicitation input
1654
1655In addition to the [common input fields](#common-input-fields), Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields.
1656
1657For form-mode elicitation (the most common case):
1658
1659```json theme={null}
1660{
1661 "session_id": "abc123",
1662 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1663 "cwd": "/Users/...",
1664 "permission_mode": "default",
1665 "hook_event_name": "Elicitation",
1666 "mcp_server_name": "my-mcp-server",
1667 "message": "Please provide your credentials",
1668 "mode": "form",
1669 "requested_schema": {
1670 "type": "object",
1671 "properties": {
1672 "username": { "type": "string", "title": "Username" }
1673 }
1674 }
1675}
1676```
1677
1678For URL-mode elicitation (browser-based authentication):
1679
1680```json theme={null}
1681{
1682 "session_id": "abc123",
1683 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1684 "cwd": "/Users/...",
1685 "permission_mode": "default",
1686 "hook_event_name": "Elicitation",
1687 "mcp_server_name": "my-mcp-server",
1688 "message": "Please authenticate",
1689 "mode": "url",
1690 "url": "https://auth.example.com/login"
1691}
1692```
1693
1694#### Elicitation output
1695
1696To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
1697
1698```json theme={null}
1699{
1700 "hookSpecificOutput": {
1701 "hookEventName": "Elicitation",
1702 "action": "accept",
1703 "content": {
1704 "username": "alice"
1705 }
1706 }
1707}
1708```
1709
1710| Field | Values | Description |
1711| :-------- | :---------------------------- | :--------------------------------------------------------------- |
1712| `action` | `accept`, `decline`, `cancel` | Whether to accept, decline, or cancel the request |
1713| `content` | object | Form field values to submit. Only used when `action` is `accept` |
1714
1715Exit code 2 denies the elicitation and shows stderr to the user.
1716
1717### ElicitationResult
1718
1719Runs after a user responds to an MCP elicitation. Hooks can observe, modify, or block the response before it is sent back to the MCP server.
1720
1721The matcher field matches against the MCP server name.
1722
1723#### ElicitationResult input
1724
1725In addition to the [common input fields](#common-input-fields), ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
1726
1727```json theme={null}
1728{
1729 "session_id": "abc123",
1730 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1731 "cwd": "/Users/...",
1732 "permission_mode": "default",
1733 "hook_event_name": "ElicitationResult",
1734 "mcp_server_name": "my-mcp-server",
1735 "action": "accept",
1736 "content": { "username": "alice" },
1737 "mode": "form",
1738 "elicitation_id": "elicit-123"
1739}
1740```
1741
1742#### ElicitationResult output
1743
1744To override the user's response, return a JSON object with `hookSpecificOutput`:
1745
1746```json theme={null}
1747{
1748 "hookSpecificOutput": {
1749 "hookEventName": "ElicitationResult",
1750 "action": "decline",
1751 "content": {}
1752 }
1753}
1754```
1755
1756| Field | Values | Description |
1757| :-------- | :---------------------------- | :--------------------------------------------------------------------- |
1758| `action` | `accept`, `decline`, `cancel` | Overrides the user's action |
1759| `content` | object | Overrides form field values. Only meaningful when `action` is `accept` |
1760
1761Exit code 2 blocks the response, changing the effective action to `decline`.
1762
1139## Prompt-based hooks1763## Prompt-based hooks
1140 1764
1141In 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 work with the following events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `UserPromptSubmit`, `Stop`, and `SubagentStop`.1765In addition to command and HTTP hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type.
1766
1767Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):
1768
1769* `PermissionRequest`
1770* `PostToolUse`
1771* `PostToolUseFailure`
1772* `PreToolUse`
1773* `Stop`
1774* `SubagentStop`
1775* `TaskCompleted`
1776* `UserPromptSubmit`
1777
1778Events that only support `type: "command"` hooks:
1779
1780* `ConfigChange`
1781* `Elicitation`
1782* `ElicitationResult`
1783* `InstructionsLoaded`
1784* `Notification`
1785* `PostCompact`
1786* `PreCompact`
1787* `SessionEnd`
1788* `SessionStart`
1789* `SubagentStart`
1790* `TeammateIdle`
1791* `WorktreeCreate`
1792* `WorktreeRemove`
1142 1793
1143### How prompt-based hooks work1794### How prompt-based hooks work
1144 1795
1302 1953
1303After the background process exits, if the hook produced a JSON response with a `systemMessage` or `additionalContext` field, that content is delivered to Claude as context on the next conversation turn.1954After the background process exits, if the hook produced a JSON response with a `systemMessage` or `additionalContext` field, that content is delivered to Claude as context on the next conversation turn.
1304 1955
1956Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
1957
1305### Example: run tests after file changes1958### Example: run tests after file changes
1306 1959
1307This hook starts a test suite in the background whenever Claude writes a file, then reports the results back to Claude when the tests finish. Save this script to `.claude/hooks/run-tests-async.sh` in your project and make it executable with `chmod +x`:1960This hook starts a test suite in the background whenever Claude writes a file, then reports the results back to Claude when the tests finish. Save this script to `.claude/hooks/run-tests-async.sh` in your project and make it executable with `chmod +x`:
1365 2018
1366### Disclaimer2019### Disclaimer
1367 2020
1368Hooks run with your system user's full permissions.2021Command hooks run with your system user's full permissions.
1369 2022
1370<Warning>2023<Warning>
1371 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.2024 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.
1372</Warning>2025</Warning>
1373 2026
1374### Security best practices2027### Security best practices
1385 2038
1386Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output. Toggle verbose mode with `Ctrl+O` to see hook progress in the transcript.2039Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output. Toggle verbose mode with `Ctrl+O` to see hook progress in the transcript.
1387 2040
1388```2041```text theme={null}
1389[DEBUG] Executing hooks for PostToolUse:Write2042[DEBUG] Executing hooks for PostToolUse:Write
1390[DEBUG] Getting matching hook commands for PostToolUse with query: Write2043[DEBUG] Getting matching hook commands for PostToolUse with query: Write
1391[DEBUG] Found 1 hook matchers in settings2044[DEBUG] Found 1 hook matchers in settings