1> ## Documentation Index
2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3> Use this file to discover all available pages before exploring further.
4
1# Hooks reference5# Hooks reference
2 6
3> This page provides reference documentation for implementing hooks in Claude Code.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.
4 8
5<Tip>9<Tip>
6 For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/hooks-guide).10 For a quickstart guide with examples, see [Automate workflows with hooks](/en/hooks-guide).
7</Tip>11</Tip>
8 12
9## Configuration13Hooks 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.
10 14
11Claude Code hooks are configured in your [settings files](/en/settings):15## Hook lifecycle
12 16
13* `~/.claude/settings.json` - User settings17Hooks 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:
14* `.claude/settings.json` - Project settings18
15* `.claude/settings.local.json` - Local project settings (not committed)19<div style={{maxWidth: "500px", margin: "0 auto"}}>
16* Enterprise managed policy settings20 <Frame>
17 21 <img src="https://mintcdn.com/claude-code/2YzYcIR7V1VggfgF/images/hooks-lifecycle.svg?fit=max&auto=format&n=2YzYcIR7V1VggfgF&q=85&s=3004e6c5dc95c4fe7fa3eb40fdc4176c" 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, and InstructionsLoaded as standalone async events" width="520" height="1100" data-path="images/hooks-lifecycle.svg" />
18### Structure22 </Frame>
19 23</div>
20Hooks are organized by matchers, where each matcher can have multiple hooks: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.
26
27| Event | When it fires |
28| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |
29| `SessionStart` | When a session begins or resumes |
30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |
31| `PreToolUse` | Before a tool call executes. Can block it |
32| `PermissionRequest` | When a permission dialog appears |
33| `PostToolUse` | After a tool call succeeds |
34| `PostToolUseFailure` | After a tool call fails |
35| `Notification` | When Claude Code sends a notification |
36| `SubagentStart` | When a subagent is spawned |
37| `SubagentStop` | When a subagent finishes |
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| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |
45| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |
46| `PreCompact` | Before context compaction |
47| `PostCompact` | After context compaction completes |
48| `Elicitation` | When an MCP server requests user input during a tool call |
49| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |
50| `SessionEnd` | When a session terminates |
51
52### How a hook resolves
53
54To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The hook runs `block-rm.sh` before every Bash tool call:
21 55
22```json theme={null}56```json theme={null}
23{57{
24 "hooks": {58 "hooks": {
25 "EventName": [59 "PreToolUse": [
26 {60 {
27 "matcher": "ToolPattern",61 "matcher": "Bash",
28 "hooks": [62 "hooks": [
29 {63 {
30 "type": "command",64 "type": "command",
31 "command": "your-command-here"65 "command": ".claude/hooks/block-rm.sh"
32 }66 }
33 ]67 ]
34 }68 }
37}71}
38```72```
39 73
40* **matcher**: Pattern to match tool names, case-sensitive (only applicable for74The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:
41 `PreToolUse`, `PermissionRequest`, and `PostToolUse`)
42 * Simple strings match exactly: `Write` matches only the Write tool
43 * Supports regex: `Edit|Write` or `Notebook.*`
44 * Use `*` to match all tools. You can also use empty string (`""`) or leave
45 `matcher` blank.
46* **hooks**: Array of hooks to execute when the pattern matches
47 * `type`: Hook execution type - `"command"` for bash commands or `"prompt"` for LLM-based evaluation
48 * `command`: (For `type: "command"`) The bash command to execute (can use `$CLAUDE_PROJECT_DIR` environment variable)
49 * `prompt`: (For `type: "prompt"`) The prompt to send to the LLM for evaluation
50 * `timeout`: (Optional) How long a hook should run, in seconds, before canceling that specific hook
51
52For events like `UserPromptSubmit`, `Stop`, and `SubagentStop`
53that don't use matchers, you can omit the matcher field:
54 75
55```json theme={null}76```bash theme={null}
56{77#!/bin/bash
57 "hooks": {78# .claude/hooks/block-rm.sh
58 "UserPromptSubmit": [79COMMAND=$(jq -r '.tool_input.command')
59 {80
60 "hooks": [81if echo "$COMMAND" | grep -q 'rm -rf'; then
61 {82 jq -n '{
62 "type": "command",83 hookSpecificOutput: {
63 "command": "/path/to/prompt-validator.py"84 hookEventName: "PreToolUse",
85 permissionDecision: "deny",
86 permissionDecisionReason: "Destructive command blocked by hook"
64 }87 }
65 ]88 }'
89else
90 exit 0 # allow the command
91fi
92```
93
94Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
95
96<Frame>
97 <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" />
98</Frame>
99
100<Steps>
101 <Step title="Event fires">
102 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
103
104 ```json theme={null}
105 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
106 ```
107 </Step>
108
109 <Step title="Matcher checks">
110 The matcher `"Bash"` matches the tool name, so `block-rm.sh` runs. If you omit the matcher or use `"*"`, the hook runs on every occurrence of the event. Hooks only skip when a matcher is defined and doesn't match.
111 </Step>
112
113 <Step title="Hook handler runs">
114 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:
115
116 ```json theme={null}
117 {
118 "hookSpecificOutput": {
119 "hookEventName": "PreToolUse",
120 "permissionDecision": "deny",
121 "permissionDecisionReason": "Destructive command blocked by hook"
66 }122 }
67 ]
68 }123 }
69}124 ```
70```
71 125
72### Project-Specific Hook Scripts126 If the command had been safe (like `npm test`), the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.
127 </Step>
73 128
74You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when129 <Step title="Claude Code acts on the result">
75Claude Code spawns the hook command) to reference scripts stored in your project,130 Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.
76ensuring they work regardless of Claude's current directory:131 </Step>
132</Steps>
133
134The [Configuration](#configuration) section below documents the full schema, and each [hook event](#hook-events) section documents what input your command receives and what output it can return.
135
136## Configuration
137
138Hooks are defined in JSON settings files. The configuration has three levels of nesting:
139
1401. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop`
1412. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool"
1423. Define one or more [hook handlers](#hook-handler-fields) to run when matched
143
144See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.
145
146<Note>
147 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.
148</Note>
149
150### Hook locations
151
152Where you define a hook determines its scope:
153
154| Location | Scope | Shareable |
155| :--------------------------------------------------------- | :---------------------------- | :--------------------------------- |
156| `~/.claude/settings.json` | All your projects | No, local to your machine |
157| `.claude/settings.json` | Single project | Yes, can be committed to the repo |
158| `.claude/settings.local.json` | Single project | No, gitignored |
159| Managed policy settings | Organization-wide | Yes, admin-controlled |
160| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |
161| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |
162
163For details on settings file resolution, see [settings](/en/settings). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration).
164
165### Matcher patterns
166
167The `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:
168
169| Event | What the matcher filters | Example matcher values |
170| :---------------------------------------------------------------------------------------------- | :------------------------ | :------------------------------------------------------------------------------------------------------------------------ |
171| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
172| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |
173| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |
174| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |
175| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |
176| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |
177| `SubagentStop` | agent type | same values as `SubagentStart` |
178| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |
179| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |
180| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |
181| `Elicitation` | MCP server name | your configured MCP server names |
182| `ElicitationResult` | MCP server name | same values as `Elicitation` |
183| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |
184
185The 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.
186
187This example runs a linting script only when Claude writes or edits a file:
77 188
78```json theme={null}189```json theme={null}
79{190{
80 "hooks": {191 "hooks": {
81 "PostToolUse": [192 "PostToolUse": [
82 {193 {
83 "matcher": "Write|Edit",194 "matcher": "Edit|Write",
84 "hooks": [195 "hooks": [
85 {196 {
86 "type": "command",197 "type": "command",
87 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"198 "command": "/path/to/lint-check.sh"
88 }199 }
89 ]200 ]
90 }201 }
93}204}
94```205```
95 206
96### Plugin hooks207`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, and `WorktreeRemove` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
97 208
98[Plugins](/en/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled.209#### Match MCP tools
99 210
100**How plugin hooks work**:211[MCP](/en/mcp) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`), so you can match them the same way you match any other tool name.
101 212
102* Plugin hooks are defined in the plugin's `hooks/hooks.json` file or in a file given by a custom path to the `hooks` field.213MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
103* When a plugin is enabled, its hooks are merged with user and project hooks
104* Multiple hooks from different sources can respond to the same event
105* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files
106 214
107**Example plugin hook configuration**:215* `mcp__memory__create_entities`: Memory server's create entities tool
216* `mcp__filesystem__read_file`: Filesystem server's read file tool
217* `mcp__github__search_repositories`: GitHub server's search tool
218
219Use regex patterns to target specific MCP tools or groups of tools:
220
221* `mcp__memory__.*` matches all tools from the `memory` server
222* `mcp__.*__write.*` matches any tool containing "write" from any server
223
224This example logs all memory server operations and validates write operations from any MCP server:
108 225
109```json theme={null}226```json theme={null}
110{227{
111 "description": "Automatic code formatting",
112 "hooks": {228 "hooks": {
113 "PostToolUse": [229 "PreToolUse": [
114 {230 {
115 "matcher": "Write|Edit",231 "matcher": "mcp__memory__.*",
116 "hooks": [232 "hooks": [
117 {233 {
118 "type": "command",234 "type": "command",
119 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",235 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
120 "timeout": 30236 }
237 ]
238 },
239 {
240 "matcher": "mcp__.*__write.*",
241 "hooks": [
242 {
243 "type": "command",
244 "command": "/home/user/scripts/validate-mcp-write.py"
121 }245 }
122 ]246 ]
123 }247 }
126}250}
127```251```
128 252
129<Note>253### Hook handler fields
130 Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.
131</Note>
132 254
133<Note>255Each 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:
134 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.
135</Note>
136 256
137**Environment variables for plugins**:257* **[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.
258* **[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.
259* **[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).
260* **[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).
138 261
139* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory262#### Common fields
140* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)
141* All standard environment variables are available
142 263
143See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.264These fields apply to all hook types:
144 265
145## Prompt-Based Hooks266| Field | Required | Description |
267| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
268| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |
269| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |
270| `statusMessage` | no | Custom spinner message displayed while the hook runs |
271| `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) |
146 272
147In 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 are currently only supported for `Stop` and `SubagentStop` hooks, where they enable intelligent, context-aware decisions.273#### Command hook fields
148 274
149### How prompt-based hooks work275In addition to the [common fields](#common-fields), command hooks accept these fields:
150 276
151Instead of executing a bash command, prompt-based hooks:277| Field | Required | Description |
278| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------ |
279| `command` | yes | Shell command to execute |
280| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |
152 281
1531. Send the hook input and your prompt to a fast LLM (Haiku)282#### HTTP hook fields
1542. The LLM responds with structured JSON containing a decision283
1553. Claude Code processes the decision automatically284In addition to the [common fields](#common-fields), HTTP hooks accept these fields:
156 285
157### Configuration286| Field | Required | Description |
287| :--------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
288| `url` | yes | URL to send the POST request to |
289| `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 |
290| `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 |
291
292Claude 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.
293
294Error 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"`.
295
296This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
158 297
159```json theme={null}298```json theme={null}
160{299{
161 "hooks": {300 "hooks": {
162 "Stop": [301 "PreToolUse": [
163 {302 {
303 "matcher": "Bash",
164 "hooks": [304 "hooks": [
165 {305 {
166 "type": "prompt",306 "type": "http",
167 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."307 "url": "http://localhost:8080/hooks/pre-tool-use",
308 "timeout": 30,
309 "headers": {
310 "Authorization": "Bearer $MY_TOKEN"
311 },
312 "allowedEnvVars": ["MY_TOKEN"]
168 }313 }
169 ]314 ]
170 }315 }
173}318}
174```319```
175 320
176**Fields:**321#### Prompt and agent hook fields
177 322
178* `type`: Must be `"prompt"`323In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:
179* `prompt`: The prompt text to send to the LLM
180 * Use `$ARGUMENTS` as a placeholder for the hook input JSON
181 * If `$ARGUMENTS` is not present, input JSON is appended to the prompt
182* `timeout`: (Optional) Timeout in seconds (default: 30 seconds)
183
184### Response schema
185
186The LLM must respond with JSON containing:
187
188```json theme={null}
189{
190 "decision": "approve" | "block",
191 "reason": "Explanation for the decision",
192 "continue": false, // Optional: stops Claude entirely
193 "stopReason": "Message shown to user", // Optional: custom stop message
194 "systemMessage": "Warning or context" // Optional: shown to user
195}
196```
197 324
198**Response fields:**325| Field | Required | Description |
326| :------- | :------- | :------------------------------------------------------------------------------------------ |
327| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |
328| `model` | no | Model to use for evaluation. Defaults to a fast model |
199 329
200* `decision`: `"approve"` allows the action, `"block"` prevents it330All 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.
201* `reason`: Explanation shown to Claude when decision is `"block"`
202* `continue`: (Optional) If `false`, stops Claude's execution entirely
203* `stopReason`: (Optional) Message shown when `continue` is false
204* `systemMessage`: (Optional) Additional message shown to the user
205 331
206### Supported hook events332### Reference scripts by path
207 333
208Prompt-based hooks work with any hook event, but are most useful for:334Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
209 335
210* **Stop**: Intelligently decide if Claude should continue working336* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.
211* **SubagentStop**: Evaluate if a subagent has completed its task337* `${CLAUDE_PLUGIN_ROOT}`: the plugin's installation directory, for scripts bundled with a [plugin](/en/plugins). Changes on each plugin update.
212* **UserPromptSubmit**: Validate user prompts with LLM assistance338* `${CLAUDE_PLUGIN_DATA}`: the plugin's [persistent data directory](/en/plugins-reference#persistent-data-directory), for dependencies and state that should survive plugin updates.
213* **PreToolUse**: Make context-aware permission decisions
214* **PermissionRequest**: Intelligently allow or deny permission dialogs
215 339
216### Example: Intelligent Stop hook340<Tabs>
341 <Tab title="Project scripts">
342 This example uses `$CLAUDE_PROJECT_DIR` to run a style checker from the project's `.claude/hooks/` directory after any `Write` or `Edit` tool call:
217 343
218```json theme={null}344 ```json theme={null}
219{345 {
220 "hooks": {346 "hooks": {
221 "Stop": [347 "PostToolUse": [
222 {348 {
349 "matcher": "Write|Edit",
223 "hooks": [350 "hooks": [
224 {351 {
225 "type": "prompt",352 "type": "command",
226 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"decision\": \"approve\" or \"block\", \"reason\": \"your explanation\"}",353 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
227 "timeout": 30
228 }354 }
229 ]355 ]
230 }356 }
231 ]357 ]
232 }358 }
233}359 }
234```360 ```
361 </Tab>
235 362
236### Example: SubagentStop with custom logic363 <Tab title="Plugin scripts">
364 Define plugin hooks in `hooks/hooks.json` with an optional top-level `description` field. When a plugin is enabled, its hooks merge with your user and project hooks.
237 365
238```json theme={null}366 This example runs a formatting script bundled with the plugin:
239{367
368 ```json theme={null}
369 {
370 "description": "Automatic code formatting",
240 "hooks": {371 "hooks": {
241 "SubagentStop": [372 "PostToolUse": [
242 {373 {
374 "matcher": "Write|Edit",
243 "hooks": [375 "hooks": [
244 {376 {
245 "type": "prompt",377 "type": "command",
246 "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"378 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
379 "timeout": 30
247 }380 }
248 ]381 ]
249 }382 }
250 ]383 ]
251 }384 }
252}385 }
253```386 ```
254 387
255### Comparison with bash command hooks388 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.
389 </Tab>
390</Tabs>
256 391
257| Feature | Bash Command Hooks | Prompt-Based Hooks |392### Hooks in skills and agents
258| --------------------- | ----------------------- | ------------------------------ |
259| **Execution** | Runs bash script | Queries LLM |
260| **Decision logic** | You implement in code | LLM evaluates context |
261| **Setup complexity** | Requires script file | Just configure prompt |
262| **Context awareness** | Limited to script logic | Natural language understanding |
263| **Performance** | Fast (local execution) | Slower (API call) |
264| **Use case** | Deterministic rules | Context-aware decisions |
265 393
266### Best practices394In addition to settings files and plugins, hooks can be defined directly in [skills](/en/skills) and [subagents](/en/sub-agents) using frontmatter. These hooks are scoped to the component's lifecycle and only run when that component is active.
267 395
268* **Be specific in prompts**: Clearly state what you want the LLM to evaluate396All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes.
269* **Include decision criteria**: List the factors the LLM should consider
270* **Test your prompts**: Verify the LLM makes correct decisions for your use cases
271* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed
272* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules
273 397
274See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.398Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.
275 399
276## Hook Events400This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
277 401
278### PreToolUse402```yaml theme={null}
403---
404name: secure-operations
405description: Perform operations with security checks
406hooks:
407 PreToolUse:
408 - matcher: "Bash"
409 hooks:
410 - type: command
411 command: "./scripts/security-check.sh"
412---
413```
279 414
280Runs after Claude creates tool parameters and before processing the tool call.415Agents use the same format in their YAML frontmatter.
281 416
282**Common matchers:**417### The `/hooks` menu
283 418
284* `Task` - Subagent tasks (see [subagents documentation](/en/sub-agents))419Type `/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.
285* `Bash` - Shell commands
286* `Glob` - File pattern matching
287* `Grep` - Content search
288* `Read` - File reading
289* `Edit` - File editing
290* `Write` - File writing
291* `WebFetch`, `WebSearch` - Web operations
292 420
293Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.421The 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:
294 422
295### PermissionRequest423* `User`: from `~/.claude/settings.json`
424* `Project`: from `.claude/settings.json`
425* `Local`: from `.claude/settings.local.json`
426* `Plugin`: from a plugin's `hooks/hooks.json`
427* `Session`: registered in memory for the current session
428* `Built-in`: registered internally by Claude Code
296 429
297Runs when the user is shown a permission dialog.430Selecting 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.
298Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.
299 431
300Recognizes the same matcher values as PreToolUse.432### Disable or remove hooks
301 433
302### PostToolUse434To remove a hook, delete its entry from the settings JSON file.
303 435
304Runs immediately after a tool completes successfully.436To 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.
305 437
306Recognizes the same matcher values as PreToolUse.438The `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.
307 439
308### Notification440Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
441
442## Hook input and output
309 443
310Runs when Claude Code sends notifications. Supports matchers to filter by notification type.444Command 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.
311 445
312**Common matchers:**446### Common input fields
313 447
314* `permission_prompt` - Permission requests from Claude Code448Hook 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.
315* `idle_prompt` - When Claude is waiting for user input (after 60+ seconds of idle time)
316* `auth_success` - Authentication success notifications
317* `elicitation_dialog` - When Claude Code needs input for MCP tool elicitation
318 449
319You can use matchers to run different hooks for different notification types, or omit the matcher to run hooks for all notifications.450| Field | Description |
451| :---------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
452| `session_id` | Current session identifier |
453| `transcript_path` | Path to conversation JSON |
454| `cwd` | Current working directory when the hook is invoked |
455| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event's JSON example below to check |
456| `hook_event_name` | Name of the event that fired |
320 457
321**Example: Different notifications for different types**458When running with `--agent` or inside a subagent, two additional fields are included:
459
460| Field | Description |
461| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
462| `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. |
463| `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. |
464
465For example, a `PreToolUse` hook for a Bash command receives this on stdin:
322 466
323```json theme={null}467```json theme={null}
324{468{
325 "hooks": {469 "session_id": "abc123",
326 "Notification": [470 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
327 {471 "cwd": "/home/user/my-project",
328 "matcher": "permission_prompt",472 "permission_mode": "default",
329 "hooks": [473 "hook_event_name": "PreToolUse",
474 "tool_name": "Bash",
475 "tool_input": {
476 "command": "npm test"
477 }
478}
479```
480
481The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.
482
483### Exit code output
484
485The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.
486
487**Exit 0** means success. Claude Code parses stdout for [JSON output fields](#json-output). JSON output is only processed on exit 0. For most events, stdout is only shown in verbose mode (`Ctrl+O`). The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on.
488
489**Exit 2** means a blocking error. Claude Code ignores stdout and any JSON in it. Instead, stderr text is fed back to Claude as an error message. The effect depends on the event: `PreToolUse` blocks the tool call, `UserPromptSubmit` rejects the prompt, and so on. See [exit code 2 behavior](#exit-code-2-behavior-per-event) for the full list.
490
491**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.
492
493For example, a hook command script that blocks dangerous Bash commands:
494
495```bash theme={null}
496#!/bin/bash
497# Reads JSON input from stdin, checks the command
498command=$(jq -r '.tool_input.command' < /dev/stdin)
499
500if [[ "$command" == rm* ]]; then
501 echo "Blocked: rm commands are not allowed" >&2
502 exit 2 # Blocking error: tool call is prevented
503fi
504
505exit 0 # Success: tool call proceeds
506```
507
508#### Exit code 2 behavior per event
509
510Exit 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.
511
512| Hook event | Can block? | What happens on exit 2 |
513| :------------------- | :--------- | :---------------------------------------------------------------------------- |
514| `PreToolUse` | Yes | Blocks the tool call |
515| `PermissionRequest` | Yes | Denies the permission |
516| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
517| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
518| `SubagentStop` | Yes | Prevents the subagent from stopping |
519| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |
520| `TaskCompleted` | Yes | Prevents the task from being marked as completed |
521| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |
522| `StopFailure` | No | Output and exit code are ignored |
523| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
524| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
525| `Notification` | No | Shows stderr to user only |
526| `SubagentStart` | No | Shows stderr to user only |
527| `SessionStart` | No | Shows stderr to user only |
528| `SessionEnd` | No | Shows stderr to user only |
529| `PreCompact` | No | Shows stderr to user only |
530| `PostCompact` | No | Shows stderr to user only |
531| `Elicitation` | Yes | Denies the elicitation |
532| `ElicitationResult` | Yes | Blocks the response (action becomes decline) |
533| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |
534| `WorktreeRemove` | No | Failures are logged in debug mode only |
535| `InstructionsLoaded` | No | Exit code is ignored |
536
537### HTTP response handling
538
539HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:
540
541* **2xx with an empty body**: success, equivalent to exit code 0 with no output
542* **2xx with a plain text body**: success, the text is added as context
543* **2xx with a JSON body**: success, parsed using the same [JSON output](#json-output) schema as command hooks
544* **Non-2xx status**: non-blocking error, execution continues
545* **Connection failure or timeout**: non-blocking error, execution continues
546
547Unlike 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.
548
549### JSON output
550
551Exit codes let you allow or block, but JSON output gives you finer-grained control. Instead of exiting with code 2 to block, exit 0 and print a JSON object to stdout. Claude Code reads specific fields from that JSON to control behavior, including [decision control](#decision-control) for blocking, allowing, or escalating to the user.
552
553<Note>
554 You must choose one approach per hook, not both: either use exit codes alone for signaling, or exit 0 and print JSON for structured control. Claude Code only processes JSON on exit 0. If you exit 2, any JSON is ignored.
555</Note>
556
557Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide.
558
559The JSON object supports three kinds of fields:
560
561* **Universal fields** like `continue` work across all events. These are listed in the table below.
562* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.
563* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.
564
565| Field | Default | Description |
566| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |
567| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |
568| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |
569| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |
570| `systemMessage` | none | Warning message shown to the user |
571
572To stop Claude entirely regardless of event type:
573
574```json theme={null}
575{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
576```
577
578#### Decision control
579
580Not 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:
581
582| Events | Decision pattern | Key fields |
583| :------------------------------------------------------------------------------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
584| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |
585| 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 |
586| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |
587| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |
588| WorktreeCreate | stdout path | Hook prints absolute path to created worktree. Non-zero exit fails creation |
589| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |
590| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |
591| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure | None | No decision control. Used for side effects like logging or cleanup |
592
593Here are examples of each pattern in action:
594
595<Tabs>
596 <Tab title="Top-level decision">
597 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:
598
599 ```json theme={null}
330 {600 {
331 "type": "command",601 "decision": "block",
332 "command": "/path/to/permission-alert.sh"602 "reason": "Test suite must pass before proceeding"
333 }603 }
334 ]604 ```
335 },605 </Tab>
606
607 <Tab title="PreToolUse">
608 Uses `hookSpecificOutput` for richer control: allow, deny, or escalate to the user. You can also modify tool input before it runs or inject additional context for Claude. See [PreToolUse decision control](#pretooluse-decision-control) for the full set of options.
609
610 ```json theme={null}
336 {611 {
337 "matcher": "idle_prompt",612 "hookSpecificOutput": {
338 "hooks": [613 "hookEventName": "PreToolUse",
614 "permissionDecision": "deny",
615 "permissionDecisionReason": "Database writes are not allowed"
616 }
617 }
618 ```
619 </Tab>
620
621 <Tab title="PermissionRequest">
622 Uses `hookSpecificOutput` to allow or deny a permission request on behalf of the user. When allowing, you can also modify the tool's input or apply permission rules so the user isn't prompted again. See [PermissionRequest decision control](#permissionrequest-decision-control) for the full set of options.
623
624 ```json theme={null}
339 {625 {
340 "type": "command",626 "hookSpecificOutput": {
341 "command": "/path/to/idle-notification.sh"627 "hookEventName": "PermissionRequest",
628 "decision": {
629 "behavior": "allow",
630 "updatedInput": {
631 "command": "npm run lint"
342 }632 }
343 ]
344 }633 }
345 ]
346 }634 }
347}635 }
348```636 ```
637 </Tab>
638</Tabs>
349 639
350### UserPromptSubmit640For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](/en/hooks-guide#what-you-can-automate) in the guide and the [Bash command validator reference implementation](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py).
351 641
352Runs when the user submits a prompt, before Claude processes it. This allows you642## Hook events
353to add additional context based on the prompt/conversation, validate prompts, or
354block certain types of prompts.
355 643
356### Stop644Each event corresponds to a point in Claude Code's lifecycle where hooks can run. The sections below are ordered to match the lifecycle: from session setup through the agentic loop to session end. Each section describes when the event fires, what matchers it supports, the JSON input it receives, and how to control behavior through output.
357 645
358Runs when the main Claude Code agent has finished responding. Does not run if646### SessionStart
359the stoppage occurred due to a user interrupt.
360 647
361### SubagentStop648Runs 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.
362 649
363Runs when a Claude Code subagent (Task tool call) has finished responding.650SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported.
364 651
365### PreCompact652The matcher value corresponds to how the session was initiated:
366 653
367Runs before Claude Code is about to run a compact operation.654| Matcher | When it fires |
655| :-------- | :------------------------------------- |
656| `startup` | New session |
657| `resume` | `--resume`, `--continue`, or `/resume` |
658| `clear` | `/clear` |
659| `compact` | Auto or manual compaction |
368 660
369**Matchers:**661#### SessionStart input
370 662
371* `manual` - Invoked from `/compact`663In addition to the [common input fields](#common-input-fields), SessionStart hooks receive `source`, `model`, and optionally `agent_type`. The `source` field indicates how the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction. The `model` field contains the model identifier. If you start Claude Code with `claude --agent <name>`, an `agent_type` field contains the agent name.
372* `auto` - Invoked from auto-compact (due to full context window)
373 664
374### SessionStart665```json theme={null}
666{
667 "session_id": "abc123",
668 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
669 "cwd": "/Users/...",
670 "hook_event_name": "SessionStart",
671 "source": "startup",
672 "model": "claude-sonnet-4-6"
673}
674```
675
676#### SessionStart decision control
375 677
376Runs when Claude Code starts a new session or resumes an existing session (which678Any text your hook script prints to stdout is added as context for Claude. In addition to the [JSON output fields](#json-output) available to all hooks, you can return these event-specific fields:
377currently does start a new session under the hood). Useful for loading in
378development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables.
379 679
380**Matchers:**680| Field | Description |
681| :------------------ | :------------------------------------------------------------------------ |
682| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |
381 683
382* `startup` - Invoked from startup684```json theme={null}
383* `resume` - Invoked from `--resume`, `--continue`, or `/resume`685{
384* `clear` - Invoked from `/clear`686 "hookSpecificOutput": {
385* `compact` - Invoked from auto or manual compact.687 "hookEventName": "SessionStart",
688 "additionalContext": "My additional context here"
689 }
690}
691```
386 692
387#### Persisting environment variables693#### Persist environment variables
388 694
389SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent bash commands.695SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent Bash commands.
390 696
391**Example: Setting individual environment variables**697To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:
392 698
393```bash theme={null}699```bash theme={null}
394#!/bin/bash700#!/bin/bash
395 701
396if [ -n "$CLAUDE_ENV_FILE" ]; then702if [ -n "$CLAUDE_ENV_FILE" ]; then
397 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"703 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
398 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"704 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
399 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"705 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
400fi706fi
401 707
402exit 0708exit 0
403```709```
404 710
405**Example: Persisting all environment changes from the hook**711To capture all environment changes from setup commands, compare the exported variables before and after:
406
407When your setup modifies the environment (e.g., `nvm use`), capture and persist all changes by diffing the environment:
408 712
409```bash theme={null}713```bash theme={null}
410#!/bin/bash714#!/bin/bash
423exit 0727exit 0
424```728```
425 729
426Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session.730Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
427 731
428<Note>732<Note>
429 `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable.733 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.
430</Note>734</Note>
431 735
432### SessionEnd736### InstructionsLoaded
433 737
434Runs when a Claude Code session ends. Useful for cleanup tasks, logging session738Fires 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.
435statistics, or saving session state.
436 739
437The `reason` field in the hook input will be one of:740The 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.
438 741
439* `clear` - Session cleared with /clear command742#### InstructionsLoaded input
440* `logout` - User logged out
441* `prompt_input_exit` - User exited while prompt input was visible
442* `other` - Other exit reasons
443 743
444## Hook Input744In addition to the [common input fields](#common-input-fields), InstructionsLoaded hooks receive these fields:
445 745
446Hooks receive JSON data via stdin containing session information and746| Field | Description |
447event-specific data:747| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
748| `file_path` | Absolute path to the instruction file that was loaded |
749| `memory_type` | Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"` |
750| `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 |
751| `globs` | Path glob patterns from the file's `paths:` frontmatter, if any. Present only for `path_glob_match` loads |
752| `trigger_file_path` | Path to the file whose access triggered this load, for lazy loads |
753| `parent_file_path` | Path to the parent instruction file that included this one, for `include` loads |
448 754
449```typescript theme={null}755```json theme={null}
450{756{
451 // Common fields757 "session_id": "abc123",
452 session_id: string758 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
453 transcript_path: string // Path to conversation JSON759 "cwd": "/Users/my-project",
454 cwd: string // The current working directory when the hook is invoked760 "hook_event_name": "InstructionsLoaded",
455 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions"761 "file_path": "/Users/my-project/CLAUDE.md",
456 762 "memory_type": "Project",
457 // Event-specific fields763 "load_reason": "session_start"
458 hook_event_name: string
459 ...
460}764}
461```765```
462 766
463### PreToolUse Input767#### InstructionsLoaded decision control
768
769InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
770
771### UserPromptSubmit
772
773Runs when the user submits a prompt, before Claude processes it. This allows you
774to add additional context based on the prompt/conversation, validate prompts, or
775block certain types of prompts.
776
777#### UserPromptSubmit input
464 778
465The exact schema for `tool_input` depends on the tool.779In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
466 780
467```json theme={null}781```json theme={null}
468{782{
470 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",784 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
471 "cwd": "/Users/...",785 "cwd": "/Users/...",
472 "permission_mode": "default",786 "permission_mode": "default",
473 "hook_event_name": "PreToolUse",787 "hook_event_name": "UserPromptSubmit",
474 "tool_name": "Write",788 "prompt": "Write a function to calculate the factorial of a number"
475 "tool_input": {789}
476 "file_path": "/path/to/file.txt",790```
477 "content": "file content"791
792#### UserPromptSubmit decision control
793
794`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.
795
796There are two ways to add context to the conversation on exit code 0:
797
798* **Plain text stdout**: any non-JSON text written to stdout is added as context
799* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
800
801Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.
802
803To block a prompt, return a JSON object with `decision` set to `"block"`:
804
805| Field | Description |
806| :------------------ | :----------------------------------------------------------------------------------------------------------------- |
807| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |
808| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |
809| `additionalContext` | String added to Claude's context |
810
811```json theme={null}
812{
813 "decision": "block",
814 "reason": "Explanation for decision",
815 "hookSpecificOutput": {
816 "hookEventName": "UserPromptSubmit",
817 "additionalContext": "My additional context here"
818 }
819}
820```
821
822<Note>
823 The JSON format isn't required for simple use cases. To add context, you can print plain text to stdout with exit code 0. Use JSON when you need to
824 block prompts or want more structured control.
825</Note>
826
827### PreToolUse
828
829Runs 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).
830
831Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.
832
833#### PreToolUse input
834
835In addition to the [common input fields](#common-input-fields), PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool:
836
837##### Bash
838
839Executes shell commands.
840
841| Field | Type | Example | Description |
842| :------------------ | :------ | :----------------- | :-------------------------------------------- |
843| `command` | string | `"npm test"` | The shell command to execute |
844| `description` | string | `"Run test suite"` | Optional description of what the command does |
845| `timeout` | number | `120000` | Optional timeout in milliseconds |
846| `run_in_background` | boolean | `false` | Whether to run the command in background |
847
848##### Write
849
850Creates or overwrites a file.
851
852| Field | Type | Example | Description |
853| :---------- | :----- | :-------------------- | :--------------------------------- |
854| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |
855| `content` | string | `"file content"` | Content to write to the file |
856
857##### Edit
858
859Replaces a string in an existing file.
860
861| Field | Type | Example | Description |
862| :------------ | :------ | :-------------------- | :--------------------------------- |
863| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |
864| `old_string` | string | `"original text"` | Text to find and replace |
865| `new_string` | string | `"replacement text"` | Replacement text |
866| `replace_all` | boolean | `false` | Whether to replace all occurrences |
867
868##### Read
869
870Reads file contents.
871
872| Field | Type | Example | Description |
873| :---------- | :----- | :-------------------- | :----------------------------------------- |
874| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |
875| `offset` | number | `10` | Optional line number to start reading from |
876| `limit` | number | `50` | Optional number of lines to read |
877
878##### Glob
879
880Finds files matching a glob pattern.
881
882| Field | Type | Example | Description |
883| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |
884| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |
885| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |
886
887##### Grep
888
889Searches file contents with regular expressions.
890
891| Field | Type | Example | Description |
892| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |
893| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |
894| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |
895| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |
896| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |
897| `-i` | boolean | `true` | Case insensitive search |
898| `multiline` | boolean | `false` | Enable multiline matching |
899
900##### WebFetch
901
902Fetches and processes web content.
903
904| Field | Type | Example | Description |
905| :------- | :----- | :---------------------------- | :----------------------------------- |
906| `url` | string | `"https://example.com/api"` | URL to fetch content from |
907| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |
908
909##### WebSearch
910
911Searches the web.
912
913| Field | Type | Example | Description |
914| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |
915| `query` | string | `"react hooks best practices"` | Search query |
916| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |
917| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |
918
919##### Agent
920
921Spawns a [subagent](/en/sub-agents).
922
923| Field | Type | Example | Description |
924| :-------------- | :----- | :------------------------- | :------------------------------------------- |
925| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |
926| `description` | string | `"Find API endpoints"` | Short description of the task |
927| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |
928| `model` | string | `"sonnet"` | Optional model alias to override the default |
929
930#### PreToolUse decision control
931
932`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.
933
934| Field | Description |
935| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
936| `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"` |
937| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |
938| `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 |
939| `additionalContext` | String added to Claude's context before the tool executes |
940
941When 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.
942
943```json theme={null}
944{
945 "hookSpecificOutput": {
946 "hookEventName": "PreToolUse",
947 "permissionDecision": "allow",
948 "permissionDecisionReason": "My reason here",
949 "updatedInput": {
950 "field_to_modify": "new value"
478 },951 },
479 "tool_use_id": "toolu_01ABC123..."952 "additionalContext": "Current environment: production. Proceed with caution."
953 }
480}954}
481```955```
482 956
483### PostToolUse Input957<Note>
958 PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.
959</Note>
960
961### PermissionRequest
962
963Runs when the user is shown a permission dialog.
964Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.
484 965
485The exact schema for `tool_input` and `tool_response` depends on the tool.966Matches on tool name, same values as PreToolUse.
967
968#### PermissionRequest input
969
970PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the "always allow" options the user would normally see in the permission dialog. The difference is when the hook fires: PermissionRequest hooks run when a permission dialog is about to be shown to the user, while PreToolUse hooks run before tool execution regardless of permission status.
971
972```json theme={null}
973{
974 "session_id": "abc123",
975 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
976 "cwd": "/Users/...",
977 "permission_mode": "default",
978 "hook_event_name": "PermissionRequest",
979 "tool_name": "Bash",
980 "tool_input": {
981 "command": "rm -rf node_modules",
982 "description": "Remove node_modules directory"
983 },
984 "permission_suggestions": [
985 {
986 "type": "addRules",
987 "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],
988 "behavior": "allow",
989 "destination": "localSettings"
990 }
991 ]
992}
993```
994
995#### PermissionRequest decision control
996
997`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:
998
999| Field | Description |
1000| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1001| `behavior` | `"allow"` grants the permission, `"deny"` denies it |
1002| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |
1003| `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 |
1004| `message` | For `"deny"` only: tells Claude why the permission was denied |
1005| `interrupt` | For `"deny"` only: if `true`, stops Claude |
1006
1007```json theme={null}
1008{
1009 "hookSpecificOutput": {
1010 "hookEventName": "PermissionRequest",
1011 "decision": {
1012 "behavior": "allow",
1013 "updatedInput": {
1014 "command": "npm run lint"
1015 }
1016 }
1017 }
1018}
1019```
1020
1021#### Permission update entries
1022
1023The `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.
1024
1025| `type` | Fields | Effect |
1026| :------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1027| `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"` |
1028| `replaceRules` | `rules`, `behavior`, `destination` | Replaces all rules of the given `behavior` at the `destination` with the provided `rules` |
1029| `removeRules` | `rules`, `behavior`, `destination` | Removes matching rules of the given `behavior` |
1030| `setMode` | `mode`, `destination` | Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan` |
1031| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |
1032| `removeDirectories` | `directories`, `destination` | Removes working directories |
1033
1034The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.
1035
1036| `destination` | Writes to |
1037| :---------------- | :---------------------------------------------- |
1038| `session` | in-memory only, discarded when the session ends |
1039| `localSettings` | `.claude/settings.local.json` |
1040| `projectSettings` | `.claude/settings.json` |
1041| `userSettings` | `~/.claude/settings.json` |
1042
1043A 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.
1044
1045### PostToolUse
1046
1047Runs immediately after a tool completes successfully.
1048
1049Matches on tool name, same values as PreToolUse.
1050
1051#### PostToolUse input
1052
1053`PostToolUse` hooks fire after a tool has already executed successfully. The input includes both `tool_input`, the arguments sent to the tool, and `tool_response`, the result it returned. The exact schema for both depends on the tool.
486 1054
487```json theme={null}1055```json theme={null}
488{1056{
504}1072}
505```1073```
506 1074
507### Notification Input1075#### PostToolUse decision control
1076
1077`PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:
1078
1079| Field | Description |
1080| :--------------------- | :----------------------------------------------------------------------------------------- |
1081| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |
1082| `reason` | Explanation shown to Claude when `decision` is `"block"` |
1083| `additionalContext` | Additional context for Claude to consider |
1084| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |
1085
1086```json theme={null}
1087{
1088 "decision": "block",
1089 "reason": "Explanation for decision",
1090 "hookSpecificOutput": {
1091 "hookEventName": "PostToolUse",
1092 "additionalContext": "Additional information for Claude"
1093 }
1094}
1095```
1096
1097### PostToolUseFailure
1098
1099Runs when a tool execution fails. This event fires for tool calls that throw errors or return failure results. Use this to log failures, send alerts, or provide corrective feedback to Claude.
1100
1101Matches on tool name, same values as PreToolUse.
1102
1103#### PostToolUseFailure input
1104
1105PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:
1106
1107```json theme={null}
1108{
1109 "session_id": "abc123",
1110 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1111 "cwd": "/Users/...",
1112 "permission_mode": "default",
1113 "hook_event_name": "PostToolUseFailure",
1114 "tool_name": "Bash",
1115 "tool_input": {
1116 "command": "npm test",
1117 "description": "Run test suite"
1118 },
1119 "tool_use_id": "toolu_01ABC123...",
1120 "error": "Command exited with non-zero status code 1",
1121 "is_interrupt": false
1122}
1123```
1124
1125| Field | Description |
1126| :------------- | :------------------------------------------------------------------------------ |
1127| `error` | String describing what went wrong |
1128| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |
1129
1130#### PostToolUseFailure decision control
1131
1132`PostToolUseFailure` hooks can provide context to Claude after a tool failure. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:
1133
1134| Field | Description |
1135| :------------------ | :------------------------------------------------------------ |
1136| `additionalContext` | Additional context for Claude to consider alongside the error |
1137
1138```json theme={null}
1139{
1140 "hookSpecificOutput": {
1141 "hookEventName": "PostToolUseFailure",
1142 "additionalContext": "Additional information about the failure for Claude"
1143 }
1144}
1145```
1146
1147### Notification
1148
1149Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`. Omit the matcher to run hooks for all notification types.
1150
1151Use separate matchers to run different handlers depending on the notification type. This configuration triggers a permission-specific alert script when Claude needs permission approval and a different notification when Claude has been idle:
1152
1153```json theme={null}
1154{
1155 "hooks": {
1156 "Notification": [
1157 {
1158 "matcher": "permission_prompt",
1159 "hooks": [
1160 {
1161 "type": "command",
1162 "command": "/path/to/permission-alert.sh"
1163 }
1164 ]
1165 },
1166 {
1167 "matcher": "idle_prompt",
1168 "hooks": [
1169 {
1170 "type": "command",
1171 "command": "/path/to/idle-notification.sh"
1172 }
1173 ]
1174 }
1175 ]
1176 }
1177}
1178```
1179
1180#### Notification input
1181
1182In addition to the [common input fields](#common-input-fields), Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired.
1183
1184```json theme={null}
1185{
1186 "session_id": "abc123",
1187 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1188 "cwd": "/Users/...",
1189 "hook_event_name": "Notification",
1190 "message": "Claude needs your permission to use Bash",
1191 "title": "Permission needed",
1192 "notification_type": "permission_prompt"
1193}
1194```
1195
1196Notification hooks cannot block or modify notifications. In addition to the [JSON output fields](#json-output) available to all hooks, you can return `additionalContext` to add context to the conversation:
1197
1198| Field | Description |
1199| :------------------ | :------------------------------- |
1200| `additionalContext` | String added to Claude's context |
1201
1202### SubagentStart
1203
1204Runs 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/`).
1205
1206#### SubagentStart input
1207
1208In addition to the [common input fields](#common-input-fields), SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name (built-in agents like `"Bash"`, `"Explore"`, `"Plan"`, or custom agent names).
1209
1210```json theme={null}
1211{
1212 "session_id": "abc123",
1213 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1214 "cwd": "/Users/...",
1215 "hook_event_name": "SubagentStart",
1216 "agent_id": "agent-abc123",
1217 "agent_type": "Explore"
1218}
1219```
1220
1221SubagentStart hooks cannot block subagent creation, but they can inject context into the subagent. In addition to the [JSON output fields](#json-output) available to all hooks, you can return:
1222
1223| Field | Description |
1224| :------------------ | :------------------------------------- |
1225| `additionalContext` | String added to the subagent's context |
1226
1227```json theme={null}
1228{
1229 "hookSpecificOutput": {
1230 "hookEventName": "SubagentStart",
1231 "additionalContext": "Follow security guidelines for this task"
1232 }
1233}
1234```
1235
1236### SubagentStop
1237
1238Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.
1239
1240#### SubagentStop input
1241
1242In 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.
1243
1244```json theme={null}
1245{
1246 "session_id": "abc123",
1247 "transcript_path": "~/.claude/projects/.../abc123.jsonl",
1248 "cwd": "/Users/...",
1249 "permission_mode": "default",
1250 "hook_event_name": "SubagentStop",
1251 "stop_hook_active": false,
1252 "agent_id": "def456",
1253 "agent_type": "Explore",
1254 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
1255 "last_assistant_message": "Analysis complete. Found 3 potential issues..."
1256}
1257```
1258
1259SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).
1260
1261### Stop
1262
1263Runs when the main Claude Code agent has finished responding. Does not run if
1264the stoppage occurred due to a user interrupt. API errors fire
1265[StopFailure](#stopfailure) instead.
1266
1267#### Stop input
1268
1269In 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.
1270
1271```json theme={null}
1272{
1273 "session_id": "abc123",
1274 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1275 "cwd": "/Users/...",
1276 "permission_mode": "default",
1277 "hook_event_name": "Stop",
1278 "stop_hook_active": true,
1279 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1280}
1281```
1282
1283#### Stop decision control
1284
1285`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:
1286
1287| Field | Description |
1288| :--------- | :------------------------------------------------------------------------- |
1289| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |
1290| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |
1291
1292```json theme={null}
1293{
1294 "decision": "block",
1295 "reason": "Must be provided when Claude is blocked from stopping"
1296}
1297```
1298
1299### StopFailure
1300
1301Runs 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.
1302
1303#### StopFailure input
1304
1305In 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.
1306
1307| Field | Description |
1308| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1309| `error` | Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |
1310| `error_details` | Additional details about the error, when available |
1311| `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"` |
1312
1313```json theme={null}
1314{
1315 "session_id": "abc123",
1316 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1317 "cwd": "/Users/...",
1318 "hook_event_name": "StopFailure",
1319 "error": "rate_limit",
1320 "error_details": "429 Too Many Requests",
1321 "last_assistant_message": "API Error: Rate limit reached"
1322}
1323```
1324
1325StopFailure hooks have no decision control. They run for notification and logging purposes only.
1326
1327### TeammateIdle
1328
1329Runs 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.
1330
1331When 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.
1332
1333#### TeammateIdle input
1334
1335In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
1336
1337```json theme={null}
1338{
1339 "session_id": "abc123",
1340 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1341 "cwd": "/Users/...",
1342 "permission_mode": "default",
1343 "hook_event_name": "TeammateIdle",
1344 "teammate_name": "researcher",
1345 "team_name": "my-project"
1346}
1347```
1348
1349| Field | Description |
1350| :-------------- | :-------------------------------------------- |
1351| `teammate_name` | Name of the teammate that is about to go idle |
1352| `team_name` | Name of the team |
1353
1354#### TeammateIdle decision control
1355
1356TeammateIdle hooks support two ways to control teammate behavior:
1357
1358* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.
1359* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1360
1361This example checks that a build artifact exists before allowing a teammate to go idle:
1362
1363```bash theme={null}
1364#!/bin/bash
1365
1366if [ ! -f "./dist/output.js" ]; then
1367 echo "Build artifact missing. Run the build before stopping." >&2
1368 exit 2
1369fi
1370
1371exit 0
1372```
1373
1374### TaskCompleted
1375
1376Runs 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.
1377
1378When 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.
1379
1380#### TaskCompleted input
1381
1382In 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`.
1383
1384```json theme={null}
1385{
1386 "session_id": "abc123",
1387 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1388 "cwd": "/Users/...",
1389 "permission_mode": "default",
1390 "hook_event_name": "TaskCompleted",
1391 "task_id": "task-001",
1392 "task_subject": "Implement user authentication",
1393 "task_description": "Add login and signup endpoints",
1394 "teammate_name": "implementer",
1395 "team_name": "my-project"
1396}
1397```
1398
1399| Field | Description |
1400| :----------------- | :------------------------------------------------------ |
1401| `task_id` | Identifier of the task being completed |
1402| `task_subject` | Title of the task |
1403| `task_description` | Detailed description of the task. May be absent |
1404| `teammate_name` | Name of the teammate completing the task. May be absent |
1405| `team_name` | Name of the team. May be absent |
1406
1407#### TaskCompleted decision control
1408
1409TaskCompleted hooks support two ways to control task completion:
1410
1411* **Exit code 2**: the task is not marked as completed and the stderr message is fed back to the model as feedback.
1412* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1413
1414This example runs tests and blocks task completion if they fail:
1415
1416```bash theme={null}
1417#!/bin/bash
1418INPUT=$(cat)
1419TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
1420
1421# Run the test suite
1422if ! npm test 2>&1; then
1423 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
1424 exit 2
1425fi
1426
1427exit 0
1428```
1429
1430### ConfigChange
1431
1432Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
1433
1434ConfigChange 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.
1435
1436The matcher filters on the configuration source:
1437
1438| Matcher | When it fires |
1439| :----------------- | :---------------------------------------- |
1440| `user_settings` | `~/.claude/settings.json` changes |
1441| `project_settings` | `.claude/settings.json` changes |
1442| `local_settings` | `.claude/settings.local.json` changes |
1443| `policy_settings` | Managed policy settings change |
1444| `skills` | A skill file in `.claude/skills/` changes |
1445
1446This example logs all configuration changes for security auditing:
1447
1448```json theme={null}
1449{
1450 "hooks": {
1451 "ConfigChange": [
1452 {
1453 "hooks": [
1454 {
1455 "type": "command",
1456 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
1457 }
1458 ]
1459 }
1460 ]
1461 }
1462}
1463```
1464
1465#### ConfigChange input
1466
1467In 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.
508 1468
509```json theme={null}1469```json theme={null}
510{1470{
511 "session_id": "abc123",1471 "session_id": "abc123",
512 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1472 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
513 "cwd": "/Users/...",1473 "cwd": "/Users/...",
514 "permission_mode": "default",1474 "hook_event_name": "ConfigChange",
515 "hook_event_name": "Notification",1475 "source": "project_settings",
516 "message": "Claude needs your permission to use Bash",1476 "file_path": "/Users/.../my-project/.claude/settings.json"
517 "notification_type": "permission_prompt"
518}1477}
519```1478```
520 1479
521### UserPromptSubmit Input1480#### ConfigChange decision control
1481
1482ConfigChange 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.
1483
1484| Field | Description |
1485| :--------- | :--------------------------------------------------------------------------------------- |
1486| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |
1487| `reason` | Explanation shown to the user when `decision` is `"block"` |
522 1488
523```json theme={null}1489```json theme={null}
524{1490{
525 "session_id": "abc123",1491 "decision": "block",
526 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1492 "reason": "Configuration changes to project settings require admin approval"
527 "cwd": "/Users/...",
528 "permission_mode": "default",
529 "hook_event_name": "UserPromptSubmit",
530 "prompt": "Write a function to calculate the factorial of a number"
531}1493}
532```1494```
533 1495
534### Stop and SubagentStop Input1496`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.
1497
1498### WorktreeCreate
1499
1500When 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.
535 1501
536`stop_hook_active` is true when Claude Code is already continuing as a result of1502The 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.
537a stop hook. Check this value or process the transcript to prevent Claude Code1503
538from running indefinitely.1504This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
539 1505
540```json theme={null}1506```json theme={null}
541{1507{
542 "session_id": "abc123",1508 "hooks": {
543 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1509 "WorktreeCreate": [
544 "permission_mode": "default",1510 {
545 "hook_event_name": "Stop",1511 "hooks": [
546 "stop_hook_active": true1512 {
1513 "type": "command",
1514 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
1515 }
1516 ]
1517 }
1518 ]
1519 }
547}1520}
548```1521```
549 1522
550### PreCompact Input1523The 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.
1524
1525#### WorktreeCreate input
551 1526
552For `manual`, `custom_instructions` comes from what the user passes into1527In 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`).
553`/compact`. For `auto`, `custom_instructions` is empty.
554 1528
555```json theme={null}1529```json theme={null}
556{1530{
557 "session_id": "abc123",1531 "session_id": "abc123",
558 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1532 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
559 "permission_mode": "default",1533 "cwd": "/Users/...",
560 "hook_event_name": "PreCompact",1534 "hook_event_name": "WorktreeCreate",
561 "trigger": "manual",1535 "name": "feature-auth"
562 "custom_instructions": ""
563}1536}
564```1537```
565 1538
566### SessionStart Input1539#### WorktreeCreate output
1540
1541The 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.
1542
1543WorktreeCreate 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.
1544
1545### WorktreeRemove
1546
1547The 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.
1548
1549Claude 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:
567 1550
568```json theme={null}1551```json theme={null}
569{1552{
570 "session_id": "abc123",1553 "hooks": {
571 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1554 "WorktreeRemove": [
572 "permission_mode": "default",1555 {
573 "hook_event_name": "SessionStart",1556 "hooks": [
574 "source": "startup"1557 {
1558 "type": "command",
1559 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
1560 }
1561 ]
1562 }
1563 ]
1564 }
575}1565}
576```1566```
577 1567
578### SessionEnd Input1568#### WorktreeRemove input
1569
1570In 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.
579 1571
580```json theme={null}1572```json theme={null}
581{1573{
582 "session_id": "abc123",1574 "session_id": "abc123",
583 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1575 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
584 "cwd": "/Users/...",1576 "cwd": "/Users/...",
585 "permission_mode": "default",1577 "hook_event_name": "WorktreeRemove",
586 "hook_event_name": "SessionEnd",1578 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
587 "reason": "exit"
588}1579}
589```1580```
590 1581
591## Hook Output1582WorktreeRemove 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.
1583
1584### PreCompact
592 1585
593There are two mutually-exclusive ways for hooks to return output back to Claude Code. The output1586Runs before Claude Code is about to run a compact operation.
594communicates whether to block and any feedback that should be shown to Claude
595and the user.
596 1587
597### Simple: Exit Code1588The matcher value indicates whether compaction was triggered manually or automatically:
598 1589
599Hooks communicate status through exit codes, stdout, and stderr:1590| Matcher | When it fires |
1591| :------- | :------------------------------------------- |
1592| `manual` | `/compact` |
1593| `auto` | Auto-compact when the context window is full |
600 1594
601* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode1595#### PreCompact input
602 (ctrl+o), except for `UserPromptSubmit` and `SessionStart`, where stdout is
603 added to the context. JSON output in `stdout` is parsed for structured control
604 (see [Advanced: JSON Output](#advanced-json-output)).
605* **Exit code 2**: Blocking error. Only `stderr` is used as the error message
606 and fed back to Claude. The format is `[command]: {stderr}`. JSON in `stdout`
607 is **not** processed for exit code 2. See per-hook-event behavior below.
608* **Other exit codes**: Non-blocking error. `stderr` is shown to the user in verbose mode (ctrl+o) with
609 format `Failed with non-blocking status code: {stderr}`. If `stderr` is empty,
610 it shows `No stderr output`. Execution continues.
611 1596
612<Warning>1597In addition to the [common input fields](#common-input-fields), PreCompact hooks receive `trigger` and `custom_instructions`. For `manual`, `custom_instructions` contains what the user passes into `/compact`. For `auto`, `custom_instructions` is empty.
613 Reminder: Claude Code does not see stdout if the exit code is 0, except for
614 the `UserPromptSubmit` hook where stdout is injected as context.
615</Warning>
616 1598
617#### Exit Code 2 Behavior1599```json theme={null}
1600{
1601 "session_id": "abc123",
1602 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1603 "cwd": "/Users/...",
1604 "hook_event_name": "PreCompact",
1605 "trigger": "manual",
1606 "custom_instructions": ""
1607}
1608```
618 1609
619| Hook Event | Behavior |1610### PostCompact
620| ------------------- | ------------------------------------------------------------------ |
621| `PreToolUse` | Blocks the tool call, shows stderr to Claude |
622| `PermissionRequest` | Denies the permission, shows stderr to Claude |
623| `PostToolUse` | Shows stderr to Claude (tool already ran) |
624| `Notification` | N/A, shows stderr to user only |
625| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |
626| `Stop` | Blocks stoppage, shows stderr to Claude |
627| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |
628| `PreCompact` | N/A, shows stderr to user only |
629| `SessionStart` | N/A, shows stderr to user only |
630| `SessionEnd` | N/A, shows stderr to user only |
631 1611
632### Advanced: JSON Output1612Runs 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.
633 1613
634Hooks can return structured JSON in `stdout` for more sophisticated control.1614The same matcher values apply as for `PreCompact`:
635 1615
636<Warning>1616| Matcher | When it fires |
637 JSON output is only processed when the hook exits with code 0. If your hook1617| :------- | :------------------------------------------------- |
638 exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout`1618| `manual` | After `/compact` |
639 is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o).1619| `auto` | After auto-compact when the context window is full |
640</Warning>
641 1620
642#### Common JSON Fields1621#### PostCompact input
643 1622
644All hook types can include these optional fields:1623In 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.
645 1624
646```json theme={null}1625```json theme={null}
647{1626{
648 "continue": true, // Whether Claude should continue after hook execution (default: true)1627 "session_id": "abc123",
649 "stopReason": "string", // Message shown when continue is false1628 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
650 1629 "cwd": "/Users/...",
651 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1630 "hook_event_name": "PostCompact",
652 "systemMessage": "string" // Optional warning message shown to the user1631 "trigger": "manual",
1632 "compact_summary": "Summary of the compacted conversation..."
653}1633}
654```1634```
655 1635
656If `continue` is false, Claude stops processing after the hooks run.1636PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
657
658* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which
659 only blocks a specific tool call and provides automatic feedback to Claude.
660* For `PostToolUse`, this is different from `"decision": "block"`, which
661 provides automated feedback to Claude.
662* For `UserPromptSubmit`, this prevents the prompt from being processed.
663* For `Stop` and `SubagentStop`, this takes precedence over any
664 `"decision": "block"` output.
665* In all cases, `"continue" = false` takes precedence over any
666 `"decision": "block"` output.
667 1637
668`stopReason` accompanies `continue` with a reason shown to the user, not shown1638### SessionEnd
669to Claude.
670 1639
671#### `PreToolUse` Decision Control1640Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
1641statistics, or saving session state. Supports matchers to filter by exit reason.
672 1642
673`PreToolUse` hooks can control whether a tool call proceeds.1643The `reason` field in the hook input indicates why the session ended:
674 1644
675* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown1645| Reason | Description |
676 to the user but not to Claude.1646| :---------------------------- | :----------------------------------------- |
677* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is1647| `clear` | Session cleared with `/clear` command |
678 shown to Claude.1648| `resume` | Session switched via interactive `/resume` |
679* `"ask"` asks the user to confirm the tool call in the UI.1649| `logout` | User logged out |
680 `permissionDecisionReason` is shown to the user but not to Claude.1650| `prompt_input_exit` | User exited while prompt input was visible |
1651| `bypass_permissions_disabled` | Bypass permissions mode was disabled |
1652| `other` | Other exit reasons |
681 1653
682Additionally, hooks can modify tool inputs before execution using `updatedInput`:1654#### SessionEnd input
683 1655
684* `updatedInput` allows you to modify the tool's input parameters before the tool executes.1656In addition to the [common input fields](#common-input-fields), SessionEnd hooks receive a `reason` field indicating why the session ended. See the [reason table](#sessionend) above for all values.
685* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.
686 1657
687```json theme={null}1658```json theme={null}
688{1659{
689 "hookSpecificOutput": {1660 "session_id": "abc123",
690 "hookEventName": "PreToolUse",1661 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
691 "permissionDecision": "allow"1662 "cwd": "/Users/...",
692 "permissionDecisionReason": "My reason here",1663 "hook_event_name": "SessionEnd",
693 "updatedInput": {1664 "reason": "other"
694 "field_to_modify": "new value"
695 }
696 }
697}1665}
698```1666```
699 1667
700<Note>1668SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
701 The `decision` and `reason` fields are deprecated for PreToolUse hooks.1669
702 Use `hookSpecificOutput.permissionDecision` and1670SessionEnd 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.
703 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields1671
704 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.1672```bash theme={null}
705</Note>1673CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
1674```
1675
1676### Elicitation
1677
1678Runs 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.
1679
1680The matcher field matches against the MCP server name.
706 1681
707#### `PermissionRequest` Decision Control1682#### Elicitation input
708 1683
709`PermissionRequest` hooks can allow or deny permission requests shown to the user.1684In 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.
710 1685
711* For `"behavior": "allow"` you can also optionally pass in an `"updatedInput"` that modifies the tool's input parameters before the tool executes.1686For form-mode elicitation (the most common case):
712* For `"behavior": "deny"` you can also optionally pass in a `"message"` string that tells the model why the permission was denied, and a boolean `"interrupt"` which will stop Claude.
713 1687
714```json theme={null}1688```json theme={null}
715{1689{
716 "hookSpecificOutput": {1690 "session_id": "abc123",
717 "hookEventName": "PermissionRequest",1691 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
718 "decision": {1692 "cwd": "/Users/...",
719 "behavior": "allow",1693 "permission_mode": "default",
720 "updatedInput": {1694 "hook_event_name": "Elicitation",
721 "command": "npm run lint"1695 "mcp_server_name": "my-mcp-server",
722 }1696 "message": "Please provide your credentials",
1697 "mode": "form",
1698 "requested_schema": {
1699 "type": "object",
1700 "properties": {
1701 "username": { "type": "string", "title": "Username" }
723 }1702 }
724 }1703 }
725}1704}
726```1705```
727 1706
728#### `PostToolUse` Decision Control1707For URL-mode elicitation (browser-based authentication):
1708
1709```json theme={null}
1710{
1711 "session_id": "abc123",
1712 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1713 "cwd": "/Users/...",
1714 "permission_mode": "default",
1715 "hook_event_name": "Elicitation",
1716 "mcp_server_name": "my-mcp-server",
1717 "message": "Please authenticate",
1718 "mode": "url",
1719 "url": "https://auth.example.com/login"
1720}
1721```
729 1722
730`PostToolUse` hooks can provide feedback to Claude after tool execution.1723#### Elicitation output
731 1724
732* `"block"` automatically prompts Claude with `reason`.1725To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
733* `undefined` does nothing. `reason` is ignored.
734* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.
735 1726
736```json theme={null}1727```json theme={null}
737{1728{
738 "decision": "block" | undefined,
739 "reason": "Explanation for decision",
740 "hookSpecificOutput": {1729 "hookSpecificOutput": {
741 "hookEventName": "PostToolUse",1730 "hookEventName": "Elicitation",
742 "additionalContext": "Additional information for Claude"1731 "action": "accept",
1732 "content": {
1733 "username": "alice"
1734 }
743 }1735 }
744}1736}
745```1737```
746 1738
747#### `UserPromptSubmit` Decision Control1739| Field | Values | Description |
1740| :-------- | :---------------------------- | :--------------------------------------------------------------- |
1741| `action` | `accept`, `decline`, `cancel` | Whether to accept, decline, or cancel the request |
1742| `content` | object | Form field values to submit. Only used when `action` is `accept` |
748 1743
749`UserPromptSubmit` hooks can control whether a user prompt is processed and add context.1744Exit code 2 denies the elicitation and shows stderr to the user.
750 1745
751**Adding context (exit code 0):**1746### ElicitationResult
752There are two ways to add context to the conversation:
753 1747
7541. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added1748Runs 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.
755 as context. This is the easiest way to inject information.
756 1749
7572. **JSON with `additionalContext`** (structured): Use the JSON format below for1750The matcher field matches against the MCP server name.
758 more control. The `additionalContext` field is added as context.
759 1751
760Both methods work with exit code 0. Plain stdout is shown as hook output in1752#### ElicitationResult input
761the transcript; `additionalContext` is added more discretely.1753
1754In addition to the [common input fields](#common-input-fields), ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
1755
1756```json theme={null}
1757{
1758 "session_id": "abc123",
1759 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1760 "cwd": "/Users/...",
1761 "permission_mode": "default",
1762 "hook_event_name": "ElicitationResult",
1763 "mcp_server_name": "my-mcp-server",
1764 "action": "accept",
1765 "content": { "username": "alice" },
1766 "mode": "form",
1767 "elicitation_id": "elicit-123"
1768}
1769```
762 1770
763**Blocking prompts:**1771#### ElicitationResult output
764 1772
765* `"decision": "block"` prevents the prompt from being processed. The submitted1773To override the user's response, return a JSON object with `hookSpecificOutput`:
766 prompt is erased from context. `"reason"` is shown to the user but not added
767 to context.
768* `"decision": undefined` (or omitted) allows the prompt to proceed normally.
769 1774
770```json theme={null}1775```json theme={null}
771{1776{
772 "decision": "block" | undefined,
773 "reason": "Explanation for decision",
774 "hookSpecificOutput": {1777 "hookSpecificOutput": {
775 "hookEventName": "UserPromptSubmit",1778 "hookEventName": "ElicitationResult",
776 "additionalContext": "My additional context here"1779 "action": "decline",
1780 "content": {}
777 }1781 }
778}1782}
779```1783```
780 1784
781<Note>1785| Field | Values | Description |
782 The JSON format is not required for simple use cases. To add context, you can1786| :-------- | :---------------------------- | :--------------------------------------------------------------------- |
783 just print plain text to stdout with exit code 0. Use JSON when you need to1787| `action` | `accept`, `decline`, `cancel` | Overrides the user's action |
784 block prompts or want more structured control.1788| `content` | object | Overrides form field values. Only meaningful when `action` is `accept` |
785</Note>1789
1790Exit code 2 blocks the response, changing the effective action to `decline`.
1791
1792## Prompt-based hooks
1793
1794In 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.
1795
1796Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):
1797
1798* `PermissionRequest`
1799* `PostToolUse`
1800* `PostToolUseFailure`
1801* `PreToolUse`
1802* `Stop`
1803* `SubagentStop`
1804* `TaskCompleted`
1805* `UserPromptSubmit`
1806
1807Events that only support `type: "command"` hooks:
1808
1809* `ConfigChange`
1810* `Elicitation`
1811* `ElicitationResult`
1812* `InstructionsLoaded`
1813* `Notification`
1814* `PostCompact`
1815* `PreCompact`
1816* `SessionEnd`
1817* `SessionStart`
1818* `StopFailure`
1819* `SubagentStart`
1820* `TeammateIdle`
1821* `WorktreeCreate`
1822* `WorktreeRemove`
1823
1824### How prompt-based hooks work
1825
1826Instead of executing a Bash command, prompt-based hooks:
1827
18281. Send the hook input and your prompt to a Claude model, Haiku by default
18292. The LLM responds with structured JSON containing a decision
18303. Claude Code processes the decision automatically
786 1831
787#### `Stop`/`SubagentStop` Decision Control1832### Prompt hook configuration
788 1833
789`Stop` and `SubagentStop` hooks can control whether Claude must continue.1834Set `type` to `"prompt"` and provide a `prompt` string instead of a `command`. Use the `$ARGUMENTS` placeholder to inject the hook's JSON input data into your prompt text. Claude Code sends the combined prompt and input to a fast Claude model, which returns a JSON decision.
790 1835
791* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1836This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
792 to know how to proceed.
793* `undefined` allows Claude to stop. `reason` is ignored.
794 1837
795```json theme={null}1838```json theme={null}
796{1839{
797 "decision": "block" | undefined,1840 "hooks": {
798 "reason": "Must be provided when Claude is blocked from stopping"1841 "Stop": [
1842 {
1843 "hooks": [
1844 {
1845 "type": "prompt",
1846 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."
1847 }
1848 ]
1849 }
1850 ]
1851 }
799}1852}
800```1853```
801 1854
802#### `SessionStart` Decision Control1855| Field | Required | Description |
1856| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1857| `type` | yes | Must be `"prompt"` |
1858| `prompt` | yes | The prompt text to send to the LLM. Use `$ARGUMENTS` as a placeholder for the hook input JSON. If `$ARGUMENTS` is not present, input JSON is appended to the prompt |
1859| `model` | no | Model to use for evaluation. Defaults to a fast model |
1860| `timeout` | no | Timeout in seconds. Default: 30 |
803 1861
804`SessionStart` hooks allow you to load in context at the start of a session.1862### Response schema
805 1863
806* `"hookSpecificOutput.additionalContext"` adds the string to the context.1864The LLM must respond with JSON containing:
807* Multiple hooks' `additionalContext` values are concatenated.
808 1865
809```json theme={null}1866```json theme={null}
810{1867{
811 "hookSpecificOutput": {1868 "ok": true | false,
812 "hookEventName": "SessionStart",1869 "reason": "Explanation for the decision"
813 "additionalContext": "My additional context here"
814 }
815}1870}
816```1871```
817 1872
818#### `SessionEnd` Decision Control1873| Field | Description |
819 1874| :------- | :--------------------------------------------------------- |
820`SessionEnd` hooks run when a session ends. They cannot block session termination1875| `ok` | `true` allows the action, `false` prevents it |
821but can perform cleanup tasks.1876| `reason` | Required when `ok` is `false`. Explanation shown to Claude |
822
823#### Exit Code Example: Bash Command Validation
824
825```python theme={null}
826#!/usr/bin/env python3
827import json
828import re
829import sys
830
831# Define validation rules as a list of (regex pattern, message) tuples
832VALIDATION_RULES = [
833 (
834 r"\bgrep\b(?!.*\|)",
835 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
836 ),
837 (
838 r"\bfind\s+\S+\s+-name\b",
839 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
840 ),
841]
842
843
844def validate_command(command: str) -> list[str]:
845 issues = []
846 for pattern, message in VALIDATION_RULES:
847 if re.search(pattern, command):
848 issues.append(message)
849 return issues
850
851
852try:
853 input_data = json.load(sys.stdin)
854except json.JSONDecodeError as e:
855 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
856 sys.exit(1)
857
858tool_name = input_data.get("tool_name", "")
859tool_input = input_data.get("tool_input", {})
860command = tool_input.get("command", "")
861
862if tool_name != "Bash" or not command:
863 sys.exit(1)
864
865# Validate the command
866issues = validate_command(command)
867
868if issues:
869 for message in issues:
870 print(f"• {message}", file=sys.stderr)
871 # Exit code 2 blocks tool call and shows stderr to Claude
872 sys.exit(2)
873```
874
875#### JSON Output Example: UserPromptSubmit to Add Context and Validation
876
877<Note>
878 For `UserPromptSubmit` hooks, you can inject context using either method:
879 1877
880 * **Plain text stdout** with exit code 0: Simplest approach—just print text1878### Example: Multi-criteria Stop hook
881 * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts,
882 or `additionalContext` for structured context injection
883 1879
884 Remember: Exit code 2 only uses `stderr` for the error message. To block using1880This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction. `SubagentStop` hooks use the same format to evaluate whether a [subagent](/en/sub-agents) should stop:
885 JSON (with a custom reason), use `"decision": "block"` with exit code 0.
886</Note>
887 1881
888```python theme={null}1882```json theme={null}
889#!/usr/bin/env python31883{
890import json1884 "hooks": {
891import sys1885 "Stop": [
892import re1886 {
893import datetime1887 "hooks": [
894 1888 {
895# Load input from stdin1889 "type": "prompt",
896try:1890 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.",
897 input_data = json.load(sys.stdin)1891 "timeout": 30
898except json.JSONDecodeError as e:1892 }
899 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)1893 ]
900 sys.exit(1)1894 }
901 1895 ]
902prompt = input_data.get("prompt", "")
903
904# Check for sensitive patterns
905sensitive_patterns = [
906 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
907]
908
909for pattern, message in sensitive_patterns:
910 if re.search(pattern, prompt):
911 # Use JSON output to block with a specific reason
912 output = {
913 "decision": "block",
914 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
915 }1896 }
916 print(json.dumps(output))1897}
917 sys.exit(0)1898```
918 1899
919# Add current time to context1900## Agent-based hooks
920context = f"Current time: {datetime.datetime.now()}"
921print(context)
922 1901
923"""1902Agent-based hooks (`type: "agent"`) are like prompt-based hooks but with multi-turn tool access. Instead of a single LLM call, an agent hook spawns a subagent that can read files, search code, and inspect the codebase to verify conditions. Agent hooks support the same events as prompt-based hooks.
924The following is also equivalent:
925print(json.dumps({
926 "hookSpecificOutput": {
927 "hookEventName": "UserPromptSubmit",
928 "additionalContext": context,
929 },
930}))
931"""
932 1903
933# Allow the prompt to proceed with the additional context1904### How agent hooks work
934sys.exit(0)
935```
936 1905
937#### JSON Output Example: PreToolUse with Approval1906When an agent hook fires:
938
939```python theme={null}
940#!/usr/bin/env python3
941import json
942import sys
943
944# Load input from stdin
945try:
946 input_data = json.load(sys.stdin)
947except json.JSONDecodeError as e:
948 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
949 sys.exit(1)
950
951tool_name = input_data.get("tool_name", "")
952tool_input = input_data.get("tool_input", {})
953
954# Example: Auto-approve file reads for documentation files
955if tool_name == "Read":
956 file_path = tool_input.get("file_path", "")
957 if file_path.endswith((".md", ".mdx", ".txt", ".json")):
958 # Use JSON output to auto-approve the tool call
959 output = {
960 "decision": "approve",
961 "reason": "Documentation file auto-approved",
962 "suppressOutput": True # Don't show in verbose mode
963 }
964 print(json.dumps(output))
965 sys.exit(0)
966
967# For other cases, let the normal permission flow proceed
968sys.exit(0)
969```
970 1907
971## Working with MCP Tools19081. Claude Code spawns a subagent with your prompt and the hook's JSON input
19092. The subagent can use tools like Read, Grep, and Glob to investigate
19103. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision
19114. Claude Code processes the decision the same way as a prompt hook
972 1912
973Claude Code hooks work seamlessly with1913Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.
974[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers
975provide tools, they appear with a special naming pattern that you can match in
976your hooks.
977 1914
978### MCP Tool Naming1915### Agent hook configuration
979 1916
980MCP tools follow the pattern `mcp__<server>__<tool>`, for example:1917Set `type` to `"agent"` and provide a `prompt` string. The configuration fields are the same as [prompt hooks](#prompt-hook-configuration), with a longer default timeout:
981 1918
982* `mcp__memory__create_entities` - Memory server's create entities tool1919| Field | Required | Description |
983* `mcp__filesystem__read_file` - Filesystem server's read file tool1920| :-------- | :------- | :------------------------------------------------------------------------------------------ |
984* `mcp__github__search_repositories` - GitHub server's search tool1921| `type` | yes | Must be `"agent"` |
1922| `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON |
1923| `model` | no | Model to use. Defaults to a fast model |
1924| `timeout` | no | Timeout in seconds. Default: 60 |
985 1925
986### Configuring Hooks for MCP Tools1926The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.
987 1927
988You can target specific MCP tools or entire MCP servers:1928This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
989 1929
990```json theme={null}1930```json theme={null}
991{1931{
992 "hooks": {1932 "hooks": {
993 "PreToolUse": [1933 "Stop": [
994 {1934 {
995 "matcher": "mcp__memory__.*",
996 "hooks": [1935 "hooks": [
997 {1936 {
998 "type": "command",1937 "type": "agent",
999 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"1938 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",
1939 "timeout": 120
1000 }1940 }
1001 ]1941 ]
1002 },1942 }
1943 ]
1944 }
1945}
1946```
1947
1948## Run hooks in the background
1949
1950By default, hooks block Claude's execution until they complete. For long-running tasks like deployments, test suites, or external API calls, set `"async": true` to run the hook in the background while Claude continues working. Async hooks cannot block or control Claude's behavior: response fields like `decision`, `permissionDecision`, and `continue` have no effect, because the action they would have controlled has already completed.
1951
1952### Configure an async hook
1953
1954Add `"async": true` to a command hook's configuration to run it in the background without blocking Claude. This field is only available on `type: "command"` hooks.
1955
1956This hook runs a test script after every `Write` tool call. Claude continues working immediately while `run-tests.sh` executes for up to 120 seconds. When the script finishes, its output is delivered on the next conversation turn:
1957
1958```json theme={null}
1959{
1960 "hooks": {
1961 "PostToolUse": [
1003 {1962 {
1004 "matcher": "mcp__.*__write.*",1963 "matcher": "Write",
1005 "hooks": [1964 "hooks": [
1006 {1965 {
1007 "type": "command",1966 "type": "command",
1008 "command": "/home/user/scripts/validate-mcp-write.py"1967 "command": "/path/to/run-tests.sh",
1968 "async": true,
1969 "timeout": 120
1009 }1970 }
1010 ]1971 ]
1011 }1972 }
1014}1975}
1015```1976```
1016 1977
1017## Examples1978The `timeout` field sets the maximum time in seconds for the background process. If not specified, async hooks use the same 10-minute default as sync hooks.
1018
1019<Tip>
1020 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/hooks-guide#more-examples) in the get started guide.
1021</Tip>
1022 1979
1023## Security Considerations1980### How async hooks execute
1024 1981
1025### Disclaimer1982When an async hook fires, Claude Code starts the hook process and immediately continues without waiting for it to finish. The hook receives the same JSON input via stdin as a synchronous hook.
1026 1983
1027**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on1984After 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.
1028your system automatically. By using hooks, you acknowledge that:
1029 1985
1030* You are solely responsible for the commands you configure1986Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
1031* Hooks can modify, delete, or access any files your user account can access
1032* Malicious or poorly written hooks can cause data loss or system damage
1033* Anthropic provides no warranty and assumes no liability for any damages
1034 resulting from hook usage
1035* You should thoroughly test hooks in a safe environment before production use
1036 1987
1037Always review and understand any hook commands before adding them to your1988### Example: run tests after file changes
1038configuration.
1039 1989
1040### Security Best Practices1990This 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`:
1041 1991
1042Here are some key practices for writing more secure hooks:1992```bash theme={null}
1993#!/bin/bash
1994# run-tests-async.sh
1043 1995
10441. **Validate and sanitize inputs** - Never trust input data blindly1996# Read hook input from stdin
10452. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1997INPUT=$(cat)
10463. **Block path traversal** - Check for `..` in file paths1998FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
10474. **Use absolute paths** - Specify full paths for scripts (use
1048 "\$CLAUDE\_PROJECT\_DIR" for the project path)
10495. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.
1050 1999
1051### Configuration Safety2000# Only run tests for source files
2001if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
2002 exit 0
2003fi
1052 2004
1053Direct edits to hooks in settings files don't take effect immediately. Claude2005# Run tests and report results via systemMessage
1054Code:2006RESULT=$(npm test 2>&1)
2007EXIT_CODE=$?
1055 2008
10561. Captures a snapshot of hooks at startup2009if [ $EXIT_CODE -eq 0 ]; then
10572. Uses this snapshot throughout the session2010 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
10583. Warns if hooks are modified externally2011else
10594. Requires review in `/hooks` menu for changes to apply2012 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
2013fi
2014```
1060 2015
1061This prevents malicious hook modifications from affecting your current session.2016Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:
1062 2017
1063## Hook Execution Details2018```json theme={null}
2019{
2020 "hooks": {
2021 "PostToolUse": [
2022 {
2023 "matcher": "Write|Edit",
2024 "hooks": [
2025 {
2026 "type": "command",
2027 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",
2028 "async": true,
2029 "timeout": 300
2030 }
2031 ]
2032 }
2033 ]
2034 }
2035}
2036```
1064 2037
1065* **Timeout**: 60-second execution limit by default, configurable per command.2038### Limitations
1066 * A timeout for an individual command does not affect the other commands.
1067* **Parallelization**: All matching hooks run in parallel
1068* **Deduplication**: Multiple identical hook commands are deduplicated automatically
1069* **Environment**: Runs in current directory with Claude Code's environment
1070 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the
1071 absolute path to the project root directory (where Claude Code was started)
1072 * The `CLAUDE_CODE_REMOTE` environment variable indicates whether the hook is running in a remote (web) environment (`"true"`) or local CLI environment (not set or empty). Use this to run different logic based on execution context.
1073* **Input**: JSON via stdin
1074* **Output**:
1075 * PreToolUse/PermissionRequest/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o)
1076 * Notification/SessionEnd: Logged to debug only (`--debug`)
1077 * UserPromptSubmit/SessionStart: stdout added as context for Claude
1078 2039
1079## Debugging2040Async hooks have several constraints compared to synchronous hooks:
1080 2041
1081### Basic Troubleshooting2042* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.
2043* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
2044* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.
2045* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
1082 2046
1083If your hooks aren't working:2047## Security considerations
1084 2048
10851. **Check configuration** - Run `/hooks` to see if your hook is registered2049### Disclaimer
10862. **Verify syntax** - Ensure your JSON settings are valid
10873. **Test commands** - Run hook commands manually first
10884. **Check permissions** - Make sure scripts are executable
10895. **Review logs** - Use `claude --debug` to see hook execution details
1090 2050
1091Common issues:2051Command hooks run with your system user's full permissions.
1092 2052
1093* **Quotes not escaped** - Use `\"` inside JSON strings2053<Warning>
1094* **Wrong matcher** - Check tool names match exactly (case-sensitive)2054 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.
1095* **Command not found** - Use full paths for scripts2055</Warning>
1096 2056
1097### Advanced Debugging2057### Security best practices
1098 2058
1099For complex hook issues:2059Keep these practices in mind when writing hooks:
1100 2060
11011. **Inspect hook execution** - Use `claude --debug` to see detailed hook2061* **Validate and sanitize inputs**: never trust input data blindly
1102 execution2062* **Always quote shell variables**: use `"$VAR"` not `$VAR`
11032. **Validate JSON schemas** - Test hook input/output with external tools2063* **Block path traversal**: check for `..` in file paths
11043. **Check environment variables** - Verify Claude Code's environment is correct2064* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root
11054. **Test edge cases** - Try hooks with unusual file paths or inputs2065* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.
11065. **Monitor system resources** - Check for resource exhaustion during hook
1107 execution
11086. **Use structured logging** - Implement logging in your hook scripts
1109 2066
1110### Debug Output Example2067## Debug hooks
1111 2068
1112Use `claude --debug` to see hook execution details:2069Run `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.
1113 2070
1114```2071```text theme={null}
1115[DEBUG] Executing hooks for PostToolUse:Write2072[DEBUG] Executing hooks for PostToolUse:Write
1116[DEBUG] Getting matching hook commands for PostToolUse with query: Write2073[DEBUG] Getting matching hook commands for PostToolUse with query: Write
1117[DEBUG] Found 1 hook matchers in settings2074[DEBUG] Found 1 hook matchers in settings
1118[DEBUG] Matched 1 hooks for query "Write"2075[DEBUG] Matched 1 hooks for query "Write"
1119[DEBUG] Found 1 hook commands to execute2076[DEBUG] Found 1 hook commands to execute
1120[DEBUG] Executing hook command: <Your command> with timeout 60000ms2077[DEBUG] Executing hook command: <Your command> with timeout 600000ms
1121[DEBUG] Hook command completed with status 0: <Your stdout>2078[DEBUG] Hook command completed with status 0: <Your stdout>
1122```2079```
1123 2080
1124Progress messages appear in verbose mode (ctrl+o) showing:2081For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](/en/hooks-guide#limitations-and-troubleshooting) in the guide.
1125
1126* Which hook is running
1127* Command being executed
1128* Success/failure status
1129* Output or error messages
1130
1131
1132
1133> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt