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/JCMefyZyaJwkJgv-/images/hooks-lifecycle.svg?fit=max&auto=format&n=JCMefyZyaJwkJgv-&q=85&s=f004f3fc7324fa2a4630e8d6559cf6dd" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCompleted) to Stop or StopFailure, TeammateIdle, PreCompact, PostCompact, and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, InstructionsLoaded, CwdChanged, and FileChanged as standalone async events" width="520" height="1100" data-path="images/hooks-lifecycle.svg" />
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| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |
45| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |
46| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |
47| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |
48| `PreCompact` | Before context compaction |
49| `PostCompact` | After context compaction completes |
50| `Elicitation` | When an MCP server requests user input during a tool call |
51| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |
52| `SessionEnd` | When a session terminates |
53
54### How a hook resolves
55
56To 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 57
22```json theme={null}58```json theme={null}
23{59{
24 "hooks": {60 "hooks": {
25 "EventName": [61 "PreToolUse": [
26 {62 {
27 "matcher": "ToolPattern",63 "matcher": "Bash",
28 "hooks": [64 "hooks": [
29 {65 {
30 "type": "command",66 "type": "command",
31 "command": "your-command-here"67 "command": ".claude/hooks/block-rm.sh"
32 }68 }
33 ]69 ]
34 }70 }
37}73}
38```74```
39 75
40* **matcher**: Pattern to match tool names, case-sensitive (only applicable for76The 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 77
55```json theme={null}78```bash theme={null}
56{79#!/bin/bash
57 "hooks": {80# .claude/hooks/block-rm.sh
58 "UserPromptSubmit": [81COMMAND=$(jq -r '.tool_input.command')
59 {82
60 "hooks": [83if echo "$COMMAND" | grep -q 'rm -rf'; then
61 {84 jq -n '{
62 "type": "command",85 hookSpecificOutput: {
63 "command": "/path/to/prompt-validator.py"86 hookEventName: "PreToolUse",
87 permissionDecision: "deny",
88 permissionDecisionReason: "Destructive command blocked by hook"
64 }89 }
65 ]90 }'
91else
92 exit 0 # allow the command
93fi
94```
95
96Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
97
98<Frame>
99 <img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/hook-resolution.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=ad667ee6d86ab2276aa48a4e73e220df" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" width="780" height="290" data-path="images/hook-resolution.svg" />
100</Frame>
101
102<Steps>
103 <Step title="Event fires">
104 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
105
106 ```json theme={null}
107 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
108 ```
109 </Step>
110
111 <Step title="Matcher checks">
112 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.
113 </Step>
114
115 <Step title="Hook handler runs">
116 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:
117
118 ```json theme={null}
119 {
120 "hookSpecificOutput": {
121 "hookEventName": "PreToolUse",
122 "permissionDecision": "deny",
123 "permissionDecisionReason": "Destructive command blocked by hook"
66 }124 }
67 ]
68 }125 }
69}126 ```
70```
71 127
72### Project-Specific Hook Scripts128 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.
129 </Step>
73 130
74You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when131 <Step title="Claude Code acts on the result">
75Claude Code spawns the hook command) to reference scripts stored in your project,132 Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.
76ensuring they work regardless of Claude's current directory:133 </Step>
134</Steps>
135
136The [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.
137
138## Configuration
139
140Hooks are defined in JSON settings files. The configuration has three levels of nesting:
141
1421. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop`
1432. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool"
1443. Define one or more [hook handlers](#hook-handler-fields) to run when matched
145
146See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.
147
148<Note>
149 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, prompt, or agent that runs. "Hook" on its own refers to the general feature.
150</Note>
151
152### Hook locations
153
154Where you define a hook determines its scope:
155
156| Location | Scope | Shareable |
157| :--------------------------------------------------------- | :---------------------------- | :--------------------------------- |
158| `~/.claude/settings.json` | All your projects | No, local to your machine |
159| `.claude/settings.json` | Single project | Yes, can be committed to the repo |
160| `.claude/settings.local.json` | Single project | No, gitignored |
161| Managed policy settings | Organization-wide | Yes, admin-controlled |
162| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |
163| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |
164
165For 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).
166
167### Matcher patterns
168
169The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field:
170
171| Event | What the matcher filters | Example matcher values |
172| :---------------------------------------------------------------------------------------------- | :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
173| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
174| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |
175| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |
176| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |
177| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |
178| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |
179| `SubagentStop` | agent type | same values as `SubagentStart` |
180| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |
181| `CwdChanged` | no matcher support | always fires on every directory change |
182| `FileChanged` | filename (basename of the changed file) | `.envrc`, `.env`, any filename you want to watch |
183| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |
184| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |
185| `Elicitation` | MCP server name | your configured MCP server names |
186| `ElicitationResult` | MCP server name | same values as `Elicitation` |
187| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |
188
189The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.
190
191This example runs a linting script only when Claude writes or edits a file:
77 192
78```json theme={null}193```json theme={null}
79{194{
80 "hooks": {195 "hooks": {
81 "PostToolUse": [196 "PostToolUse": [
82 {197 {
83 "matcher": "Write|Edit",198 "matcher": "Edit|Write",
84 "hooks": [199 "hooks": [
85 {200 {
86 "type": "command",201 "type": "command",
87 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"202 "command": "/path/to/lint-check.sh"
88 }203 }
89 ]204 ]
90 }205 }
93}208}
94```209```
95 210
96### Plugin hooks211`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
97 212
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.213#### Match MCP tools
99 214
100**How plugin hooks work**:215[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 216
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.217MCP 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 218
107**Example plugin hook configuration**:219* `mcp__memory__create_entities`: Memory server's create entities tool
220* `mcp__filesystem__read_file`: Filesystem server's read file tool
221* `mcp__github__search_repositories`: GitHub server's search tool
222
223Use regex patterns to target specific MCP tools or groups of tools:
224
225* `mcp__memory__.*` matches all tools from the `memory` server
226* `mcp__.*__write.*` matches any tool containing "write" from any server
227
228This example logs all memory server operations and validates write operations from any MCP server:
108 229
109```json theme={null}230```json theme={null}
110{231{
111 "description": "Automatic code formatting",
112 "hooks": {232 "hooks": {
113 "PostToolUse": [233 "PreToolUse": [
114 {234 {
115 "matcher": "Write|Edit",235 "matcher": "mcp__memory__.*",
116 "hooks": [236 "hooks": [
117 {237 {
118 "type": "command",238 "type": "command",
119 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",239 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
120 "timeout": 30240 }
241 ]
242 },
243 {
244 "matcher": "mcp__.*__write.*",
245 "hooks": [
246 {
247 "type": "command",
248 "command": "/home/user/scripts/validate-mcp-write.py"
121 }249 }
122 ]250 ]
123 }251 }
126}254}
127```255```
128 256
129<Note>257### 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 258
133<Note>259Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, LLM prompt, or agent that runs when the matcher matches. There are four types:
134 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.
135</Note>
136 260
137**Environment variables for plugins**:261* **[Command hooks](#command-hook-fields)** (`type: "command"`): run a shell command. Your script receives the event's [JSON input](#hook-input-and-output) on stdin and communicates results back through exit codes and stdout.
262* **[HTTP hooks](#http-hook-fields)** (`type: "http"`): send the event's JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same [JSON output format](#json-output) as command hooks.
263* **[Prompt hooks](#prompt-and-agent-hook-fields)** (`type: "prompt"`): send a prompt to a Claude model for single-turn evaluation. The model returns a yes/no decision as JSON. See [Prompt-based hooks](#prompt-based-hooks).
264* **[Agent hooks](#prompt-and-agent-hook-fields)** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. See [Agent-based hooks](#agent-based-hooks).
138 265
139* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory266#### Common fields
140* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)
141* All standard environment variables are available
142 267
143See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.268These fields apply to all hook types:
144 269
145## Prompt-Based Hooks270| Field | Required | Description |
271| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
272| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |
273| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |
274| `statusMessage` | no | Custom spinner message displayed while the hook runs |
275| `once` | no | If `true`, runs only once per session then is removed. Skills only, not agents. See [Hooks in skills and agents](#hooks-in-skills-and-agents) |
146 276
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.277#### Command hook fields
148 278
149### How prompt-based hooks work279In addition to the [common fields](#common-fields), command hooks accept these fields:
150 280
151Instead of executing a bash command, prompt-based hooks:281| Field | Required | Description |
282| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
283| `command` | yes | Shell command to execute |
284| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |
285| `shell` | no | Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly |
152 286
1531. Send the hook input and your prompt to a fast LLM (Haiku)287#### HTTP hook fields
1542. The LLM responds with structured JSON containing a decision288
1553. Claude Code processes the decision automatically289In addition to the [common fields](#common-fields), HTTP hooks accept these fields:
156 290
157### Configuration291| Field | Required | Description |
292| :--------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
293| `url` | yes | URL to send the POST request to |
294| `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 |
295| `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 |
296
297Claude 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.
298
299Error 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"`.
300
301This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
158 302
159```json theme={null}303```json theme={null}
160{304{
161 "hooks": {305 "hooks": {
162 "Stop": [306 "PreToolUse": [
163 {307 {
308 "matcher": "Bash",
164 "hooks": [309 "hooks": [
165 {310 {
166 "type": "prompt",311 "type": "http",
167 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."312 "url": "http://localhost:8080/hooks/pre-tool-use",
313 "timeout": 30,
314 "headers": {
315 "Authorization": "Bearer $MY_TOKEN"
316 },
317 "allowedEnvVars": ["MY_TOKEN"]
168 }318 }
169 ]319 ]
170 }320 }
173}323}
174```324```
175 325
176**Fields:**326#### Prompt and agent hook fields
177 327
178* `type`: Must be `"prompt"`328In 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 329
198**Response fields:**330| Field | Required | Description |
331| :------- | :------- | :------------------------------------------------------------------------------------------ |
332| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |
333| `model` | no | Model to use for evaluation. Defaults to a fast model |
199 334
200* `decision`: `"approve"` allows the action, `"block"` prevents it335All 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 336
206### Supported hook events337### Reference scripts by path
207 338
208Prompt-based hooks work with any hook event, but are most useful for:339Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
209 340
210* **Stop**: Intelligently decide if Claude should continue working341* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.
211* **SubagentStop**: Evaluate if a subagent has completed its task342* `${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 assistance343* `${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 344
216### Example: Intelligent Stop hook345<Tabs>
346 <Tab title="Project scripts">
347 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 348
218```json theme={null}349 ```json theme={null}
219{350 {
220 "hooks": {351 "hooks": {
221 "Stop": [352 "PostToolUse": [
222 {353 {
354 "matcher": "Write|Edit",
223 "hooks": [355 "hooks": [
224 {356 {
225 "type": "prompt",357 "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\"}",358 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
227 "timeout": 30
228 }359 }
229 ]360 ]
230 }361 }
231 ]362 ]
232 }363 }
233}364 }
234```365 ```
366 </Tab>
235 367
236### Example: SubagentStop with custom logic368 <Tab title="Plugin scripts">
369 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 370
238```json theme={null}371 This example runs a formatting script bundled with the plugin:
239{372
373 ```json theme={null}
374 {
375 "description": "Automatic code formatting",
240 "hooks": {376 "hooks": {
241 "SubagentStop": [377 "PostToolUse": [
242 {378 {
379 "matcher": "Write|Edit",
243 "hooks": [380 "hooks": [
244 {381 {
245 "type": "prompt",382 "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\"}"383 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
384 "timeout": 30
247 }385 }
248 ]386 ]
249 }387 }
250 ]388 ]
251 }389 }
252}390 }
253```391 ```
254 392
255### Comparison with bash command hooks393 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.
394 </Tab>
395</Tabs>
256 396
257| Feature | Bash Command Hooks | Prompt-Based Hooks |397### 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 398
266### Best practices399In 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 400
268* **Be specific in prompts**: Clearly state what you want the LLM to evaluate401All 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 402
274See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.403Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.
275 404
276## Hook Events405This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
277 406
278### PreToolUse407```yaml theme={null}
408---
409name: secure-operations
410description: Perform operations with security checks
411hooks:
412 PreToolUse:
413 - matcher: "Bash"
414 hooks:
415 - type: command
416 command: "./scripts/security-check.sh"
417---
418```
279 419
280Runs after Claude creates tool parameters and before processing the tool call.420Agents use the same format in their YAML frontmatter.
281 421
282**Common matchers:**422### The `/hooks` menu
283 423
284* `Task` - Subagent tasks (see [subagents documentation](/en/sub-agents))424Type `/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 425
293Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.426The 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 427
295### PermissionRequest428* `User`: from `~/.claude/settings.json`
429* `Project`: from `.claude/settings.json`
430* `Local`: from `.claude/settings.local.json`
431* `Plugin`: from a plugin's `hooks/hooks.json`
432* `Session`: registered in memory for the current session
433* `Built-in`: registered internally by Claude Code
296 434
297Runs when the user is shown a permission dialog.435Selecting 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 436
300Recognizes the same matcher values as PreToolUse.437### Disable or remove hooks
301 438
302### PostToolUse439To remove a hook, delete its entry from the settings JSON file.
303 440
304Runs immediately after a tool completes successfully.441To 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 442
306Recognizes the same matcher values as PreToolUse.443The `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 444
308### Notification445Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
446
447## Hook input and output
448
449Command 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.
450
451### Common input fields
309 452
310Runs when Claude Code sends notifications. Supports matchers to filter by notification type.453Hook 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.
311 454
312**Common matchers:**455| Field | Description |
456| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
457| `session_id` | Current session identifier |
458| `transcript_path` | Path to conversation JSON |
459| `cwd` | Current working directory when the hook is invoked |
460| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event's JSON example below to check |
461| `hook_event_name` | Name of the event that fired |
313 462
314* `permission_prompt` - Permission requests from Claude Code463When running with `--agent` or inside a subagent, two additional fields are included:
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 464
319You can use matchers to run different hooks for different notification types, or omit the matcher to run hooks for all notifications.465| Field | Description |
466| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
467| `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. |
468| `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. |
320 469
321**Example: Different notifications for different types**470For example, a `PreToolUse` hook for a Bash command receives this on stdin:
322 471
323```json theme={null}472```json theme={null}
324{473{
325 "hooks": {474 "session_id": "abc123",
326 "Notification": [475 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
327 {476 "cwd": "/home/user/my-project",
328 "matcher": "permission_prompt",477 "permission_mode": "default",
329 "hooks": [478 "hook_event_name": "PreToolUse",
479 "tool_name": "Bash",
480 "tool_input": {
481 "command": "npm test"
482 }
483}
484```
485
486The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.
487
488### Exit code output
489
490The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.
491
492**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.
493
494**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.
495
496**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.
497
498For example, a hook command script that blocks dangerous Bash commands:
499
500```bash theme={null}
501#!/bin/bash
502# Reads JSON input from stdin, checks the command
503command=$(jq -r '.tool_input.command' < /dev/stdin)
504
505if [[ "$command" == rm* ]]; then
506 echo "Blocked: rm commands are not allowed" >&2
507 exit 2 # Blocking error: tool call is prevented
508fi
509
510exit 0 # Success: tool call proceeds
511```
512
513#### Exit code 2 behavior per event
514
515Exit 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.
516
517| Hook event | Can block? | What happens on exit 2 |
518| :------------------- | :--------- | :---------------------------------------------------------------------------- |
519| `PreToolUse` | Yes | Blocks the tool call |
520| `PermissionRequest` | Yes | Denies the permission |
521| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
522| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
523| `SubagentStop` | Yes | Prevents the subagent from stopping |
524| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |
525| `TaskCompleted` | Yes | Prevents the task from being marked as completed |
526| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |
527| `StopFailure` | No | Output and exit code are ignored |
528| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
529| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
530| `Notification` | No | Shows stderr to user only |
531| `SubagentStart` | No | Shows stderr to user only |
532| `SessionStart` | No | Shows stderr to user only |
533| `SessionEnd` | No | Shows stderr to user only |
534| `CwdChanged` | No | Shows stderr to user only |
535| `FileChanged` | No | Shows stderr to user only |
536| `PreCompact` | No | Shows stderr to user only |
537| `PostCompact` | No | Shows stderr to user only |
538| `Elicitation` | Yes | Denies the elicitation |
539| `ElicitationResult` | Yes | Blocks the response (action becomes decline) |
540| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |
541| `WorktreeRemove` | No | Failures are logged in debug mode only |
542| `InstructionsLoaded` | No | Exit code is ignored |
543
544### HTTP response handling
545
546HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:
547
548* **2xx with an empty body**: success, equivalent to exit code 0 with no output
549* **2xx with a plain text body**: success, the text is added as context
550* **2xx with a JSON body**: success, parsed using the same [JSON output](#json-output) schema as command hooks
551* **Non-2xx status**: non-blocking error, execution continues
552* **Connection failure or timeout**: non-blocking error, execution continues
553
554Unlike 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.
555
556### JSON output
557
558Exit 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.
559
560<Note>
561 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.
562</Note>
563
564Your 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.
565
566The JSON object supports three kinds of fields:
567
568* **Universal fields** like `continue` work across all events. These are listed in the table below.
569* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.
570* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.
571
572| Field | Default | Description |
573| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |
574| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |
575| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |
576| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |
577| `systemMessage` | none | Warning message shown to the user |
578
579To stop Claude entirely regardless of event type:
580
581```json theme={null}
582{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
583```
584
585#### Decision control
586
587Not 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:
588
589| Events | Decision pattern | Key fields |
590| :-------------------------------------------------------------------------------------------------------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
591| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |
592| 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 |
593| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |
594| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |
595| WorktreeCreate | path return | Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation |
596| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |
597| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |
598| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged | None | No decision control. Used for side effects like logging or cleanup |
599
600Here are examples of each pattern in action:
601
602<Tabs>
603 <Tab title="Top-level decision">
604 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:
605
606 ```json theme={null}
330 {607 {
331 "type": "command",608 "decision": "block",
332 "command": "/path/to/permission-alert.sh"609 "reason": "Test suite must pass before proceeding"
333 }610 }
334 ]611 ```
335 },612 </Tab>
613
614 <Tab title="PreToolUse">
615 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.
616
617 ```json theme={null}
336 {618 {
337 "matcher": "idle_prompt",619 "hookSpecificOutput": {
338 "hooks": [620 "hookEventName": "PreToolUse",
621 "permissionDecision": "deny",
622 "permissionDecisionReason": "Database writes are not allowed"
623 }
624 }
625 ```
626 </Tab>
627
628 <Tab title="PermissionRequest">
629 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.
630
631 ```json theme={null}
339 {632 {
340 "type": "command",633 "hookSpecificOutput": {
341 "command": "/path/to/idle-notification.sh"634 "hookEventName": "PermissionRequest",
635 "decision": {
636 "behavior": "allow",
637 "updatedInput": {
638 "command": "npm run lint"
342 }639 }
343 ]
344 }640 }
345 ]
346 }641 }
347}642 }
348```643 ```
644 </Tab>
645</Tabs>
349 646
350### UserPromptSubmit647For 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 648
352Runs when the user submits a prompt, before Claude processes it. This allows you649## Hook events
353to add additional context based on the prompt/conversation, validate prompts, or
354block certain types of prompts.
355 650
356### Stop651Each 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 652
358Runs when the main Claude Code agent has finished responding. Does not run if653### SessionStart
359the stoppage occurred due to a user interrupt.
360 654
361### SubagentStop655Runs 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 656
363Runs when a Claude Code subagent (Task tool call) has finished responding.657SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported.
364 658
365### PreCompact659The matcher value corresponds to how the session was initiated:
366 660
367Runs before Claude Code is about to run a compact operation.661| Matcher | When it fires |
662| :-------- | :------------------------------------- |
663| `startup` | New session |
664| `resume` | `--resume`, `--continue`, or `/resume` |
665| `clear` | `/clear` |
666| `compact` | Auto or manual compaction |
368 667
369**Matchers:**668#### SessionStart input
370 669
371* `manual` - Invoked from `/compact`670In 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 671
374### SessionStart672```json theme={null}
673{
674 "session_id": "abc123",
675 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
676 "cwd": "/Users/...",
677 "hook_event_name": "SessionStart",
678 "source": "startup",
679 "model": "claude-sonnet-4-6"
680}
681```
682
683#### SessionStart decision control
375 684
376Runs when Claude Code starts a new session or resumes an existing session (which685Any 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 686
380**Matchers:**687| Field | Description |
688| :------------------ | :------------------------------------------------------------------------ |
689| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |
381 690
382* `startup` - Invoked from startup691```json theme={null}
383* `resume` - Invoked from `--resume`, `--continue`, or `/resume`692{
384* `clear` - Invoked from `/clear`693 "hookSpecificOutput": {
385* `compact` - Invoked from auto or manual compact.694 "hookEventName": "SessionStart",
695 "additionalContext": "My additional context here"
696 }
697}
698```
386 699
387#### Persisting environment variables700#### Persist environment variables
388 701
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.702SessionStart 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 703
391**Example: Setting individual environment variables**704To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:
392 705
393```bash theme={null}706```bash theme={null}
394#!/bin/bash707#!/bin/bash
395 708
396if [ -n "$CLAUDE_ENV_FILE" ]; then709if [ -n "$CLAUDE_ENV_FILE" ]; then
397 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"710 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
398 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"711 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
399 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"712 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
400fi713fi
401 714
402exit 0715exit 0
403```716```
404 717
405**Example: Persisting all environment changes from the hook**718To 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 719
409```bash theme={null}720```bash theme={null}
410#!/bin/bash721#!/bin/bash
423exit 0734exit 0
424```735```
425 736
426Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session.737Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
427 738
428<Note>739<Note>
429 `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable.740 `CLAUDE_ENV_FILE` is available for SessionStart, [CwdChanged](#cwdchanged), and [FileChanged](#filechanged) hooks. Other hook types do not have access to this variable.
430</Note>741</Note>
431 742
432### SessionEnd743### InstructionsLoaded
433 744
434Runs when a Claude Code session ends. Useful for cleanup tasks, logging session745Fires 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 746
437The `reason` field in the hook input will be one of:747The 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 748
439* `clear` - Session cleared with /clear command749#### InstructionsLoaded input
440* `logout` - User logged out
441* `prompt_input_exit` - User exited while prompt input was visible
442* `other` - Other exit reasons
443 750
444## Hook Input751In addition to the [common input fields](#common-input-fields), InstructionsLoaded hooks receive these fields:
445 752
446Hooks receive JSON data via stdin containing session information and753| Field | Description |
447event-specific data:754| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
755| `file_path` | Absolute path to the instruction file that was loaded |
756| `memory_type` | Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"` |
757| `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 |
758| `globs` | Path glob patterns from the file's `paths:` frontmatter, if any. Present only for `path_glob_match` loads |
759| `trigger_file_path` | Path to the file whose access triggered this load, for lazy loads |
760| `parent_file_path` | Path to the parent instruction file that included this one, for `include` loads |
448 761
449```typescript theme={null}762```json theme={null}
450{763{
451 // Common fields764 "session_id": "abc123",
452 session_id: string765 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
453 transcript_path: string // Path to conversation JSON766 "cwd": "/Users/my-project",
454 cwd: string // The current working directory when the hook is invoked767 "hook_event_name": "InstructionsLoaded",
455 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions"768 "file_path": "/Users/my-project/CLAUDE.md",
456 769 "memory_type": "Project",
457 // Event-specific fields770 "load_reason": "session_start"
458 hook_event_name: string
459 ...
460}771}
461```772```
462 773
463### PreToolUse Input774#### InstructionsLoaded decision control
775
776InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
777
778### UserPromptSubmit
779
780Runs when the user submits a prompt, before Claude processes it. This allows you
781to add additional context based on the prompt/conversation, validate prompts, or
782block certain types of prompts.
783
784#### UserPromptSubmit input
464 785
465The exact schema for `tool_input` depends on the tool.786In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
466 787
467```json theme={null}788```json theme={null}
468{789{
470 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",791 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
471 "cwd": "/Users/...",792 "cwd": "/Users/...",
472 "permission_mode": "default",793 "permission_mode": "default",
473 "hook_event_name": "PreToolUse",794 "hook_event_name": "UserPromptSubmit",
474 "tool_name": "Write",795 "prompt": "Write a function to calculate the factorial of a number"
475 "tool_input": {796}
476 "file_path": "/path/to/file.txt",797```
477 "content": "file content"798
478 },799#### UserPromptSubmit decision control
479 "tool_use_id": "toolu_01ABC123..."800
801`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.
802
803There are two ways to add context to the conversation on exit code 0:
804
805* **Plain text stdout**: any non-JSON text written to stdout is added as context
806* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
807
808Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.
809
810To block a prompt, return a JSON object with `decision` set to `"block"`:
811
812| Field | Description |
813| :------------------ | :----------------------------------------------------------------------------------------------------------------- |
814| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |
815| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |
816| `additionalContext` | String added to Claude's context |
817
818```json theme={null}
819{
820 "decision": "block",
821 "reason": "Explanation for decision",
822 "hookSpecificOutput": {
823 "hookEventName": "UserPromptSubmit",
824 "additionalContext": "My additional context here"
825 }
826}
827```
828
829<Note>
830 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
831 block prompts or want more structured control.
832</Note>
833
834### PreToolUse
835
836Runs 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).
837
838Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.
839
840#### PreToolUse input
841
842In 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:
843
844##### Bash
845
846Executes shell commands.
847
848| Field | Type | Example | Description |
849| :------------------ | :------ | :----------------- | :-------------------------------------------- |
850| `command` | string | `"npm test"` | The shell command to execute |
851| `description` | string | `"Run test suite"` | Optional description of what the command does |
852| `timeout` | number | `120000` | Optional timeout in milliseconds |
853| `run_in_background` | boolean | `false` | Whether to run the command in background |
854
855##### Write
856
857Creates or overwrites a file.
858
859| Field | Type | Example | Description |
860| :---------- | :----- | :-------------------- | :--------------------------------- |
861| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |
862| `content` | string | `"file content"` | Content to write to the file |
863
864##### Edit
865
866Replaces a string in an existing file.
867
868| Field | Type | Example | Description |
869| :------------ | :------ | :-------------------- | :--------------------------------- |
870| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |
871| `old_string` | string | `"original text"` | Text to find and replace |
872| `new_string` | string | `"replacement text"` | Replacement text |
873| `replace_all` | boolean | `false` | Whether to replace all occurrences |
874
875##### Read
876
877Reads file contents.
878
879| Field | Type | Example | Description |
880| :---------- | :----- | :-------------------- | :----------------------------------------- |
881| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |
882| `offset` | number | `10` | Optional line number to start reading from |
883| `limit` | number | `50` | Optional number of lines to read |
884
885##### Glob
886
887Finds files matching a glob pattern.
888
889| Field | Type | Example | Description |
890| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |
891| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |
892| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |
893
894##### Grep
895
896Searches file contents with regular expressions.
897
898| Field | Type | Example | Description |
899| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |
900| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |
901| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |
902| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |
903| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |
904| `-i` | boolean | `true` | Case insensitive search |
905| `multiline` | boolean | `false` | Enable multiline matching |
906
907##### WebFetch
908
909Fetches and processes web content.
910
911| Field | Type | Example | Description |
912| :------- | :----- | :---------------------------- | :----------------------------------- |
913| `url` | string | `"https://example.com/api"` | URL to fetch content from |
914| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |
915
916##### WebSearch
917
918Searches the web.
919
920| Field | Type | Example | Description |
921| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |
922| `query` | string | `"react hooks best practices"` | Search query |
923| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |
924| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |
925
926##### Agent
927
928Spawns a [subagent](/en/sub-agents).
929
930| Field | Type | Example | Description |
931| :-------------- | :----- | :------------------------- | :------------------------------------------- |
932| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |
933| `description` | string | `"Find API endpoints"` | Short description of the task |
934| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |
935| `model` | string | `"sonnet"` | Optional model alias to override the default |
936
937#### PreToolUse decision control
938
939`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.
940
941| Field | Description |
942| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
943| `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"` |
944| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |
945| `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 |
946| `additionalContext` | String added to Claude's context before the tool executes |
947
948When 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.
949
950```json theme={null}
951{
952 "hookSpecificOutput": {
953 "hookEventName": "PreToolUse",
954 "permissionDecision": "allow",
955 "permissionDecisionReason": "My reason here",
956 "updatedInput": {
957 "field_to_modify": "new value"
958 },
959 "additionalContext": "Current environment: production. Proceed with caution."
960 }
480}961}
481```962```
482 963
483### PostToolUse Input964<Note>
965 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.
966</Note>
967
968### PermissionRequest
969
970Runs when the user is shown a permission dialog.
971Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.
972
973Matches on tool name, same values as PreToolUse.
974
975#### PermissionRequest input
484 976
485The exact schema for `tool_input` and `tool_response` depends on the tool.977PermissionRequest 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.
978
979```json theme={null}
980{
981 "session_id": "abc123",
982 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
983 "cwd": "/Users/...",
984 "permission_mode": "default",
985 "hook_event_name": "PermissionRequest",
986 "tool_name": "Bash",
987 "tool_input": {
988 "command": "rm -rf node_modules",
989 "description": "Remove node_modules directory"
990 },
991 "permission_suggestions": [
992 {
993 "type": "addRules",
994 "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],
995 "behavior": "allow",
996 "destination": "localSettings"
997 }
998 ]
999}
1000```
1001
1002#### PermissionRequest decision control
1003
1004`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:
1005
1006| Field | Description |
1007| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1008| `behavior` | `"allow"` grants the permission, `"deny"` denies it |
1009| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |
1010| `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 |
1011| `message` | For `"deny"` only: tells Claude why the permission was denied |
1012| `interrupt` | For `"deny"` only: if `true`, stops Claude |
1013
1014```json theme={null}
1015{
1016 "hookSpecificOutput": {
1017 "hookEventName": "PermissionRequest",
1018 "decision": {
1019 "behavior": "allow",
1020 "updatedInput": {
1021 "command": "npm run lint"
1022 }
1023 }
1024 }
1025}
1026```
1027
1028#### Permission update entries
1029
1030The `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.
1031
1032| `type` | Fields | Effect |
1033| :------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1034| `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"` |
1035| `replaceRules` | `rules`, `behavior`, `destination` | Replaces all rules of the given `behavior` at the `destination` with the provided `rules` |
1036| `removeRules` | `rules`, `behavior`, `destination` | Removes matching rules of the given `behavior` |
1037| `setMode` | `mode`, `destination` | Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan` |
1038| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |
1039| `removeDirectories` | `directories`, `destination` | Removes working directories |
1040
1041The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.
1042
1043| `destination` | Writes to |
1044| :---------------- | :---------------------------------------------- |
1045| `session` | in-memory only, discarded when the session ends |
1046| `localSettings` | `.claude/settings.local.json` |
1047| `projectSettings` | `.claude/settings.json` |
1048| `userSettings` | `~/.claude/settings.json` |
1049
1050A 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.
1051
1052### PostToolUse
1053
1054Runs immediately after a tool completes successfully.
1055
1056Matches on tool name, same values as PreToolUse.
1057
1058#### PostToolUse input
1059
1060`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 1061
487```json theme={null}1062```json theme={null}
488{1063{
504}1079}
505```1080```
506 1081
507### Notification Input1082#### PostToolUse decision control
1083
1084`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:
1085
1086| Field | Description |
1087| :--------------------- | :----------------------------------------------------------------------------------------- |
1088| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |
1089| `reason` | Explanation shown to Claude when `decision` is `"block"` |
1090| `additionalContext` | Additional context for Claude to consider |
1091| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |
1092
1093```json theme={null}
1094{
1095 "decision": "block",
1096 "reason": "Explanation for decision",
1097 "hookSpecificOutput": {
1098 "hookEventName": "PostToolUse",
1099 "additionalContext": "Additional information for Claude"
1100 }
1101}
1102```
1103
1104### PostToolUseFailure
1105
1106Runs 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.
1107
1108Matches on tool name, same values as PreToolUse.
1109
1110#### PostToolUseFailure input
1111
1112PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:
1113
1114```json theme={null}
1115{
1116 "session_id": "abc123",
1117 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1118 "cwd": "/Users/...",
1119 "permission_mode": "default",
1120 "hook_event_name": "PostToolUseFailure",
1121 "tool_name": "Bash",
1122 "tool_input": {
1123 "command": "npm test",
1124 "description": "Run test suite"
1125 },
1126 "tool_use_id": "toolu_01ABC123...",
1127 "error": "Command exited with non-zero status code 1",
1128 "is_interrupt": false
1129}
1130```
1131
1132| Field | Description |
1133| :------------- | :------------------------------------------------------------------------------ |
1134| `error` | String describing what went wrong |
1135| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |
1136
1137#### PostToolUseFailure decision control
1138
1139`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:
1140
1141| Field | Description |
1142| :------------------ | :------------------------------------------------------------ |
1143| `additionalContext` | Additional context for Claude to consider alongside the error |
1144
1145```json theme={null}
1146{
1147 "hookSpecificOutput": {
1148 "hookEventName": "PostToolUseFailure",
1149 "additionalContext": "Additional information about the failure for Claude"
1150 }
1151}
1152```
1153
1154### Notification
1155
1156Runs 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.
1157
1158Use 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:
1159
1160```json theme={null}
1161{
1162 "hooks": {
1163 "Notification": [
1164 {
1165 "matcher": "permission_prompt",
1166 "hooks": [
1167 {
1168 "type": "command",
1169 "command": "/path/to/permission-alert.sh"
1170 }
1171 ]
1172 },
1173 {
1174 "matcher": "idle_prompt",
1175 "hooks": [
1176 {
1177 "type": "command",
1178 "command": "/path/to/idle-notification.sh"
1179 }
1180 ]
1181 }
1182 ]
1183 }
1184}
1185```
1186
1187#### Notification input
1188
1189In 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.
1190
1191```json theme={null}
1192{
1193 "session_id": "abc123",
1194 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1195 "cwd": "/Users/...",
1196 "hook_event_name": "Notification",
1197 "message": "Claude needs your permission to use Bash",
1198 "title": "Permission needed",
1199 "notification_type": "permission_prompt"
1200}
1201```
1202
1203Notification 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:
1204
1205| Field | Description |
1206| :------------------ | :------------------------------- |
1207| `additionalContext` | String added to Claude's context |
1208
1209### SubagentStart
1210
1211Runs 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/`).
1212
1213#### SubagentStart input
1214
1215In 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).
1216
1217```json theme={null}
1218{
1219 "session_id": "abc123",
1220 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1221 "cwd": "/Users/...",
1222 "hook_event_name": "SubagentStart",
1223 "agent_id": "agent-abc123",
1224 "agent_type": "Explore"
1225}
1226```
1227
1228SubagentStart 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:
1229
1230| Field | Description |
1231| :------------------ | :------------------------------------- |
1232| `additionalContext` | String added to the subagent's context |
1233
1234```json theme={null}
1235{
1236 "hookSpecificOutput": {
1237 "hookEventName": "SubagentStart",
1238 "additionalContext": "Follow security guidelines for this task"
1239 }
1240}
1241```
1242
1243### SubagentStop
1244
1245Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.
1246
1247#### SubagentStop input
1248
1249In 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.
1250
1251```json theme={null}
1252{
1253 "session_id": "abc123",
1254 "transcript_path": "~/.claude/projects/.../abc123.jsonl",
1255 "cwd": "/Users/...",
1256 "permission_mode": "default",
1257 "hook_event_name": "SubagentStop",
1258 "stop_hook_active": false,
1259 "agent_id": "def456",
1260 "agent_type": "Explore",
1261 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
1262 "last_assistant_message": "Analysis complete. Found 3 potential issues..."
1263}
1264```
1265
1266SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).
1267
1268### Stop
1269
1270Runs when the main Claude Code agent has finished responding. Does not run if
1271the stoppage occurred due to a user interrupt. API errors fire
1272[StopFailure](#stopfailure) instead.
1273
1274#### Stop input
1275
1276In 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.
1277
1278```json theme={null}
1279{
1280 "session_id": "abc123",
1281 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1282 "cwd": "/Users/...",
1283 "permission_mode": "default",
1284 "hook_event_name": "Stop",
1285 "stop_hook_active": true,
1286 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1287}
1288```
1289
1290#### Stop decision control
1291
1292`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:
1293
1294| Field | Description |
1295| :--------- | :------------------------------------------------------------------------- |
1296| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |
1297| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |
1298
1299```json theme={null}
1300{
1301 "decision": "block",
1302 "reason": "Must be provided when Claude is blocked from stopping"
1303}
1304```
1305
1306### StopFailure
1307
1308Runs 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.
1309
1310#### StopFailure input
1311
1312In 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.
1313
1314| Field | Description |
1315| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1316| `error` | Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |
1317| `error_details` | Additional details about the error, when available |
1318| `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"` |
1319
1320```json theme={null}
1321{
1322 "session_id": "abc123",
1323 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1324 "cwd": "/Users/...",
1325 "hook_event_name": "StopFailure",
1326 "error": "rate_limit",
1327 "error_details": "429 Too Many Requests",
1328 "last_assistant_message": "API Error: Rate limit reached"
1329}
1330```
1331
1332StopFailure hooks have no decision control. They run for notification and logging purposes only.
1333
1334### TeammateIdle
1335
1336Runs 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.
1337
1338When 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.
1339
1340#### TeammateIdle input
1341
1342In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
1343
1344```json theme={null}
1345{
1346 "session_id": "abc123",
1347 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1348 "cwd": "/Users/...",
1349 "permission_mode": "default",
1350 "hook_event_name": "TeammateIdle",
1351 "teammate_name": "researcher",
1352 "team_name": "my-project"
1353}
1354```
1355
1356| Field | Description |
1357| :-------------- | :-------------------------------------------- |
1358| `teammate_name` | Name of the teammate that is about to go idle |
1359| `team_name` | Name of the team |
1360
1361#### TeammateIdle decision control
1362
1363TeammateIdle hooks support two ways to control teammate behavior:
1364
1365* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.
1366* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1367
1368This example checks that a build artifact exists before allowing a teammate to go idle:
1369
1370```bash theme={null}
1371#!/bin/bash
1372
1373if [ ! -f "./dist/output.js" ]; then
1374 echo "Build artifact missing. Run the build before stopping." >&2
1375 exit 2
1376fi
1377
1378exit 0
1379```
1380
1381### TaskCompleted
1382
1383Runs 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.
1384
1385When 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.
1386
1387#### TaskCompleted input
1388
1389In 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`.
1390
1391```json theme={null}
1392{
1393 "session_id": "abc123",
1394 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1395 "cwd": "/Users/...",
1396 "permission_mode": "default",
1397 "hook_event_name": "TaskCompleted",
1398 "task_id": "task-001",
1399 "task_subject": "Implement user authentication",
1400 "task_description": "Add login and signup endpoints",
1401 "teammate_name": "implementer",
1402 "team_name": "my-project"
1403}
1404```
1405
1406| Field | Description |
1407| :----------------- | :------------------------------------------------------ |
1408| `task_id` | Identifier of the task being completed |
1409| `task_subject` | Title of the task |
1410| `task_description` | Detailed description of the task. May be absent |
1411| `teammate_name` | Name of the teammate completing the task. May be absent |
1412| `team_name` | Name of the team. May be absent |
1413
1414#### TaskCompleted decision control
1415
1416TaskCompleted hooks support two ways to control task completion:
1417
1418* **Exit code 2**: the task is not marked as completed and the stderr message is fed back to the model as feedback.
1419* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1420
1421This example runs tests and blocks task completion if they fail:
1422
1423```bash theme={null}
1424#!/bin/bash
1425INPUT=$(cat)
1426TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
1427
1428# Run the test suite
1429if ! npm test 2>&1; then
1430 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
1431 exit 2
1432fi
1433
1434exit 0
1435```
1436
1437### ConfigChange
1438
1439Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
1440
1441ConfigChange 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.
1442
1443The matcher filters on the configuration source:
1444
1445| Matcher | When it fires |
1446| :----------------- | :---------------------------------------- |
1447| `user_settings` | `~/.claude/settings.json` changes |
1448| `project_settings` | `.claude/settings.json` changes |
1449| `local_settings` | `.claude/settings.local.json` changes |
1450| `policy_settings` | Managed policy settings change |
1451| `skills` | A skill file in `.claude/skills/` changes |
1452
1453This example logs all configuration changes for security auditing:
1454
1455```json theme={null}
1456{
1457 "hooks": {
1458 "ConfigChange": [
1459 {
1460 "hooks": [
1461 {
1462 "type": "command",
1463 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
1464 }
1465 ]
1466 }
1467 ]
1468 }
1469}
1470```
1471
1472#### ConfigChange input
1473
1474In 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.
1475
1476```json theme={null}
1477{
1478 "session_id": "abc123",
1479 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1480 "cwd": "/Users/...",
1481 "hook_event_name": "ConfigChange",
1482 "source": "project_settings",
1483 "file_path": "/Users/.../my-project/.claude/settings.json"
1484}
1485```
1486
1487#### ConfigChange decision control
1488
1489ConfigChange 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.
1490
1491| Field | Description |
1492| :--------- | :--------------------------------------------------------------------------------------- |
1493| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |
1494| `reason` | Explanation shown to the user when `decision` is `"block"` |
1495
1496```json theme={null}
1497{
1498 "decision": "block",
1499 "reason": "Configuration changes to project settings require admin approval"
1500}
1501```
1502
1503`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.
1504
1505### CwdChanged
1506
1507Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with [FileChanged](#filechanged) for tools like [direnv](https://direnv.net/) that manage per-directory environment.
1508
1509CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.
1510
1511CwdChanged does not support matchers and fires on every directory change.
1512
1513#### CwdChanged input
1514
1515In addition to the [common input fields](#common-input-fields), CwdChanged hooks receive `old_cwd` and `new_cwd`.
1516
1517```json theme={null}
1518{
1519 "session_id": "abc123",
1520 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
1521 "cwd": "/Users/my-project/src",
1522 "hook_event_name": "CwdChanged",
1523 "old_cwd": "/Users/my-project",
1524 "new_cwd": "/Users/my-project/src"
1525}
1526```
1527
1528#### CwdChanged output
1529
1530In addition to the [JSON output fields](#json-output) available to all hooks, CwdChanged hooks can return `watchPaths` to dynamically set which file paths [FileChanged](#filechanged) watches:
1531
1532| Field | Description |
1533| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1534| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Returning an empty array clears the dynamic list, which is typical when entering a new directory |
1535
1536CwdChanged hooks have no decision control. They cannot block the directory change.
1537
1538### FileChanged
1539
1540Runs when a watched file changes on disk. The `matcher` field in your hook configuration controls which filenames to watch: it is a pipe-separated list of basenames (filenames without directory paths, for example `".envrc|.env"`). The same `matcher` value is also used to filter which hooks run when a file changes, matching against the basename of the changed file. Useful for reloading environment variables when project configuration files are modified.
1541
1542FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.
1543
1544#### FileChanged input
1545
1546In addition to the [common input fields](#common-input-fields), FileChanged hooks receive `file_path` and `event`.
1547
1548| Field | Description |
1549| :---------- | :---------------------------------------------------------------------------------------------- |
1550| `file_path` | Absolute path to the file that changed |
1551| `event` | What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted) |
1552
1553```json theme={null}
1554{
1555 "session_id": "abc123",
1556 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
1557 "cwd": "/Users/my-project",
1558 "hook_event_name": "FileChanged",
1559 "file_path": "/Users/my-project/.envrc",
1560 "event": "change"
1561}
1562```
1563
1564#### FileChanged output
1565
1566In addition to the [JSON output fields](#json-output) available to all hooks, FileChanged hooks can return `watchPaths` to dynamically update which file paths are watched:
1567
1568| Field | Description |
1569| :----------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1570| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Use this when your hook script discovers additional files to watch based on the changed file |
1571
1572FileChanged hooks have no decision control. They cannot block the file change from occurring.
1573
1574### WorktreeCreate
1575
1576When 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.
1577
1578The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`.
1579
1580This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
1581
1582```json theme={null}
1583{
1584 "hooks": {
1585 "WorktreeCreate": [
1586 {
1587 "hooks": [
1588 {
1589 "type": "command",
1590 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
1591 }
1592 ]
1593 }
1594 ]
1595 }
1596}
1597```
1598
1599The 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.
1600
1601#### WorktreeCreate input
1602
1603In 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`).
508 1604
509```json theme={null}1605```json theme={null}
510{1606{
511 "session_id": "abc123",1607 "session_id": "abc123",
512 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1608 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
513 "cwd": "/Users/...",1609 "cwd": "/Users/...",
514 "permission_mode": "default",1610 "hook_event_name": "WorktreeCreate",
515 "hook_event_name": "Notification",1611 "name": "feature-auth"
516 "message": "Claude needs your permission to use Bash",
517 "notification_type": "permission_prompt"
518}1612}
519```1613```
520 1614
521### UserPromptSubmit Input1615#### WorktreeCreate output
1616
1617WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook's success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
1618
1619* **Command hooks** (`type: "command"`): print the path on stdout.
1620* **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
1621
1622If the hook fails or produces no path, worktree creation fails with an error.
1623
1624### WorktreeRemove
1625
1626The 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.
1627
1628Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
522 1629
523```json theme={null}1630```json theme={null}
524{1631{
525 "session_id": "abc123",1632 "hooks": {
526 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1633 "WorktreeRemove": [
527 "cwd": "/Users/...",1634 {
528 "permission_mode": "default",1635 "hooks": [
529 "hook_event_name": "UserPromptSubmit",1636 {
530 "prompt": "Write a function to calculate the factorial of a number"1637 "type": "command",
1638 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
1639 }
1640 ]
1641 }
1642 ]
1643 }
531}1644}
532```1645```
533 1646
534### Stop and SubagentStop Input1647#### WorktreeRemove input
535 1648
536`stop_hook_active` is true when Claude Code is already continuing as a result of1649In 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.
537a stop hook. Check this value or process the transcript to prevent Claude Code
538from running indefinitely.
539 1650
540```json theme={null}1651```json theme={null}
541{1652{
542 "session_id": "abc123",1653 "session_id": "abc123",
543 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1654 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
544 "permission_mode": "default",1655 "cwd": "/Users/...",
545 "hook_event_name": "Stop",1656 "hook_event_name": "WorktreeRemove",
546 "stop_hook_active": true1657 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
547}1658}
548```1659```
549 1660
550### PreCompact Input1661WorktreeRemove 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.
1662
1663### PreCompact
1664
1665Runs before Claude Code is about to run a compact operation.
1666
1667The matcher value indicates whether compaction was triggered manually or automatically:
551 1668
552For `manual`, `custom_instructions` comes from what the user passes into1669| Matcher | When it fires |
553`/compact`. For `auto`, `custom_instructions` is empty.1670| :------- | :------------------------------------------- |
1671| `manual` | `/compact` |
1672| `auto` | Auto-compact when the context window is full |
1673
1674#### PreCompact input
1675
1676In 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.
554 1677
555```json theme={null}1678```json theme={null}
556{1679{
557 "session_id": "abc123",1680 "session_id": "abc123",
558 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1681 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
559 "permission_mode": "default",1682 "cwd": "/Users/...",
560 "hook_event_name": "PreCompact",1683 "hook_event_name": "PreCompact",
561 "trigger": "manual",1684 "trigger": "manual",
562 "custom_instructions": ""1685 "custom_instructions": ""
563}1686}
564```1687```
565 1688
566### SessionStart Input1689### PostCompact
1690
1691Runs 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.
1692
1693The same matcher values apply as for `PreCompact`:
1694
1695| Matcher | When it fires |
1696| :------- | :------------------------------------------------- |
1697| `manual` | After `/compact` |
1698| `auto` | After auto-compact when the context window is full |
1699
1700#### PostCompact input
1701
1702In 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.
567 1703
568```json theme={null}1704```json theme={null}
569{1705{
570 "session_id": "abc123",1706 "session_id": "abc123",
571 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1707 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
572 "permission_mode": "default",1708 "cwd": "/Users/...",
573 "hook_event_name": "SessionStart",1709 "hook_event_name": "PostCompact",
574 "source": "startup"1710 "trigger": "manual",
1711 "compact_summary": "Summary of the compacted conversation..."
575}1712}
576```1713```
577 1714
578### SessionEnd Input1715PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
1716
1717### SessionEnd
1718
1719Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
1720statistics, or saving session state. Supports matchers to filter by exit reason.
1721
1722The `reason` field in the hook input indicates why the session ended:
1723
1724| Reason | Description |
1725| :---------------------------- | :----------------------------------------- |
1726| `clear` | Session cleared with `/clear` command |
1727| `resume` | Session switched via interactive `/resume` |
1728| `logout` | User logged out |
1729| `prompt_input_exit` | User exited while prompt input was visible |
1730| `bypass_permissions_disabled` | Bypass permissions mode was disabled |
1731| `other` | Other exit reasons |
1732
1733#### SessionEnd input
1734
1735In 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.
579 1736
580```json theme={null}1737```json theme={null}
581{1738{
582 "session_id": "abc123",1739 "session_id": "abc123",
583 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1740 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
584 "cwd": "/Users/...",1741 "cwd": "/Users/...",
585 "permission_mode": "default",
586 "hook_event_name": "SessionEnd",1742 "hook_event_name": "SessionEnd",
587 "reason": "exit"1743 "reason": "other"
588}1744}
589```1745```
590 1746
591## Hook Output1747SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
592 1748
593There are two mutually-exclusive ways for hooks to return output back to Claude Code. The output1749SessionEnd 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.
594communicates whether to block and any feedback that should be shown to Claude
595and the user.
596 1750
597### Simple: Exit Code1751```bash theme={null}
598 1752CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
599Hooks communicate status through exit codes, stdout, and stderr:1753```
600
601* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode
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
612<Warning>
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
617#### Exit Code 2 Behavior
618 1754
619| Hook Event | Behavior |1755### Elicitation
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 1756
632### Advanced: JSON Output1757Runs 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.
633 1758
634Hooks can return structured JSON in `stdout` for more sophisticated control.1759The matcher field matches against the MCP server name.
635 1760
636<Warning>1761#### Elicitation input
637 JSON output is only processed when the hook exits with code 0. If your hook
638 exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout`
639 is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o).
640</Warning>
641 1762
642#### Common JSON Fields1763In 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.
643 1764
644All hook types can include these optional fields:1765For form-mode elicitation (the most common case):
645 1766
646```json theme={null}1767```json theme={null}
647{1768{
648 "continue": true, // Whether Claude should continue after hook execution (default: true)1769 "session_id": "abc123",
649 "stopReason": "string", // Message shown when continue is false1770 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
650 1771 "cwd": "/Users/...",
651 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1772 "permission_mode": "default",
652 "systemMessage": "string" // Optional warning message shown to the user1773 "hook_event_name": "Elicitation",
1774 "mcp_server_name": "my-mcp-server",
1775 "message": "Please provide your credentials",
1776 "mode": "form",
1777 "requested_schema": {
1778 "type": "object",
1779 "properties": {
1780 "username": { "type": "string", "title": "Username" }
1781 }
1782 }
653}1783}
654```1784```
655 1785
656If `continue` is false, Claude stops processing after the hooks run.1786For URL-mode elicitation (browser-based authentication):
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
668`stopReason` accompanies `continue` with a reason shown to the user, not shown
669to Claude.
670
671#### `PreToolUse` Decision Control
672 1787
673`PreToolUse` hooks can control whether a tool call proceeds.1788```json theme={null}
674 1789{
675* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown1790 "session_id": "abc123",
676 to the user but not to Claude.1791 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
677* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is1792 "cwd": "/Users/...",
678 shown to Claude.1793 "permission_mode": "default",
679* `"ask"` asks the user to confirm the tool call in the UI.1794 "hook_event_name": "Elicitation",
680 `permissionDecisionReason` is shown to the user but not to Claude.1795 "mcp_server_name": "my-mcp-server",
1796 "message": "Please authenticate",
1797 "mode": "url",
1798 "url": "https://auth.example.com/login"
1799}
1800```
681 1801
682Additionally, hooks can modify tool inputs before execution using `updatedInput`:1802#### Elicitation output
683 1803
684* `updatedInput` allows you to modify the tool's input parameters before the tool executes.1804To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
685* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.
686 1805
687```json theme={null}1806```json theme={null}
688{1807{
689 "hookSpecificOutput": {1808 "hookSpecificOutput": {
690 "hookEventName": "PreToolUse",1809 "hookEventName": "Elicitation",
691 "permissionDecision": "allow"1810 "action": "accept",
692 "permissionDecisionReason": "My reason here",1811 "content": {
693 "updatedInput": {1812 "username": "alice"
694 "field_to_modify": "new value"
695 }1813 }
696 }1814 }
697}1815}
698```1816```
699 1817
700<Note>1818| Field | Values | Description |
701 The `decision` and `reason` fields are deprecated for PreToolUse hooks.1819| :-------- | :---------------------------- | :--------------------------------------------------------------- |
702 Use `hookSpecificOutput.permissionDecision` and1820| `action` | `accept`, `decline`, `cancel` | Whether to accept, decline, or cancel the request |
703 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields1821| `content` | object | Form field values to submit. Only used when `action` is `accept` |
704 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.1822
705</Note>1823Exit code 2 denies the elicitation and shows stderr to the user.
706 1824
707#### `PermissionRequest` Decision Control1825### ElicitationResult
708 1826
709`PermissionRequest` hooks can allow or deny permission requests shown to the user.1827Runs 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.
710 1828
711* For `"behavior": "allow"` you can also optionally pass in an `"updatedInput"` that modifies the tool's input parameters before the tool executes.1829The matcher field matches against the MCP server name.
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.1830
1831#### ElicitationResult input
1832
1833In addition to the [common input fields](#common-input-fields), ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
713 1834
714```json theme={null}1835```json theme={null}
715{1836{
716 "hookSpecificOutput": {1837 "session_id": "abc123",
717 "hookEventName": "PermissionRequest",1838 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
718 "decision": {1839 "cwd": "/Users/...",
719 "behavior": "allow",1840 "permission_mode": "default",
720 "updatedInput": {1841 "hook_event_name": "ElicitationResult",
721 "command": "npm run lint"1842 "mcp_server_name": "my-mcp-server",
722 }1843 "action": "accept",
723 }1844 "content": { "username": "alice" },
724 }1845 "mode": "form",
1846 "elicitation_id": "elicit-123"
725}1847}
726```1848```
727 1849
728#### `PostToolUse` Decision Control1850#### ElicitationResult output
729
730`PostToolUse` hooks can provide feedback to Claude after tool execution.
731 1851
732* `"block"` automatically prompts Claude with `reason`.1852To override the user's response, return a JSON object with `hookSpecificOutput`:
733* `undefined` does nothing. `reason` is ignored.
734* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.
735 1853
736```json theme={null}1854```json theme={null}
737{1855{
738 "decision": "block" | undefined,
739 "reason": "Explanation for decision",
740 "hookSpecificOutput": {1856 "hookSpecificOutput": {
741 "hookEventName": "PostToolUse",1857 "hookEventName": "ElicitationResult",
742 "additionalContext": "Additional information for Claude"1858 "action": "decline",
1859 "content": {}
743 }1860 }
744}1861}
745```1862```
746 1863
747#### `UserPromptSubmit` Decision Control1864| Field | Values | Description |
1865| :-------- | :---------------------------- | :--------------------------------------------------------------------- |
1866| `action` | `accept`, `decline`, `cancel` | Overrides the user's action |
1867| `content` | object | Overrides form field values. Only meaningful when `action` is `accept` |
1868
1869Exit code 2 blocks the response, changing the effective action to `decline`.
748 1870
749`UserPromptSubmit` hooks can control whether a user prompt is processed and add context.1871## Prompt-based hooks
750 1872
751**Adding context (exit code 0):**1873In 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.
752There are two ways to add context to the conversation:
753 1874
7541. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added1875Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):
755 as context. This is the easiest way to inject information.
756 1876
7572. **JSON with `additionalContext`** (structured): Use the JSON format below for1877* `PermissionRequest`
758 more control. The `additionalContext` field is added as context.1878* `PostToolUse`
1879* `PostToolUseFailure`
1880* `PreToolUse`
1881* `Stop`
1882* `SubagentStop`
1883* `TaskCompleted`
1884* `UserPromptSubmit`
759 1885
760Both methods work with exit code 0. Plain stdout is shown as hook output in1886Events that support `command` and `http` hooks but not `prompt` or `agent`:
761the transcript; `additionalContext` is added more discretely.
762 1887
763**Blocking prompts:**1888* `ConfigChange`
1889* `CwdChanged`
1890* `Elicitation`
1891* `ElicitationResult`
1892* `FileChanged`
1893* `InstructionsLoaded`
1894* `Notification`
1895* `PostCompact`
1896* `PreCompact`
1897* `SessionEnd`
1898* `StopFailure`
1899* `SubagentStart`
1900* `TeammateIdle`
1901* `WorktreeCreate`
1902* `WorktreeRemove`
764 1903
765* `"decision": "block"` prevents the prompt from being processed. The submitted1904`SessionStart` supports only `command` hooks.
766 prompt is erased from context. `"reason"` is shown to the user but not added1905
767 to context.1906### How prompt-based hooks work
768* `"decision": undefined` (or omitted) allows the prompt to proceed normally.1907
1908Instead of executing a Bash command, prompt-based hooks:
1909
19101. Send the hook input and your prompt to a Claude model, Haiku by default
19112. The LLM responds with structured JSON containing a decision
19123. Claude Code processes the decision automatically
1913
1914### Prompt hook configuration
1915
1916Set `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.
1917
1918This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
769 1919
770```json theme={null}1920```json theme={null}
771{1921{
772 "decision": "block" | undefined,1922 "hooks": {
773 "reason": "Explanation for decision",1923 "Stop": [
774 "hookSpecificOutput": {1924 {
775 "hookEventName": "UserPromptSubmit",1925 "hooks": [
776 "additionalContext": "My additional context here"1926 {
1927 "type": "prompt",
1928 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."
1929 }
1930 ]
1931 }
1932 ]
777 }1933 }
778}1934}
779```1935```
780 1936
781<Note>1937| Field | Required | Description |
782 The JSON format is not required for simple use cases. To add context, you can1938| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
783 just print plain text to stdout with exit code 0. Use JSON when you need to1939| `type` | yes | Must be `"prompt"` |
784 block prompts or want more structured control.1940| `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 |
785</Note>1941| `model` | no | Model to use for evaluation. Defaults to a fast model |
786 1942| `timeout` | no | Timeout in seconds. Default: 30 |
787#### `Stop`/`SubagentStop` Decision Control
788 1943
789`Stop` and `SubagentStop` hooks can control whether Claude must continue.1944### Response schema
790 1945
791* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1946The LLM must respond with JSON containing:
792 to know how to proceed.
793* `undefined` allows Claude to stop. `reason` is ignored.
794 1947
795```json theme={null}1948```json theme={null}
796{1949{
797 "decision": "block" | undefined,1950 "ok": true | false,
798 "reason": "Must be provided when Claude is blocked from stopping"1951 "reason": "Explanation for the decision"
799}1952}
800```1953```
801 1954
802#### `SessionStart` Decision Control1955| Field | Description |
1956| :------- | :--------------------------------------------------------- |
1957| `ok` | `true` allows the action, `false` prevents it |
1958| `reason` | Required when `ok` is `false`. Explanation shown to Claude |
803 1959
804`SessionStart` hooks allow you to load in context at the start of a session.1960### Example: Multi-criteria Stop hook
805 1961
806* `"hookSpecificOutput.additionalContext"` adds the string to the context.1962This `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:
807* Multiple hooks' `additionalContext` values are concatenated.
808 1963
809```json theme={null}1964```json theme={null}
810{1965{
811 "hookSpecificOutput": {1966 "hooks": {
812 "hookEventName": "SessionStart",1967 "Stop": [
813 "additionalContext": "My additional context here"1968 {
1969 "hooks": [
1970 {
1971 "type": "prompt",
1972 "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.",
1973 "timeout": 30
1974 }
1975 ]
1976 }
1977 ]
814 }1978 }
815}1979}
816```1980```
817 1981
818#### `SessionEnd` Decision Control1982## Agent-based hooks
819
820`SessionEnd` hooks run when a session ends. They cannot block session termination
821but can perform cleanup tasks.
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 1983
875#### JSON Output Example: UserPromptSubmit to Add Context and Validation1984Agent-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.
876 1985
877<Note>1986### How agent hooks work
878 For `UserPromptSubmit` hooks, you can inject context using either method:
879 1987
880 * **Plain text stdout** with exit code 0: Simplest approach—just print text1988When an agent hook fires:
881 * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts,
882 or `additionalContext` for structured context injection
883 1989
884 Remember: Exit code 2 only uses `stderr` for the error message. To block using19901. Claude Code spawns a subagent with your prompt and the hook's JSON input
885 JSON (with a custom reason), use `"decision": "block"` with exit code 0.19912. The subagent can use tools like Read, Grep, and Glob to investigate
886</Note>19923. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision
19934. Claude Code processes the decision the same way as a prompt hook
887 1994
888```python theme={null}1995Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.
889#!/usr/bin/env python3
890import json
891import sys
892import re
893import datetime
894
895# Load input from stdin
896try:
897 input_data = json.load(sys.stdin)
898except json.JSONDecodeError as e:
899 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
900 sys.exit(1)
901
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 }
916 print(json.dumps(output))
917 sys.exit(0)
918 1996
919# Add current time to context1997### Agent hook configuration
920context = f"Current time: {datetime.datetime.now()}"
921print(context)
922 1998
923"""1999Set `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:
924The following is also equivalent:
925print(json.dumps({
926 "hookSpecificOutput": {
927 "hookEventName": "UserPromptSubmit",
928 "additionalContext": context,
929 },
930}))
931"""
932 2000
933# Allow the prompt to proceed with the additional context2001| Field | Required | Description |
934sys.exit(0)2002| :-------- | :------- | :------------------------------------------------------------------------------------------ |
935```2003| `type` | yes | Must be `"agent"` |
2004| `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON |
2005| `model` | no | Model to use. Defaults to a fast model |
2006| `timeout` | no | Timeout in seconds. Default: 60 |
936 2007
937#### JSON Output Example: PreToolUse with Approval2008The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.
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 2009
971## Working with MCP Tools2010This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
972 2011
973Claude Code hooks work seamlessly with2012```json theme={null}
974[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers2013{
975provide tools, they appear with a special naming pattern that you can match in2014 "hooks": {
976your hooks.2015 "Stop": [
2016 {
2017 "hooks": [
2018 {
2019 "type": "agent",
2020 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",
2021 "timeout": 120
2022 }
2023 ]
2024 }
2025 ]
2026 }
2027}
2028```
977 2029
978### MCP Tool Naming2030## Run hooks in the background
979 2031
980MCP tools follow the pattern `mcp__<server>__<tool>`, for example:2032By 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.
981 2033
982* `mcp__memory__create_entities` - Memory server's create entities tool2034### Configure an async hook
983* `mcp__filesystem__read_file` - Filesystem server's read file tool
984* `mcp__github__search_repositories` - GitHub server's search tool
985 2035
986### Configuring Hooks for MCP Tools2036Add `"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.
987 2037
988You can target specific MCP tools or entire MCP servers:2038This 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:
989 2039
990```json theme={null}2040```json theme={null}
991{2041{
992 "hooks": {2042 "hooks": {
993 "PreToolUse": [2043 "PostToolUse": [
994 {
995 "matcher": "mcp__memory__.*",
996 "hooks": [
997 {
998 "type": "command",
999 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
1000 }
1001 ]
1002 },
1003 {2044 {
1004 "matcher": "mcp__.*__write.*",2045 "matcher": "Write",
1005 "hooks": [2046 "hooks": [
1006 {2047 {
1007 "type": "command",2048 "type": "command",
1008 "command": "/home/user/scripts/validate-mcp-write.py"2049 "command": "/path/to/run-tests.sh",
2050 "async": true,
2051 "timeout": 120
1009 }2052 }
1010 ]2053 ]
1011 }2054 }
1014}2057}
1015```2058```
1016 2059
1017## Examples2060The `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 2061
1023## Security Considerations2062### How async hooks execute
1024 2063
1025### Disclaimer2064When 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 2065
1027**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on2066After 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 2067
1030* You are solely responsible for the commands you configure2068Async 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 2069
1037Always review and understand any hook commands before adding them to your2070### Example: run tests after file changes
1038configuration.
1039 2071
1040### Security Best Practices2072This 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 2073
1042Here are some key practices for writing more secure hooks:2074```bash theme={null}
2075#!/bin/bash
2076# run-tests-async.sh
1043 2077
10441. **Validate and sanitize inputs** - Never trust input data blindly2078# Read hook input from stdin
10452. **Always quote shell variables** - Use `"$VAR"` not `$VAR`2079INPUT=$(cat)
10463. **Block path traversal** - Check for `..` in file paths2080FILE_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 2081
1051### Configuration Safety2082# Only run tests for source files
2083if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
2084 exit 0
2085fi
1052 2086
1053Direct edits to hooks in settings files don't take effect immediately. Claude2087# Run tests and report results via systemMessage
1054Code:2088RESULT=$(npm test 2>&1)
2089EXIT_CODE=$?
1055 2090
10561. Captures a snapshot of hooks at startup2091if [ $EXIT_CODE -eq 0 ]; then
10572. Uses this snapshot throughout the session2092 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
10583. Warns if hooks are modified externally2093else
10594. Requires review in `/hooks` menu for changes to apply2094 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
2095fi
2096```
1060 2097
1061This prevents malicious hook modifications from affecting your current session.2098Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:
1062 2099
1063## Hook Execution Details2100```json theme={null}
2101{
2102 "hooks": {
2103 "PostToolUse": [
2104 {
2105 "matcher": "Write|Edit",
2106 "hooks": [
2107 {
2108 "type": "command",
2109 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",
2110 "async": true,
2111 "timeout": 300
2112 }
2113 ]
2114 }
2115 ]
2116 }
2117}
2118```
1064 2119
1065* **Timeout**: 60-second execution limit by default, configurable per command.2120### 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 2121
1079## Debugging2122Async hooks have several constraints compared to synchronous hooks:
1080 2123
1081### Basic Troubleshooting2124* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.
2125* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
2126* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.
2127* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
1082 2128
1083If your hooks aren't working:2129## Security considerations
1084 2130
10851. **Check configuration** - Run `/hooks` to see if your hook is registered2131### 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 2132
1091Common issues:2133Command hooks run with your system user's full permissions.
1092 2134
1093* **Quotes not escaped** - Use `\"` inside JSON strings2135<Warning>
1094* **Wrong matcher** - Check tool names match exactly (case-sensitive)2136 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 scripts2137</Warning>
1096 2138
1097### Advanced Debugging2139### Security best practices
1098 2140
1099For complex hook issues:2141Keep these practices in mind when writing hooks:
1100 2142
11011. **Inspect hook execution** - Use `claude --debug` to see detailed hook2143* **Validate and sanitize inputs**: never trust input data blindly
1102 execution2144* **Always quote shell variables**: use `"$VAR"` not `$VAR`
11032. **Validate JSON schemas** - Test hook input/output with external tools2145* **Block path traversal**: check for `..` in file paths
11043. **Check environment variables** - Verify Claude Code's environment is correct2146* **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 inputs2147* **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 2148
1110### Debug Output Example2149## Windows PowerShell tool
1111 2150
1112Use `claude --debug` to see hook execution details:2151On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (5.1).
1113 2152
2153```json theme={null}
2154{
2155 "hooks": {
2156 "PostToolUse": [
2157 {
2158 "matcher": "Write",
2159 "hooks": [
2160 {
2161 "type": "command",
2162 "shell": "powershell",
2163 "command": "Write-Host 'File written'"
2164 }
2165 ]
2166 }
2167 ]
2168 }
2169}
1114```2170```
2171
2172## Debug hooks
2173
2174Run `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.
2175
2176```text theme={null}
1115[DEBUG] Executing hooks for PostToolUse:Write2177[DEBUG] Executing hooks for PostToolUse:Write
1116[DEBUG] Getting matching hook commands for PostToolUse with query: Write2178[DEBUG] Getting matching hook commands for PostToolUse with query: Write
1117[DEBUG] Found 1 hook matchers in settings2179[DEBUG] Found 1 hook matchers in settings
1118[DEBUG] Matched 1 hooks for query "Write"2180[DEBUG] Matched 1 hooks for query "Write"
1119[DEBUG] Found 1 hook commands to execute2181[DEBUG] Found 1 hook commands to execute
1120[DEBUG] Executing hook command: <Your command> with timeout 60000ms2182[DEBUG] Executing hook command: <Your command> with timeout 600000ms
1121[DEBUG] Hook command completed with status 0: <Your stdout>2183[DEBUG] Hook command completed with status 0: <Your stdout>
1122```2184```
1123 2185
1124Progress messages appear in verbose mode (ctrl+o) showing:2186For 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