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/JCMefyZyaJwkJgv-/images/hooks-lifecycle.svg?fit=max&auto=format&n=JCMefyZyaJwkJgv-&q=85&s=f004f3fc7324fa2a4630e8d6559cf6dd" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCompleted) to Stop or StopFailure, TeammateIdle, PreCompact, PostCompact, and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, InstructionsLoaded, CwdChanged, and FileChanged 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| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |
40| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |
41| `TaskCompleted` | When a task is being marked as completed |
42| `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 |
43| `ConfigChange` | When a configuration file changes during a session |
44| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |
45| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |
46| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |
47| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |
39| `PreCompact` | Before context compaction |48| `PreCompact` | Before context compaction |
49| `PostCompact` | After context compaction completes |
50| `Elicitation` | When an MCP server requests user input during a tool call |
51| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |
40| `SessionEnd` | When a session terminates |52| `SessionEnd` | When a session terminates |
41 53
42### How a hook resolves54### How a hook resolves
84Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:96Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
85 97
86<Frame>98<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" />99 <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>100</Frame>
89 101
90<Steps>102<Steps>
134See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.146See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.
135 147
136<Note>148<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.149 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>150</Note>
139 151
140### Hook locations152### 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:169The `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 170
159| Event | What the matcher filters | Example matcher values |171| Event | What the matcher filters | Example matcher values |
160| :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------- |172| :---------------------------------------------------------------------------------------------- | :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
161| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |173| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
162| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |174| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |
163| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |175| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |
164| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |176| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |
165| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |177| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |
166| `PreCompact` | what triggered compaction | `manual`, `auto` |178| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |
167| `SubagentStop` | agent type | same values as `SubagentStart` |179| `SubagentStop` | agent type | same values as `SubagentStart` |
168| `UserPromptSubmit`, `Stop` | no matcher support | always fires on every occurrence |180| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |
181| `CwdChanged` | no matcher support | always fires on every directory change |
182| `FileChanged` | filename (basename of the changed file) | `.envrc`, `.env`, any filename you want to watch |
183| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |
184| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |
185| `Elicitation` | MCP server name | your configured MCP server names |
186| `ElicitationResult` | MCP server name | same values as `Elicitation` |
187| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |
169 188
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.189The 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 190
189}208}
190```209```
191 210
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.211`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
193 212
194#### Match MCP tools213#### Match MCP tools
195 214
237 256
238### Hook handler fields257### Hook handler fields
239 258
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:259Each 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 260
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.261* **[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.
262* **[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).263* **[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).264* **[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 265
249 269
250| Field | Required | Description |270| Field | Required | Description |
251| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |271| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
252| `type` | yes | `"command"`, `"prompt"`, or `"agent"` |272| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |
253| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |273| `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 |274| `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) |275| `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 |283| `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) |284| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |
265 285
286#### HTTP hook fields
287
288In addition to the [common fields](#common-fields), HTTP hooks accept these fields:
289
290| Field | Required | Description |
291| :--------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
292| `url` | yes | URL to send the POST request to |
293| `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 |
294| `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 |
295
296Claude 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.
297
298Error 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"`.
299
300This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
301
302```json theme={null}
303{
304 "hooks": {
305 "PreToolUse": [
306 {
307 "matcher": "Bash",
308 "hooks": [
309 {
310 "type": "http",
311 "url": "http://localhost:8080/hooks/pre-tool-use",
312 "timeout": 30,
313 "headers": {
314 "Authorization": "Bearer $MY_TOKEN"
315 },
316 "allowedEnvVars": ["MY_TOKEN"]
317 }
318 ]
319 }
320 ]
321 }
322}
323```
324
266#### Prompt and agent hook fields325#### Prompt and agent hook fields
267 326
268In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:327In 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 |331| `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 |332| `model` | no | Model to use for evaluation. Defaults to a fast model |
274 333
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.334All 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 335
277### Reference scripts by path336### Reference scripts by path
278 337
279Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:338Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
280 339
281* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.340* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.
282* `${CLAUDE_PLUGIN_ROOT}`: the plugin's root directory, for scripts bundled with a [plugin](/en/plugins).341* `${CLAUDE_PLUGIN_ROOT}`: the plugin's installation directory, for scripts bundled with a [plugin](/en/plugins). Changes on each plugin update.
342* `${CLAUDE_PLUGIN_DATA}`: the plugin's [persistent data directory](/en/plugins-reference#persistent-data-directory), for dependencies and state that should survive plugin updates.
283 343
284<Tabs>344<Tabs>
285 <Tab title="Project scripts">345 <Tab title="Project scripts">
360 420
361### The `/hooks` menu421### The `/hooks` menu
362 422
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.423Type `/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.
424
425The 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:
364 426
365Each hook in the menu is labeled with a bracket prefix indicating its source:427* `User`: from `~/.claude/settings.json`
428* `Project`: from `.claude/settings.json`
429* `Local`: from `.claude/settings.local.json`
430* `Plugin`: from a plugin's `hooks/hooks.json`
431* `Session`: registered in memory for the current session
432* `Built-in`: registered internally by Claude Code
366 433
367* `[User]`: from `~/.claude/settings.json`434Selecting 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.
368* `[Project]`: from `.claude/settings.json`
369* `[Local]`: from `.claude/settings.local.json`
370* `[Plugin]`: from a plugin's `hooks/hooks.json`, read-only
371 435
372### Disable or remove hooks436### Disable or remove hooks
373 437
374To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it.438To remove a hook, delete its entry from the settings JSON file.
439
440To 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 441
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.442The `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 443
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.444Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
379 445
380## Hook input and output446## Hook input and output
381 447
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.448Command 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 449
384### Common input fields450### Common input fields
385 451
386All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section:452Hook 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 453
388| Field | Description |454| Field | Description |
389| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |455| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
390| `session_id` | Current session identifier |456| `session_id` | Current session identifier |
391| `transcript_path` | Path to conversation JSON |457| `transcript_path` | Path to conversation JSON |
392| `cwd` | Current working directory when the hook is invoked |458| `cwd` | Current working directory when the hook is invoked |
393| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |459| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event's JSON example below to check |
394| `hook_event_name` | Name of the event that fired |460| `hook_event_name` | Name of the event that fired |
395 461
462When running with `--agent` or inside a subagent, two additional fields are included:
463
464| Field | Description |
465| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
466| `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. |
467| `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. |
468
396For example, a `PreToolUse` hook for a Bash command receives this on stdin:469For example, a `PreToolUse` hook for a Bash command receives this on stdin:
397 470
398```json theme={null}471```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.514Exit 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 515
443| Hook event | Can block? | What happens on exit 2 |516| Hook event | Can block? | What happens on exit 2 |
444| :------------------- | :--------- | :-------------------------------------------------------- |517| :------------------- | :--------- | :---------------------------------------------------------------------------- |
445| `PreToolUse` | Yes | Blocks the tool call |518| `PreToolUse` | Yes | Blocks the tool call |
446| `PermissionRequest` | Yes | Denies the permission |519| `PermissionRequest` | Yes | Denies the permission |
447| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |520| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
448| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |521| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
449| `SubagentStop` | Yes | Prevents the subagent from stopping |522| `SubagentStop` | Yes | Prevents the subagent from stopping |
523| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |
524| `TaskCompleted` | Yes | Prevents the task from being marked as completed |
525| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |
526| `StopFailure` | No | Output and exit code are ignored |
450| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |527| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
451| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |528| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
452| `Notification` | No | Shows stderr to user only |529| `Notification` | No | Shows stderr to user only |
453| `SubagentStart` | No | Shows stderr to user only |530| `SubagentStart` | No | Shows stderr to user only |
454| `SessionStart` | No | Shows stderr to user only |531| `SessionStart` | No | Shows stderr to user only |
455| `SessionEnd` | No | Shows stderr to user only |532| `SessionEnd` | No | Shows stderr to user only |
533| `CwdChanged` | No | Shows stderr to user only |
534| `FileChanged` | No | Shows stderr to user only |
456| `PreCompact` | No | Shows stderr to user only |535| `PreCompact` | No | Shows stderr to user only |
536| `PostCompact` | No | Shows stderr to user only |
537| `Elicitation` | Yes | Denies the elicitation |
538| `ElicitationResult` | Yes | Blocks the response (action becomes decline) |
539| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |
540| `WorktreeRemove` | No | Failures are logged in debug mode only |
541| `InstructionsLoaded` | No | Exit code is ignored |
542
543### HTTP response handling
544
545HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:
546
547* **2xx with an empty body**: success, equivalent to exit code 0 with no output
548* **2xx with a plain text body**: success, the text is added as context
549* **2xx with a JSON body**: success, parsed using the same [JSON output](#json-output) schema as command hooks
550* **Non-2xx status**: non-blocking error, execution continues
551* **Connection failure or timeout**: non-blocking error, execution continues
552
553Unlike 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 554
458### JSON output555### JSON output
459 556
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:586Not 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 587
491| Events | Decision pattern | Key fields |588| Events | Decision pattern | Key fields |
492| :-------------------------------------------------------------------- | :------------------- | :---------------------------------------------------------------- |589| :-------------------------------------------------------------------------------------------------------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
493| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop | Top-level `decision` | `decision: "block"`, `reason` |590| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |
591| 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` |592| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |
495| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |593| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |
594| WorktreeCreate | stdout path | Hook prints absolute path to created worktree. Non-zero exit fails creation |
595| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |
596| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |
597| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged | None | No decision control. Used for side effects like logging or cleanup |
496 598
497Here are examples of each pattern in action:599Here are examples of each pattern in action:
498 600
499<Tabs>601<Tabs>
500 <Tab title="Top-level decision">602 <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:603 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 604
503 ```json theme={null}605 ```json theme={null}
504 {606 {
551 653
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.654Runs 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 655
554SessionStart runs on every session, so keep these hooks fast.656SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported.
555 657
556The matcher value corresponds to how the session was initiated:658The matcher value corresponds to how the session was initiated:
557 659
571 "session_id": "abc123",673 "session_id": "abc123",
572 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",674 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
573 "cwd": "/Users/...",675 "cwd": "/Users/...",
574 "permission_mode": "default",
575 "hook_event_name": "SessionStart",676 "hook_event_name": "SessionStart",
576 "source": "startup",677 "source": "startup",
577 "model": "claude-sonnet-4-5-20250929"678 "model": "claude-sonnet-4-6"
578}679}
579```680```
580 681
635Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.736Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
636 737
637<Note>738<Note>
638 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.739 `CLAUDE_ENV_FILE` is available for SessionStart, [CwdChanged](#cwdchanged), and [FileChanged](#filechanged) hooks. Other hook types do not have access to this variable.
639</Note>740</Note>
640 741
742### InstructionsLoaded
743
744Fires 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.
745
746The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
747
748#### InstructionsLoaded input
749
750In addition to the [common input fields](#common-input-fields), InstructionsLoaded hooks receive these fields:
751
752| Field | Description |
753| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
754| `file_path` | Absolute path to the instruction file that was loaded |
755| `memory_type` | Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"` |
756| `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 |
757| `globs` | Path glob patterns from the file's `paths:` frontmatter, if any. Present only for `path_glob_match` loads |
758| `trigger_file_path` | Path to the file whose access triggered this load, for lazy loads |
759| `parent_file_path` | Path to the parent instruction file that included this one, for `include` loads |
760
761```json theme={null}
762{
763 "session_id": "abc123",
764 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
765 "cwd": "/Users/my-project",
766 "hook_event_name": "InstructionsLoaded",
767 "file_path": "/Users/my-project/CLAUDE.md",
768 "memory_type": "Project",
769 "load_reason": "session_start"
770}
771```
772
773#### InstructionsLoaded decision control
774
775InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
776
641### UserPromptSubmit777### UserPromptSubmit
642 778
643Runs when the user submits a prompt, before Claude processes it. This allows you779Runs when the user submits a prompt, before Claude processes it. This allows you
696 832
697### PreToolUse833### PreToolUse
698 834
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).835Runs 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 836
701Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.837Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.
702 838
786| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |922| `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 |923| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |
788 924
789##### Task925##### Agent
790 926
791Spawns a [subagent](/en/sub-agents).927Spawns a [subagent](/en/sub-agents).
792 928
802`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.938`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.
803 939
804| Field | Description |940| Field | Description |
805| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |941| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
806| `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm |942| `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"` |
807| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |943| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |
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 |944| `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 |945| `additionalContext` | String added to Claude's context before the tool executes |
810 946
947When 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.
948
811```json theme={null}949```json theme={null}
812{950{
813 "hookSpecificOutput": {951 "hookSpecificOutput": {
850 "description": "Remove node_modules directory"988 "description": "Remove node_modules directory"
851 },989 },
852 "permission_suggestions": [990 "permission_suggestions": [
853 { "type": "toolAlwaysAllow", "tool": "Bash" }991 {
992 "type": "addRules",
993 "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],
994 "behavior": "allow",
995 "destination": "localSettings"
996 }
854 ]997 ]
855}998}
856```999```
860`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:1003`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:
861 1004
862| Field | Description |1005| Field | Description |
863| :------------------- | :------------------------------------------------------------------------------------------------------------- |1006| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
864| `behavior` | `"allow"` grants the permission, `"deny"` denies it |1007| `behavior` | `"allow"` grants the permission, `"deny"` denies it |
865| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |1008| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |
866| `updatedPermissions` | For `"allow"` only: applies permission rule updates, equivalent to the user selecting an "always allow" option |1009| `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 |
867| `message` | For `"deny"` only: tells Claude why the permission was denied |1010| `message` | For `"deny"` only: tells Claude why the permission was denied |
868| `interrupt` | For `"deny"` only: if `true`, stops Claude |1011| `interrupt` | For `"deny"` only: if `true`, stops Claude |
869 1012
881}1024}
882```1025```
883 1026
1027#### Permission update entries
1028
1029The `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.
1030
1031| `type` | Fields | Effect |
1032| :------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1033| `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"` |
1034| `replaceRules` | `rules`, `behavior`, `destination` | Replaces all rules of the given `behavior` at the `destination` with the provided `rules` |
1035| `removeRules` | `rules`, `behavior`, `destination` | Removes matching rules of the given `behavior` |
1036| `setMode` | `mode`, `destination` | Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan` |
1037| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |
1038| `removeDirectories` | `directories`, `destination` | Removes working directories |
1039
1040The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.
1041
1042| `destination` | Writes to |
1043| :---------------- | :---------------------------------------------- |
1044| `session` | in-memory only, discarded when the session ends |
1045| `localSettings` | `.claude/settings.local.json` |
1046| `projectSettings` | `.claude/settings.json` |
1047| `userSettings` | `~/.claude/settings.json` |
1048
1049A 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.
1050
884### PostToolUse1051### PostToolUse
885 1052
886Runs immediately after a tool completes successfully.1053Runs immediately after a tool completes successfully.
1025 "session_id": "abc123",1192 "session_id": "abc123",
1026 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1193 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1027 "cwd": "/Users/...",1194 "cwd": "/Users/...",
1028 "permission_mode": "default",
1029 "hook_event_name": "Notification",1195 "hook_event_name": "Notification",
1030 "message": "Claude needs your permission to use Bash",1196 "message": "Claude needs your permission to use Bash",
1031 "title": "Permission needed",1197 "title": "Permission needed",
1041 1207
1042### SubagentStart1208### SubagentStart
1043 1209
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/`).1210Runs 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 1211
1046#### SubagentStart input1212#### SubagentStart input
1047 1213
1052 "session_id": "abc123",1218 "session_id": "abc123",
1053 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1219 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1054 "cwd": "/Users/...",1220 "cwd": "/Users/...",
1055 "permission_mode": "default",
1056 "hook_event_name": "SubagentStart",1221 "hook_event_name": "SubagentStart",
1057 "agent_id": "agent-abc123",1222 "agent_id": "agent-abc123",
1058 "agent_type": "Explore"1223 "agent_type": "Explore"
1080 1245
1081#### SubagentStop input1246#### SubagentStop input
1082 1247
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.1248In 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 1249
1085```json theme={null}1250```json theme={null}
1086{1251{
1092 "stop_hook_active": false,1257 "stop_hook_active": false,
1093 "agent_id": "def456",1258 "agent_id": "def456",
1094 "agent_type": "Explore",1259 "agent_type": "Explore",
1095 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl"1260 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
1261 "last_assistant_message": "Analysis complete. Found 3 potential issues..."
1096}1262}
1097```1263```
1098 1264
1101### Stop1267### Stop
1102 1268
1103Runs when the main Claude Code agent has finished responding. Does not run if1269Runs when the main Claude Code agent has finished responding. Does not run if
1104the stoppage occurred due to a user interrupt.1270the stoppage occurred due to a user interrupt. API errors fire
1271[StopFailure](#stopfailure) instead.
1105 1272
1106#### Stop input1273#### Stop input
1107 1274
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.1275In 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 1276
1110```json theme={null}1277```json theme={null}
1111{1278{
1114 "cwd": "/Users/...",1281 "cwd": "/Users/...",
1115 "permission_mode": "default",1282 "permission_mode": "default",
1116 "hook_event_name": "Stop",1283 "hook_event_name": "Stop",
1117 "stop_hook_active": true1284 "stop_hook_active": true,
1285 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1118}1286}
1119```1287```
1120 1288
1134}1302}
1135```1303```
1136 1304
1305### StopFailure
1306
1307Runs instead of [Stop](#stop) when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.
1308
1309#### StopFailure input
1310
1311In addition to the [common input fields](#common-input-fields), StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering.
1312
1313| Field | Description |
1314| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1315| `error` | Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |
1316| `error_details` | Additional details about the error, when available |
1317| `last_assistant_message` | The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude's conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"` |
1318
1319```json theme={null}
1320{
1321 "session_id": "abc123",
1322 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1323 "cwd": "/Users/...",
1324 "hook_event_name": "StopFailure",
1325 "error": "rate_limit",
1326 "error_details": "429 Too Many Requests",
1327 "last_assistant_message": "API Error: Rate limit reached"
1328}
1329```
1330
1331StopFailure hooks have no decision control. They run for notification and logging purposes only.
1332
1333### TeammateIdle
1334
1335Runs 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.
1336
1337When 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.
1338
1339#### TeammateIdle input
1340
1341In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
1342
1343```json theme={null}
1344{
1345 "session_id": "abc123",
1346 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1347 "cwd": "/Users/...",
1348 "permission_mode": "default",
1349 "hook_event_name": "TeammateIdle",
1350 "teammate_name": "researcher",
1351 "team_name": "my-project"
1352}
1353```
1354
1355| Field | Description |
1356| :-------------- | :-------------------------------------------- |
1357| `teammate_name` | Name of the teammate that is about to go idle |
1358| `team_name` | Name of the team |
1359
1360#### TeammateIdle decision control
1361
1362TeammateIdle hooks support two ways to control teammate behavior:
1363
1364* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.
1365* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1366
1367This example checks that a build artifact exists before allowing a teammate to go idle:
1368
1369```bash theme={null}
1370#!/bin/bash
1371
1372if [ ! -f "./dist/output.js" ]; then
1373 echo "Build artifact missing. Run the build before stopping." >&2
1374 exit 2
1375fi
1376
1377exit 0
1378```
1379
1380### TaskCompleted
1381
1382Runs 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.
1383
1384When 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.
1385
1386#### TaskCompleted input
1387
1388In 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`.
1389
1390```json theme={null}
1391{
1392 "session_id": "abc123",
1393 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1394 "cwd": "/Users/...",
1395 "permission_mode": "default",
1396 "hook_event_name": "TaskCompleted",
1397 "task_id": "task-001",
1398 "task_subject": "Implement user authentication",
1399 "task_description": "Add login and signup endpoints",
1400 "teammate_name": "implementer",
1401 "team_name": "my-project"
1402}
1403```
1404
1405| Field | Description |
1406| :----------------- | :------------------------------------------------------ |
1407| `task_id` | Identifier of the task being completed |
1408| `task_subject` | Title of the task |
1409| `task_description` | Detailed description of the task. May be absent |
1410| `teammate_name` | Name of the teammate completing the task. May be absent |
1411| `team_name` | Name of the team. May be absent |
1412
1413#### TaskCompleted decision control
1414
1415TaskCompleted hooks support two ways to control task completion:
1416
1417* **Exit code 2**: the task is not marked as completed and the stderr message is fed back to the model as feedback.
1418* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1419
1420This example runs tests and blocks task completion if they fail:
1421
1422```bash theme={null}
1423#!/bin/bash
1424INPUT=$(cat)
1425TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
1426
1427# Run the test suite
1428if ! npm test 2>&1; then
1429 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
1430 exit 2
1431fi
1432
1433exit 0
1434```
1435
1436### ConfigChange
1437
1438Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
1439
1440ConfigChange 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.
1441
1442The matcher filters on the configuration source:
1443
1444| Matcher | When it fires |
1445| :----------------- | :---------------------------------------- |
1446| `user_settings` | `~/.claude/settings.json` changes |
1447| `project_settings` | `.claude/settings.json` changes |
1448| `local_settings` | `.claude/settings.local.json` changes |
1449| `policy_settings` | Managed policy settings change |
1450| `skills` | A skill file in `.claude/skills/` changes |
1451
1452This example logs all configuration changes for security auditing:
1453
1454```json theme={null}
1455{
1456 "hooks": {
1457 "ConfigChange": [
1458 {
1459 "hooks": [
1460 {
1461 "type": "command",
1462 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
1463 }
1464 ]
1465 }
1466 ]
1467 }
1468}
1469```
1470
1471#### ConfigChange input
1472
1473In 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.
1474
1475```json theme={null}
1476{
1477 "session_id": "abc123",
1478 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1479 "cwd": "/Users/...",
1480 "hook_event_name": "ConfigChange",
1481 "source": "project_settings",
1482 "file_path": "/Users/.../my-project/.claude/settings.json"
1483}
1484```
1485
1486#### ConfigChange decision control
1487
1488ConfigChange 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.
1489
1490| Field | Description |
1491| :--------- | :--------------------------------------------------------------------------------------- |
1492| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |
1493| `reason` | Explanation shown to the user when `decision` is `"block"` |
1494
1495```json theme={null}
1496{
1497 "decision": "block",
1498 "reason": "Configuration changes to project settings require admin approval"
1499}
1500```
1501
1502`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.
1503
1504### CwdChanged
1505
1506Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with [FileChanged](#filechanged) for tools like [direnv](https://direnv.net/) that manage per-directory environment.
1507
1508CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.
1509
1510CwdChanged does not support matchers and fires on every directory change.
1511
1512#### CwdChanged input
1513
1514In addition to the [common input fields](#common-input-fields), CwdChanged hooks receive `old_cwd` and `new_cwd`.
1515
1516```json theme={null}
1517{
1518 "session_id": "abc123",
1519 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
1520 "cwd": "/Users/my-project/src",
1521 "hook_event_name": "CwdChanged",
1522 "old_cwd": "/Users/my-project",
1523 "new_cwd": "/Users/my-project/src"
1524}
1525```
1526
1527#### CwdChanged output
1528
1529In addition to the [JSON output fields](#json-output) available to all hooks, CwdChanged hooks can return `watchPaths` to dynamically set which file paths [FileChanged](#filechanged) watches:
1530
1531| Field | Description |
1532| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1533| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Returning an empty array clears the dynamic list, which is typical when entering a new directory |
1534
1535CwdChanged hooks have no decision control. They cannot block the directory change.
1536
1537### FileChanged
1538
1539Runs when a watched file changes on disk. The `matcher` field in your hook configuration controls which filenames to watch: it is a pipe-separated list of basenames (filenames without directory paths, for example `".envrc|.env"`). The same `matcher` value is also used to filter which hooks run when a file changes, matching against the basename of the changed file. Useful for reloading environment variables when project configuration files are modified.
1540
1541FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.
1542
1543#### FileChanged input
1544
1545In addition to the [common input fields](#common-input-fields), FileChanged hooks receive `file_path` and `event`.
1546
1547| Field | Description |
1548| :---------- | :---------------------------------------------------------------------------------------------- |
1549| `file_path` | Absolute path to the file that changed |
1550| `event` | What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted) |
1551
1552```json theme={null}
1553{
1554 "session_id": "abc123",
1555 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
1556 "cwd": "/Users/my-project",
1557 "hook_event_name": "FileChanged",
1558 "file_path": "/Users/my-project/.envrc",
1559 "event": "change"
1560}
1561```
1562
1563#### FileChanged output
1564
1565In addition to the [JSON output fields](#json-output) available to all hooks, FileChanged hooks can return `watchPaths` to dynamically update which file paths are watched:
1566
1567| Field | Description |
1568| :----------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1569| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Use this when your hook script discovers additional files to watch based on the changed file |
1570
1571FileChanged hooks have no decision control. They cannot block the file change from occurring.
1572
1573### WorktreeCreate
1574
1575When 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.
1576
1577The 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.
1578
1579This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
1580
1581```json theme={null}
1582{
1583 "hooks": {
1584 "WorktreeCreate": [
1585 {
1586 "hooks": [
1587 {
1588 "type": "command",
1589 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
1590 }
1591 ]
1592 }
1593 ]
1594 }
1595}
1596```
1597
1598The 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.
1599
1600#### WorktreeCreate input
1601
1602In 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`).
1603
1604```json theme={null}
1605{
1606 "session_id": "abc123",
1607 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1608 "cwd": "/Users/...",
1609 "hook_event_name": "WorktreeCreate",
1610 "name": "feature-auth"
1611}
1612```
1613
1614#### WorktreeCreate output
1615
1616The 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.
1617
1618WorktreeCreate 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.
1619
1620### WorktreeRemove
1621
1622The 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.
1623
1624Claude 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:
1625
1626```json theme={null}
1627{
1628 "hooks": {
1629 "WorktreeRemove": [
1630 {
1631 "hooks": [
1632 {
1633 "type": "command",
1634 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
1635 }
1636 ]
1637 }
1638 ]
1639 }
1640}
1641```
1642
1643#### WorktreeRemove input
1644
1645In 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.
1646
1647```json theme={null}
1648{
1649 "session_id": "abc123",
1650 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1651 "cwd": "/Users/...",
1652 "hook_event_name": "WorktreeRemove",
1653 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
1654}
1655```
1656
1657WorktreeRemove 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.
1658
1137### PreCompact1659### PreCompact
1138 1660
1139Runs before Claude Code is about to run a compact operation.1661Runs before Claude Code is about to run a compact operation.
1154 "session_id": "abc123",1676 "session_id": "abc123",
1155 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1677 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1156 "cwd": "/Users/...",1678 "cwd": "/Users/...",
1157 "permission_mode": "default",
1158 "hook_event_name": "PreCompact",1679 "hook_event_name": "PreCompact",
1159 "trigger": "manual",1680 "trigger": "manual",
1160 "custom_instructions": ""1681 "custom_instructions": ""
1161}1682}
1162```1683```
1163 1684
1685### PostCompact
1686
1687Runs 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.
1688
1689The same matcher values apply as for `PreCompact`:
1690
1691| Matcher | When it fires |
1692| :------- | :------------------------------------------------- |
1693| `manual` | After `/compact` |
1694| `auto` | After auto-compact when the context window is full |
1695
1696#### PostCompact input
1697
1698In 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.
1699
1700```json theme={null}
1701{
1702 "session_id": "abc123",
1703 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1704 "cwd": "/Users/...",
1705 "hook_event_name": "PostCompact",
1706 "trigger": "manual",
1707 "compact_summary": "Summary of the compacted conversation..."
1708}
1709```
1710
1711PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
1712
1164### SessionEnd1713### SessionEnd
1165 1714
1166Runs when a Claude Code session ends. Useful for cleanup tasks, logging session1715Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
1171| Reason | Description |1720| Reason | Description |
1172| :---------------------------- | :----------------------------------------- |1721| :---------------------------- | :----------------------------------------- |
1173| `clear` | Session cleared with `/clear` command |1722| `clear` | Session cleared with `/clear` command |
1723| `resume` | Session switched via interactive `/resume` |
1174| `logout` | User logged out |1724| `logout` | User logged out |
1175| `prompt_input_exit` | User exited while prompt input was visible |1725| `prompt_input_exit` | User exited while prompt input was visible |
1176| `bypass_permissions_disabled` | Bypass permissions mode was disabled |1726| `bypass_permissions_disabled` | Bypass permissions mode was disabled |
1185 "session_id": "abc123",1735 "session_id": "abc123",
1186 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1736 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1187 "cwd": "/Users/...",1737 "cwd": "/Users/...",
1188 "permission_mode": "default",
1189 "hook_event_name": "SessionEnd",1738 "hook_event_name": "SessionEnd",
1190 "reason": "other"1739 "reason": "other"
1191}1740}
1193 1742
1194SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.1743SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
1195 1744
1745SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. 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.
1746
1747```bash theme={null}
1748CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
1749```
1750
1751### Elicitation
1752
1753Runs 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.
1754
1755The matcher field matches against the MCP server name.
1756
1757#### Elicitation input
1758
1759In 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.
1760
1761For form-mode elicitation (the most common case):
1762
1763```json theme={null}
1764{
1765 "session_id": "abc123",
1766 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1767 "cwd": "/Users/...",
1768 "permission_mode": "default",
1769 "hook_event_name": "Elicitation",
1770 "mcp_server_name": "my-mcp-server",
1771 "message": "Please provide your credentials",
1772 "mode": "form",
1773 "requested_schema": {
1774 "type": "object",
1775 "properties": {
1776 "username": { "type": "string", "title": "Username" }
1777 }
1778 }
1779}
1780```
1781
1782For URL-mode elicitation (browser-based authentication):
1783
1784```json theme={null}
1785{
1786 "session_id": "abc123",
1787 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1788 "cwd": "/Users/...",
1789 "permission_mode": "default",
1790 "hook_event_name": "Elicitation",
1791 "mcp_server_name": "my-mcp-server",
1792 "message": "Please authenticate",
1793 "mode": "url",
1794 "url": "https://auth.example.com/login"
1795}
1796```
1797
1798#### Elicitation output
1799
1800To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
1801
1802```json theme={null}
1803{
1804 "hookSpecificOutput": {
1805 "hookEventName": "Elicitation",
1806 "action": "accept",
1807 "content": {
1808 "username": "alice"
1809 }
1810 }
1811}
1812```
1813
1814| Field | Values | Description |
1815| :-------- | :---------------------------- | :--------------------------------------------------------------- |
1816| `action` | `accept`, `decline`, `cancel` | Whether to accept, decline, or cancel the request |
1817| `content` | object | Form field values to submit. Only used when `action` is `accept` |
1818
1819Exit code 2 denies the elicitation and shows stderr to the user.
1820
1821### ElicitationResult
1822
1823Runs 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.
1824
1825The matcher field matches against the MCP server name.
1826
1827#### ElicitationResult input
1828
1829In addition to the [common input fields](#common-input-fields), ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
1830
1831```json theme={null}
1832{
1833 "session_id": "abc123",
1834 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1835 "cwd": "/Users/...",
1836 "permission_mode": "default",
1837 "hook_event_name": "ElicitationResult",
1838 "mcp_server_name": "my-mcp-server",
1839 "action": "accept",
1840 "content": { "username": "alice" },
1841 "mode": "form",
1842 "elicitation_id": "elicit-123"
1843}
1844```
1845
1846#### ElicitationResult output
1847
1848To override the user's response, return a JSON object with `hookSpecificOutput`:
1849
1850```json theme={null}
1851{
1852 "hookSpecificOutput": {
1853 "hookEventName": "ElicitationResult",
1854 "action": "decline",
1855 "content": {}
1856 }
1857}
1858```
1859
1860| Field | Values | Description |
1861| :-------- | :---------------------------- | :--------------------------------------------------------------------- |
1862| `action` | `accept`, `decline`, `cancel` | Overrides the user's action |
1863| `content` | object | Overrides form field values. Only meaningful when `action` is `accept` |
1864
1865Exit code 2 blocks the response, changing the effective action to `decline`.
1866
1196## Prompt-based hooks1867## Prompt-based hooks
1197 1868
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`.1869In 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.
1870
1871Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):
1872
1873* `PermissionRequest`
1874* `PostToolUse`
1875* `PostToolUseFailure`
1876* `PreToolUse`
1877* `Stop`
1878* `SubagentStop`
1879* `TaskCompleted`
1880* `UserPromptSubmit`
1881
1882Events that only support `type: "command"` hooks:
1883
1884* `ConfigChange`
1885* `CwdChanged`
1886* `Elicitation`
1887* `ElicitationResult`
1888* `FileChanged`
1889* `InstructionsLoaded`
1890* `Notification`
1891* `PostCompact`
1892* `PreCompact`
1893* `SessionEnd`
1894* `SessionStart`
1895* `StopFailure`
1896* `SubagentStart`
1897* `TeammateIdle`
1898* `WorktreeCreate`
1899* `WorktreeRemove`
1199 1900
1200### How prompt-based hooks work1901### How prompt-based hooks work
1201 1902
1359 2060
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.2061After 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 2062
2063Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
2064
1362### Example: run tests after file changes2065### Example: run tests after file changes
1363 2066
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`:2067This 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 2125
1423### Disclaimer2126### Disclaimer
1424 2127
1425Hooks run with your system user's full permissions.2128Command hooks run with your system user's full permissions.
1426 2129
1427<Warning>2130<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.2131 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>2132</Warning>
1430 2133
1431### Security best practices2134### Security best practices
1442 2145
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.2146Run `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 2147
1445```2148```text theme={null}
1446[DEBUG] Executing hooks for PostToolUse:Write2149[DEBUG] Executing hooks for PostToolUse:Write
1447[DEBUG] Getting matching hook commands for PostToolUse with query: Write2150[DEBUG] Getting matching hook commands for PostToolUse with query: Write
1448[DEBUG] Found 1 hook matchers in settings2151[DEBUG] Found 1 hook matchers in settings