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
84Now 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:
85 94
86<Frame>95<Frame>
87 <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" />
88</Frame>97</Frame>
89 98
90<Steps>99<Steps>
134See [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.
135 144
136<Note>145<Note>
137 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.
138</Note>147</Note>
139 148
140### Hook locations149### Hook locations
157The `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:
158 167
159| Event | What the matcher filters | Example matcher values |168| Event | What the matcher filters | Example matcher values |
160| :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------- |169| :-------------------------------------------------------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |
161| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |170| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
162| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |171| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |
163| `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` |
165| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |174| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |
166| `PreCompact` | what triggered compaction | `manual`, `auto` |175| `PreCompact` | what triggered compaction | `manual`, `auto` |
167| `SubagentStop` | agent type | same values as `SubagentStart` |176| `SubagentStop` | agent type | same values as `SubagentStart` |
168| `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 |
169 179
170The 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.
171 181
189}199}
190```200```
191 201
192`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.
193 203
194#### Match MCP tools204#### Match MCP tools
195 205
237 247
238### Hook handler fields248### Hook handler fields
239 249
240Each 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:
241 251
242* **[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.
243* **[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).
244* **[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).
245 256
249 260
250| Field | Required | Description |261| Field | Required | Description |
251| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |262| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
252| `type` | yes | `"command"`, `"prompt"`, or `"agent"` |263| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |
253| `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 |
254| `statusMessage` | no | Custom spinner message displayed while the hook runs |265| `statusMessage` | no | Custom spinner message displayed while the hook runs |
255| `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) |
263| `command` | yes | Shell command to execute |274| `command` | yes | Shell command to execute |
264| `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) |
265 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
266#### Prompt and agent hook fields316#### Prompt and agent hook fields
267 317
268In 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:
272| `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 |
273| `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 |
274 324
275All 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.
276 326
277### Reference scripts by path327### Reference scripts by path
278 328
360 410
361### The `/hooks` menu411### The `/hooks` menu
362 412
363Type `/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.
364 414
365Each hook in the menu is labeled with a bracket prefix indicating its source: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:
366 416
367* `[User]`: from `~/.claude/settings.json`417* `User`: from `~/.claude/settings.json`
368* `[Project]`: from `.claude/settings.json`418* `Project`: from `.claude/settings.json`
369* `[Local]`: from `.claude/settings.local.json`419* `Local`: from `.claude/settings.local.json`
370* `[Plugin]`: from a plugin's `hooks/hooks.json`, read-only420* `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
423
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.
371 425
372### Disable or remove hooks426### Disable or remove hooks
373 427
374To 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.
429
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.
375 431
376To 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.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.
377 433
378Direct 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.434Direct 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.
379 435
380## Hook input and output436## Hook input and output
381 437
382Hooks 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.
383 439
384### Common input fields440### Common input fields
385 441
386All 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.
387 443
388| Field | Description |444| Field | Description |
389| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |445| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
393| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |449| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |
394| `hook_event_name` | Name of the event that fired |450| `hook_event_name` | Name of the event that fired |
395 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
396For 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:
397 460
398```json theme={null}461```json theme={null}
441Exit 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.
442 505
443| Hook event | Can block? | What happens on exit 2 |506| Hook event | Can block? | What happens on exit 2 |
444| :------------------- | :--------- | :-------------------------------------------------------- |507| :------------------- | :--------- | :---------------------------------------------------------------------------- |
445| `PreToolUse` | Yes | Blocks the tool call |508| `PreToolUse` | Yes | Blocks the tool call |
446| `PermissionRequest` | Yes | Denies the permission |509| `PermissionRequest` | Yes | Denies the permission |
447| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |510| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
448| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |511| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
449| `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`) |
450| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |516| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
451| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |517| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
452| `Notification` | No | Shows stderr to user only |518| `Notification` | No | Shows stderr to user only |
454| `SessionStart` | No | Shows stderr to user only |520| `SessionStart` | No | Shows stderr to user only |
455| `SessionEnd` | No | Shows stderr to user only |521| `SessionEnd` | No | Shows stderr to user only |
456| `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.
457 541
458### JSON output542### JSON output
459 543
489Not 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: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:
490 574
491| Events | Decision pattern | Key fields |575| Events | Decision pattern | Key fields |
492| :-------------------------------------------------------------------- | :------------------- | :---------------------------------------------------------------- |576| :------------------------------------------------------------------------------------ | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
493| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop | Top-level `decision` | `decision: "block"`, `reason` |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 |
494| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |579| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |
495| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |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 |
496 585
497Here are examples of each pattern in action:586Here are examples of each pattern in action:
498 587
499<Tabs>588<Tabs>
500 <Tab title="Top-level decision">589 <Tab title="Top-level decision">
501 Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SubagentStop`. The only value is `"block"` — to allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all: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:
502 591
503 ```json theme={null}592 ```json theme={null}
504 {593 {
551 640
552Runs 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.
553 642
554SessionStart 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.
555 644
556The matcher value corresponds to how the session was initiated:645The matcher value corresponds to how the session was initiated:
557 646
574 "permission_mode": "default",663 "permission_mode": "default",
575 "hook_event_name": "SessionStart",664 "hook_event_name": "SessionStart",
576 "source": "startup",665 "source": "startup",
577 "model": "claude-sonnet-4-5-20250929"666 "model": "claude-sonnet-4-6"
578}667}
579```668```
580 669
638 `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.
639</Note>728</Note>
640 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"`, or `"include"` |
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
641### UserPromptSubmit766### UserPromptSubmit
642 767
643Runs 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
696 821
697### PreToolUse822### PreToolUse
698 823
699Runs 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).
700 825
701Use [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.
702 827
786| `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 |
787| `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 |
788 913
789##### Task914##### Agent
790 915
791Spawns a [subagent](/en/sub-agents).916Spawns a [subagent](/en/sub-agents).
792 917
808| `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 |
809| `additionalContext` | String added to Claude's context before the tool executes |934| `additionalContext` | String added to Claude's context before the tool executes |
810 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
811```json theme={null}938```json theme={null}
812{939{
813 "hookSpecificOutput": {940 "hookSpecificOutput": {
1041 1168
1042### SubagentStart1169### SubagentStart
1043 1170
1044Runs 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/`).1171Runs 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/`).
1045 1172
1046#### SubagentStart input1173#### SubagentStart input
1047 1174
1080 1207
1081#### SubagentStop input1208#### SubagentStop input
1082 1209
1083In 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.1210In 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.
1084 1211
1085```json theme={null}1212```json theme={null}
1086{1213{
1092 "stop_hook_active": false,1219 "stop_hook_active": false,
1093 "agent_id": "def456",1220 "agent_id": "def456",
1094 "agent_type": "Explore",1221 "agent_type": "Explore",
1095 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl"1222 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
1223 "last_assistant_message": "Analysis complete. Found 3 potential issues..."
1096}1224}
1097```1225```
1098 1226
1105 1233
1106#### Stop input1234#### Stop input
1107 1235
1108In 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.1236In 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.
1109 1237
1110```json theme={null}1238```json theme={null}
1111{1239{
1114 "cwd": "/Users/...",1242 "cwd": "/Users/...",
1115 "permission_mode": "default",1243 "permission_mode": "default",
1116 "hook_event_name": "Stop",1244 "hook_event_name": "Stop",
1117 "stop_hook_active": true1245 "stop_hook_active": true,
1246 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1118}1247}
1119```1248```
1120 1249
1134}1263}
1135```1264```
1136 1265
1266### TeammateIdle
1267
1268Runs 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.
1269
1270When 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.
1271
1272#### TeammateIdle input
1273
1274In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
1275
1276```json theme={null}
1277{
1278 "session_id": "abc123",
1279 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1280 "cwd": "/Users/...",
1281 "permission_mode": "default",
1282 "hook_event_name": "TeammateIdle",
1283 "teammate_name": "researcher",
1284 "team_name": "my-project"
1285}
1286```
1287
1288| Field | Description |
1289| :-------------- | :-------------------------------------------- |
1290| `teammate_name` | Name of the teammate that is about to go idle |
1291| `team_name` | Name of the team |
1292
1293#### TeammateIdle decision control
1294
1295TeammateIdle hooks support two ways to control teammate behavior:
1296
1297* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.
1298* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1299
1300This example checks that a build artifact exists before allowing a teammate to go idle:
1301
1302```bash theme={null}
1303#!/bin/bash
1304
1305if [ ! -f "./dist/output.js" ]; then
1306 echo "Build artifact missing. Run the build before stopping." >&2
1307 exit 2
1308fi
1309
1310exit 0
1311```
1312
1313### TaskCompleted
1314
1315Runs 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.
1316
1317When 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.
1318
1319#### TaskCompleted input
1320
1321In 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`.
1322
1323```json theme={null}
1324{
1325 "session_id": "abc123",
1326 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1327 "cwd": "/Users/...",
1328 "permission_mode": "default",
1329 "hook_event_name": "TaskCompleted",
1330 "task_id": "task-001",
1331 "task_subject": "Implement user authentication",
1332 "task_description": "Add login and signup endpoints",
1333 "teammate_name": "implementer",
1334 "team_name": "my-project"
1335}
1336```
1337
1338| Field | Description |
1339| :----------------- | :------------------------------------------------------ |
1340| `task_id` | Identifier of the task being completed |
1341| `task_subject` | Title of the task |
1342| `task_description` | Detailed description of the task. May be absent |
1343| `teammate_name` | Name of the teammate completing the task. May be absent |
1344| `team_name` | Name of the team. May be absent |
1345
1346#### TaskCompleted decision control
1347
1348TaskCompleted hooks support two ways to control task completion:
1349
1350* **Exit code 2**: the task is not marked as completed and the stderr message is fed back to the model as feedback.
1351* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1352
1353This example runs tests and blocks task completion if they fail:
1354
1355```bash theme={null}
1356#!/bin/bash
1357INPUT=$(cat)
1358TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
1359
1360# Run the test suite
1361if ! npm test 2>&1; then
1362 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
1363 exit 2
1364fi
1365
1366exit 0
1367```
1368
1369### ConfigChange
1370
1371Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
1372
1373ConfigChange 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.
1374
1375The matcher filters on the configuration source:
1376
1377| Matcher | When it fires |
1378| :----------------- | :---------------------------------------- |
1379| `user_settings` | `~/.claude/settings.json` changes |
1380| `project_settings` | `.claude/settings.json` changes |
1381| `local_settings` | `.claude/settings.local.json` changes |
1382| `policy_settings` | Managed policy settings change |
1383| `skills` | A skill file in `.claude/skills/` changes |
1384
1385This example logs all configuration changes for security auditing:
1386
1387```json theme={null}
1388{
1389 "hooks": {
1390 "ConfigChange": [
1391 {
1392 "hooks": [
1393 {
1394 "type": "command",
1395 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
1396 }
1397 ]
1398 }
1399 ]
1400 }
1401}
1402```
1403
1404#### ConfigChange input
1405
1406In 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.
1407
1408```json theme={null}
1409{
1410 "session_id": "abc123",
1411 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1412 "cwd": "/Users/...",
1413 "permission_mode": "default",
1414 "hook_event_name": "ConfigChange",
1415 "source": "project_settings",
1416 "file_path": "/Users/.../my-project/.claude/settings.json"
1417}
1418```
1419
1420#### ConfigChange decision control
1421
1422ConfigChange 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.
1423
1424| Field | Description |
1425| :--------- | :--------------------------------------------------------------------------------------- |
1426| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |
1427| `reason` | Explanation shown to the user when `decision` is `"block"` |
1428
1429```json theme={null}
1430{
1431 "decision": "block",
1432 "reason": "Configuration changes to project settings require admin approval"
1433}
1434```
1435
1436`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.
1437
1438### WorktreeCreate
1439
1440When 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.
1441
1442The 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.
1443
1444This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
1445
1446```json theme={null}
1447{
1448 "hooks": {
1449 "WorktreeCreate": [
1450 {
1451 "hooks": [
1452 {
1453 "type": "command",
1454 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
1455 }
1456 ]
1457 }
1458 ]
1459 }
1460}
1461```
1462
1463The 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.
1464
1465#### WorktreeCreate input
1466
1467In 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`).
1468
1469```json theme={null}
1470{
1471 "session_id": "abc123",
1472 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1473 "cwd": "/Users/...",
1474 "hook_event_name": "WorktreeCreate",
1475 "name": "feature-auth"
1476}
1477```
1478
1479#### WorktreeCreate output
1480
1481The 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.
1482
1483WorktreeCreate 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.
1484
1485### WorktreeRemove
1486
1487The 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.
1488
1489Claude 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:
1490
1491```json theme={null}
1492{
1493 "hooks": {
1494 "WorktreeRemove": [
1495 {
1496 "hooks": [
1497 {
1498 "type": "command",
1499 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
1500 }
1501 ]
1502 }
1503 ]
1504 }
1505}
1506```
1507
1508#### WorktreeRemove input
1509
1510In 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.
1511
1512```json theme={null}
1513{
1514 "session_id": "abc123",
1515 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1516 "cwd": "/Users/...",
1517 "hook_event_name": "WorktreeRemove",
1518 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
1519}
1520```
1521
1522WorktreeRemove 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.
1523
1137### PreCompact1524### PreCompact
1138 1525
1139Runs before Claude Code is about to run a compact operation.1526Runs before Claude Code is about to run a compact operation.
1161}1548}
1162```1549```
1163 1550
1551### PostCompact
1552
1553Runs 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.
1554
1555The same matcher values apply as for `PreCompact`:
1556
1557| Matcher | When it fires |
1558| :------- | :------------------------------------------------- |
1559| `manual` | After `/compact` |
1560| `auto` | After auto-compact when the context window is full |
1561
1562#### PostCompact input
1563
1564In 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.
1565
1566```json theme={null}
1567{
1568 "session_id": "abc123",
1569 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1570 "cwd": "/Users/...",
1571 "permission_mode": "default",
1572 "hook_event_name": "PostCompact",
1573 "trigger": "manual",
1574 "compact_summary": "Summary of the compacted conversation..."
1575}
1576```
1577
1578PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
1579
1164### SessionEnd1580### SessionEnd
1165 1581
1166Runs when a Claude Code session ends. Useful for cleanup tasks, logging session1582Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
1193 1609
1194SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.1610SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
1195 1611
1612SessionEnd 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.
1613
1614```bash theme={null}
1615CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
1616```
1617
1618### Elicitation
1619
1620Runs 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.
1621
1622The matcher field matches against the MCP server name.
1623
1624#### Elicitation input
1625
1626In 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.
1627
1628For form-mode elicitation (the most common case):
1629
1630```json theme={null}
1631{
1632 "session_id": "abc123",
1633 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1634 "cwd": "/Users/...",
1635 "permission_mode": "default",
1636 "hook_event_name": "Elicitation",
1637 "mcp_server_name": "my-mcp-server",
1638 "message": "Please provide your credentials",
1639 "mode": "form",
1640 "requested_schema": {
1641 "type": "object",
1642 "properties": {
1643 "username": { "type": "string", "title": "Username" }
1644 }
1645 }
1646}
1647```
1648
1649For URL-mode elicitation (browser-based authentication):
1650
1651```json theme={null}
1652{
1653 "session_id": "abc123",
1654 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1655 "cwd": "/Users/...",
1656 "permission_mode": "default",
1657 "hook_event_name": "Elicitation",
1658 "mcp_server_name": "my-mcp-server",
1659 "message": "Please authenticate",
1660 "mode": "url",
1661 "url": "https://auth.example.com/login"
1662}
1663```
1664
1665#### Elicitation output
1666
1667To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
1668
1669```json theme={null}
1670{
1671 "hookSpecificOutput": {
1672 "hookEventName": "Elicitation",
1673 "action": "accept",
1674 "content": {
1675 "username": "alice"
1676 }
1677 }
1678}
1679```
1680
1681| Field | Values | Description |
1682| :-------- | :---------------------------- | :--------------------------------------------------------------- |
1683| `action` | `accept`, `decline`, `cancel` | Whether to accept, decline, or cancel the request |
1684| `content` | object | Form field values to submit. Only used when `action` is `accept` |
1685
1686Exit code 2 denies the elicitation and shows stderr to the user.
1687
1688### ElicitationResult
1689
1690Runs 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.
1691
1692The matcher field matches against the MCP server name.
1693
1694#### ElicitationResult input
1695
1696In addition to the [common input fields](#common-input-fields), ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
1697
1698```json theme={null}
1699{
1700 "session_id": "abc123",
1701 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1702 "cwd": "/Users/...",
1703 "permission_mode": "default",
1704 "hook_event_name": "ElicitationResult",
1705 "mcp_server_name": "my-mcp-server",
1706 "action": "accept",
1707 "content": { "username": "alice" },
1708 "mode": "form",
1709 "elicitation_id": "elicit-123"
1710}
1711```
1712
1713#### ElicitationResult output
1714
1715To override the user's response, return a JSON object with `hookSpecificOutput`:
1716
1717```json theme={null}
1718{
1719 "hookSpecificOutput": {
1720 "hookEventName": "ElicitationResult",
1721 "action": "decline",
1722 "content": {}
1723 }
1724}
1725```
1726
1727| Field | Values | Description |
1728| :-------- | :---------------------------- | :--------------------------------------------------------------------- |
1729| `action` | `accept`, `decline`, `cancel` | Overrides the user's action |
1730| `content` | object | Overrides form field values. Only meaningful when `action` is `accept` |
1731
1732Exit code 2 blocks the response, changing the effective action to `decline`.
1733
1196## Prompt-based hooks1734## Prompt-based hooks
1197 1735
1198In 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`.1736In 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.
1737
1738Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):
1739
1740* `PermissionRequest`
1741* `PostToolUse`
1742* `PostToolUseFailure`
1743* `PreToolUse`
1744* `Stop`
1745* `SubagentStop`
1746* `TaskCompleted`
1747* `UserPromptSubmit`
1748
1749Events that only support `type: "command"` hooks:
1750
1751* `ConfigChange`
1752* `Elicitation`
1753* `ElicitationResult`
1754* `InstructionsLoaded`
1755* `Notification`
1756* `PostCompact`
1757* `PreCompact`
1758* `SessionEnd`
1759* `SessionStart`
1760* `SubagentStart`
1761* `TeammateIdle`
1762* `WorktreeCreate`
1763* `WorktreeRemove`
1199 1764
1200### How prompt-based hooks work1765### How prompt-based hooks work
1201 1766
1359 1924
1360After 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.1925After 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.
1361 1926
1927Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
1928
1362### Example: run tests after file changes1929### Example: run tests after file changes
1363 1930
1364This 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`:1931This 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`:
1422 1989
1423### Disclaimer1990### Disclaimer
1424 1991
1425Hooks run with your system user's full permissions.1992Command hooks run with your system user's full permissions.
1426 1993
1427<Warning>1994<Warning>
1428 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.1995 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.
1429</Warning>1996</Warning>
1430 1997
1431### Security best practices1998### Security best practices
1442 2009
1443Run `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.2010Run `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.
1444 2011
1445```2012```text theme={null}
1446[DEBUG] Executing hooks for PostToolUse:Write2013[DEBUG] Executing hooks for PostToolUse:Write
1447[DEBUG] Getting matching hook commands for PostToolUse with query: Write2014[DEBUG] Getting matching hook commands for PostToolUse with query: Write
1448[DEBUG] Found 1 hook matchers in settings2015[DEBUG] Found 1 hook matchers in settings