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, 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 or LLM prompts that execute automatically at specific points in Claude Code's lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks and MCP tool hooks. If you're setting up hooks for the first time, start with the [guide](/en/hooks-guide) instead.
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, this arrives on stdin. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:
14* `.claude/settings.json` - Project settings
15* `.claude/settings.local.json` - Local project settings (not committed)
16* Enterprise managed policy settings
17 18
18<Note>19<div style={{maxWidth: "500px", margin: "0 auto"}}>
19 Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration).20 <Frame>
20</Note>21 <img src="https://mintcdn.com/claude-code/rsuu-ovdPNos9Dnn/images/hooks-lifecycle.svg?fit=max&auto=format&n=rsuu-ovdPNos9Dnn&q=85&s=ce5f1225339bbccdfbb52e99205db912" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop to SessionEnd, with WorktreeCreate and WorktreeRemove as standalone setup and teardown events" data-og-width="520" width="520" data-og-height="1020" height="1020" data-path="images/hooks-lifecycle.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/rsuu-ovdPNos9Dnn/images/hooks-lifecycle.svg?w=280&fit=max&auto=format&n=rsuu-ovdPNos9Dnn&q=85&s=7c7143c65492c1beb6bc66f5d206ba15 280w, https://mintcdn.com/claude-code/rsuu-ovdPNos9Dnn/images/hooks-lifecycle.svg?w=560&fit=max&auto=format&n=rsuu-ovdPNos9Dnn&q=85&s=dafaebf8f789f94edbf6bd66853c69df 560w, https://mintcdn.com/claude-code/rsuu-ovdPNos9Dnn/images/hooks-lifecycle.svg?w=840&fit=max&auto=format&n=rsuu-ovdPNos9Dnn&q=85&s=2caa51d2d95596f1f80b92e3f5f534fa 840w, https://mintcdn.com/claude-code/rsuu-ovdPNos9Dnn/images/hooks-lifecycle.svg?w=1100&fit=max&auto=format&n=rsuu-ovdPNos9Dnn&q=85&s=614def559f34f9b0c1dec93739d96b64 1100w, https://mintcdn.com/claude-code/rsuu-ovdPNos9Dnn/images/hooks-lifecycle.svg?w=1650&fit=max&auto=format&n=rsuu-ovdPNos9Dnn&q=85&s=ca45b85fdd8b2da81c69d12c453230cb 1650w, https://mintcdn.com/claude-code/rsuu-ovdPNos9Dnn/images/hooks-lifecycle.svg?w=2500&fit=max&auto=format&n=rsuu-ovdPNos9Dnn&q=85&s=7fd92d6b9713493f59962c9f295c9d2f 2500w" />
22 </Frame>
23</div>
21 24
22### Structure25The 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.
23 26
24Hooks are organized by matchers, where each matcher can have multiple hooks: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| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |
40| `TaskCompleted` | When a task is being marked as completed |
41| `ConfigChange` | When a configuration file changes during a session |
42| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |
43| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |
44| `PreCompact` | Before context compaction |
45| `SessionEnd` | When a session terminates |
46
47### How a hook resolves
48
49To 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:
25 50
26```json theme={null}51```json theme={null}
27{52{
28 "hooks": {53 "hooks": {
29 "EventName": [54 "PreToolUse": [
30 {55 {
31 "matcher": "ToolPattern",56 "matcher": "Bash",
32 "hooks": [57 "hooks": [
33 {58 {
34 "type": "command",59 "type": "command",
35 "command": "your-command-here"60 "command": ".claude/hooks/block-rm.sh"
36 }61 }
37 ]62 ]
38 }63 }
41}66}
42```67```
43 68
44* **matcher**: Pattern to match tool names, case-sensitive (only applicable for69The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:
45 `PreToolUse`, `PermissionRequest`, and `PostToolUse`)
46 * Simple strings match exactly: `Write` matches only the Write tool
47 * Supports regex: `Edit|Write` or `Notebook.*`
48 * Use `*` to match all tools. You can also use empty string (`""`) or leave
49 `matcher` blank.
50* **hooks**: Array of hooks to execute when the pattern matches
51 * `type`: Hook execution type - `"command"` for bash commands or `"prompt"` for LLM-based evaluation
52 * `command`: (For `type: "command"`) The bash command to execute (can use `$CLAUDE_PROJECT_DIR` environment variable)
53 * `prompt`: (For `type: "prompt"`) The prompt to send to the LLM for evaluation
54 * `timeout`: (Optional) How long a hook should run, in seconds, before canceling that specific hook
55
56For events like `UserPromptSubmit`, `Stop`, and `SubagentStop`
57that don't use matchers, you can omit the matcher field:
58 70
59```json theme={null}71```bash theme={null}
60{72#!/bin/bash
61 "hooks": {73# .claude/hooks/block-rm.sh
62 "UserPromptSubmit": [74COMMAND=$(jq -r '.tool_input.command')
63 {75
64 "hooks": [76if echo "$COMMAND" | grep -q 'rm -rf'; then
65 {77 jq -n '{
66 "type": "command",78 hookSpecificOutput: {
67 "command": "/path/to/prompt-validator.py"79 hookEventName: "PreToolUse",
68 }80 permissionDecision: "deny",
69 ]81 permissionDecisionReason: "Destructive command blocked by hook"
70 }
71 ]
72 }82 }
73}83 }'
84else
85 exit 0 # allow the command
86fi
74```87```
75 88
76### Project-Specific Hook Scripts89Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
77 90
78You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when91<Frame>
79Claude Code spawns the hook command) to reference scripts stored in your project,92 <img src="https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=5bb890134390ecd0581477cf41ef730b" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" data-og-width="780" width="780" data-og-height="290" height="290" data-path="images/hook-resolution.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=280&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=5dcaecd24c260b8a90365d74e2c1fcda 280w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=560&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=c03d91c279f01d92e58ddd70fdbe66f2 560w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=840&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=1be57a4819cbb949a5ea9d08a05c9ecd 840w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=1100&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=0e9dd1807dc7a5c56011d0889b0d5208 1100w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=1650&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=69496ac02e70fabfece087ba31a1dcfc 1650w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=2500&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=a012346cb46a33b86580348802055267 2500w" />
80ensuring they work regardless of Claude's current directory:93</Frame>
81 94
82```json theme={null}95<Steps>
83{96 <Step title="Event fires">
84 "hooks": {97 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
85 "PostToolUse": [98
86 {99 ```json theme={null}
87 "matcher": "Write|Edit",100 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
88 "hooks": [101 ```
102 </Step>
103
104 <Step title="Matcher checks">
105 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.
106 </Step>
107
108 <Step title="Hook handler runs">
109 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:
110
111 ```json theme={null}
89 {112 {
90 "type": "command",113 "hookSpecificOutput": {
91 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"114 "hookEventName": "PreToolUse",
92 }115 "permissionDecision": "deny",
93 ]116 "permissionDecisionReason": "Destructive command blocked by hook"
94 }117 }
95 ]
96 }118 }
97}119 ```
98```120
121 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.
122 </Step>
123
124 <Step title="Claude Code acts on the result">
125 Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.
126 </Step>
127</Steps>
128
129The [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.
130
131## Configuration
132
133Hooks are defined in JSON settings files. The configuration has three levels of nesting:
99 134
100### Plugin hooks1351. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop`
1362. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool"
1373. Define one or more [hook handlers](#hook-handler-fields) to run when matched
101 138
102[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.139See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.
103 140
104**How plugin hooks work**:141<Note>
142 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, prompt, or agent that runs. "Hook" on its own refers to the general feature.
143</Note>
144
145### Hook locations
146
147Where you define a hook determines its scope:
148
149| Location | Scope | Shareable |
150| :--------------------------------------------------------- | :---------------------------- | :--------------------------------- |
151| `~/.claude/settings.json` | All your projects | No, local to your machine |
152| `.claude/settings.json` | Single project | Yes, can be committed to the repo |
153| `.claude/settings.local.json` | Single project | No, gitignored |
154| Managed policy settings | Organization-wide | Yes, admin-controlled |
155| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |
156| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |
157
158For 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).
159
160### Matcher patterns
161
162The `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:
105 163
106* 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.164| Event | What the matcher filters | Example matcher values |
107* When a plugin is enabled, its hooks are merged with user and project hooks165| :---------------------------------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |
108* Multiple hooks from different sources can respond to the same event166| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
109* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files167| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |
168| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |
169| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |
170| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |
171| `PreCompact` | what triggered compaction | `manual`, `auto` |
172| `SubagentStop` | agent type | same values as `SubagentStart` |
173| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |
174| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |
110 175
111**Example plugin hook configuration**:176The 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.
177
178This example runs a linting script only when Claude writes or edits a file:
112 179
113```json theme={null}180```json theme={null}
114{181{
115 "description": "Automatic code formatting",
116 "hooks": {182 "hooks": {
117 "PostToolUse": [183 "PostToolUse": [
118 {184 {
119 "matcher": "Write|Edit",185 "matcher": "Edit|Write",
120 "hooks": [186 "hooks": [
121 {187 {
122 "type": "command",188 "type": "command",
123 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",189 "command": "/path/to/lint-check.sh"
124 "timeout": 30
125 }190 }
126 ]191 ]
127 }192 }
130}195}
131```196```
132 197
133<Note>198`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, and `WorktreeRemove` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
134 Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.
135</Note>
136
137<Note>
138 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.
139</Note>
140
141**Environment variables for plugins**:
142
143* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory
144* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)
145* All standard environment variables are available
146 199
147See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.200#### Match MCP tools
148 201
149## Prompt-Based Hooks202[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.
150 203
151In 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.204MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
152 205
153### How prompt-based hooks work206* `mcp__memory__create_entities`: Memory server's create entities tool
207* `mcp__filesystem__read_file`: Filesystem server's read file tool
208* `mcp__github__search_repositories`: GitHub server's search tool
154 209
155Instead of executing a bash command, prompt-based hooks:210Use regex patterns to target specific MCP tools or groups of tools:
156 211
1571. Send the hook input and your prompt to a fast LLM (Haiku)212* `mcp__memory__.*` matches all tools from the `memory` server
1582. The LLM responds with structured JSON containing a decision213* `mcp__.*__write.*` matches any tool containing "write" from any server
1593. Claude Code processes the decision automatically
160 214
161### Configuration215This example logs all memory server operations and validates write operations from any MCP server:
162 216
163```json theme={null}217```json theme={null}
164{218{
165 "hooks": {219 "hooks": {
166 "Stop": [220 "PreToolUse": [
167 {221 {
222 "matcher": "mcp__memory__.*",
168 "hooks": [223 "hooks": [
169 {224 {
170 "type": "prompt",225 "type": "command",
171 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."226 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
227 }
228 ]
229 },
230 {
231 "matcher": "mcp__.*__write.*",
232 "hooks": [
233 {
234 "type": "command",
235 "command": "/home/user/scripts/validate-mcp-write.py"
172 }236 }
173 ]237 ]
174 }238 }
177}241}
178```242```
179 243
180**Fields:**244### Hook handler fields
181 245
182* `type`: Must be `"prompt"`246Each object in the inner `hooks` array is a hook handler: the shell command, LLM prompt, or agent that runs when the matcher matches. There are three types:
183* `prompt`: The prompt text to send to the LLM
184 * Use `$ARGUMENTS` as a placeholder for the hook input JSON
185 * If `$ARGUMENTS` is not present, input JSON is appended to the prompt
186* `timeout`: (Optional) Timeout in seconds (default: 30 seconds)
187 247
188### Response schema248* **[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.
249* **[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).
250* **[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).
189 251
190The LLM must respond with JSON containing:252#### Common fields
191 253
192```json theme={null}254These fields apply to all hook types:
193{
194 "decision": "approve" | "block",
195 "reason": "Explanation for the decision",
196 "continue": false, // Optional: stops Claude entirely
197 "stopReason": "Message shown to user", // Optional: custom stop message
198 "systemMessage": "Warning or context" // Optional: shown to user
199}
200```
201 255
202**Response fields:**256| Field | Required | Description |
257| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
258| `type` | yes | `"command"`, `"prompt"`, or `"agent"` |
259| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |
260| `statusMessage` | no | Custom spinner message displayed while the hook runs |
261| `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) |
203 262
204* `decision`: `"approve"` allows the action, `"block"` prevents it263#### Command hook fields
205* `reason`: Explanation shown to Claude when decision is `"block"`
206* `continue`: (Optional) If `false`, stops Claude's execution entirely
207* `stopReason`: (Optional) Message shown when `continue` is false
208* `systemMessage`: (Optional) Additional message shown to the user
209 264
210### Supported hook events265In addition to the [common fields](#common-fields), command hooks accept these fields:
211 266
212Prompt-based hooks work with any hook event, but are most useful for:267| Field | Required | Description |
268| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------ |
269| `command` | yes | Shell command to execute |
270| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |
213 271
214* **Stop**: Intelligently decide if Claude should continue working272#### Prompt and agent hook fields
215* **SubagentStop**: Evaluate if a subagent has completed its task
216* **UserPromptSubmit**: Validate user prompts with LLM assistance
217* **PreToolUse**: Make context-aware permission decisions
218* **PermissionRequest**: Intelligently allow or deny permission dialogs
219 273
220### Example: Intelligent Stop hook274In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:
221 275
222```json theme={null}276| Field | Required | Description |
223{277| :------- | :------- | :------------------------------------------------------------------------------------------ |
278| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |
279| `model` | no | Model to use for evaluation. Defaults to a fast model |
280
281All matching hooks run in parallel, and identical handlers are deduplicated automatically. Handlers run in the current directory with Claude Code's environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
282
283### Reference scripts by path
284
285Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
286
287* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.
288* `${CLAUDE_PLUGIN_ROOT}`: the plugin's root directory, for scripts bundled with a [plugin](/en/plugins).
289
290<Tabs>
291 <Tab title="Project scripts">
292 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:
293
294 ```json theme={null}
295 {
224 "hooks": {296 "hooks": {
225 "Stop": [297 "PostToolUse": [
226 {298 {
299 "matcher": "Write|Edit",
227 "hooks": [300 "hooks": [
228 {301 {
229 "type": "prompt",302 "type": "command",
230 "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\"}",303 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
231 "timeout": 30
232 }304 }
233 ]305 ]
234 }306 }
235 ]307 ]
236 }308 }
237}309 }
238```310 ```
311 </Tab>
239 312
240### Example: SubagentStop with custom logic313 <Tab title="Plugin scripts">
314 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.
241 315
242```json theme={null}316 This example runs a formatting script bundled with the plugin:
243{317
318 ```json theme={null}
319 {
320 "description": "Automatic code formatting",
244 "hooks": {321 "hooks": {
245 "SubagentStop": [322 "PostToolUse": [
246 {323 {
324 "matcher": "Write|Edit",
247 "hooks": [325 "hooks": [
248 {326 {
249 "type": "prompt",327 "type": "command",
250 "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\"}"328 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
329 "timeout": 30
251 }330 }
252 ]331 ]
253 }332 }
254 ]333 ]
255 }334 }
256}335 }
257```336 ```
258 337
259### Comparison with bash command hooks338 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.
339 </Tab>
340</Tabs>
260 341
261| Feature | Bash Command Hooks | Prompt-Based Hooks |342### Hooks in skills and agents
262| --------------------- | ----------------------- | ------------------------------ |
263| **Execution** | Runs bash script | Queries LLM |
264| **Decision logic** | You implement in code | LLM evaluates context |
265| **Setup complexity** | Requires script file | Configure prompt |
266| **Context awareness** | Limited to script logic | Natural language understanding |
267| **Performance** | Fast (local execution) | Slower (API call) |
268| **Use case** | Deterministic rules | Context-aware decisions |
269 343
270### Best practices344In 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.
271 345
272* **Be specific in prompts**: Clearly state what you want the LLM to evaluate346All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes.
273* **Include decision criteria**: List the factors the LLM should consider
274* **Test your prompts**: Verify the LLM makes correct decisions for your use cases
275* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed
276* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules
277 347
278See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.348Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.
279 349
280## Hook Events350This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
281 351
282### PreToolUse352```yaml theme={null}
353---
354name: secure-operations
355description: Perform operations with security checks
356hooks:
357 PreToolUse:
358 - matcher: "Bash"
359 hooks:
360 - type: command
361 command: "./scripts/security-check.sh"
362---
363```
283 364
284Runs after Claude creates tool parameters and before processing the tool call.365Agents use the same format in their YAML frontmatter.
285 366
286**Common matchers:**367### The `/hooks` menu
287 368
288* `Task` - Subagent tasks (see [subagents documentation](/en/sub-agents))369Type `/hooks` in Claude Code to open the interactive hooks manager, where you can view, add, and delete hooks without editing settings files directly. For a step-by-step walkthrough, see [Set up your first hook](/en/hooks-guide#set-up-your-first-hook) in the guide.
289* `Bash` - Shell commands
290* `Glob` - File pattern matching
291* `Grep` - Content search
292* `Read` - File reading
293* `Edit` - File editing
294* `Write` - File writing
295* `WebFetch`, `WebSearch` - Web operations
296 370
297Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.371Each hook in the menu is labeled with a bracket prefix indicating its source:
298 372
299### PermissionRequest373* `[User]`: from `~/.claude/settings.json`
374* `[Project]`: from `.claude/settings.json`
375* `[Local]`: from `.claude/settings.local.json`
376* `[Plugin]`: from a plugin's `hooks/hooks.json`, read-only
300 377
301Runs when the user is shown a permission dialog.378### Disable or remove hooks
302Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.
303 379
304Recognizes the same matcher values as PreToolUse.380To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it.
305 381
306### PostToolUse382To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file or use the toggle in the `/hooks` menu. There is no way to disable an individual hook while keeping it in the configuration.
307 383
308Runs immediately after a tool completes successfully.384The `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.
309 385
310Recognizes the same matcher values as PreToolUse.386Direct edits to hooks in settings files don't take effect immediately. Claude Code captures a snapshot of hooks at startup and uses it throughout the session. This prevents malicious or accidental hook modifications from taking effect mid-session without your review. If hooks are modified externally, Claude Code warns you and requires review in the `/hooks` menu before changes apply.
311 387
312### Notification388## Hook input and output
313 389
314Runs when Claude Code sends notifications. Supports matchers to filter by notification type.390Hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. This section covers fields and behavior common to all events. Each event's section under [Hook events](#hook-events) includes its specific input schema and decision control options.
315 391
316**Common matchers:**392### Common input fields
317 393
318* `permission_prompt` - Permission requests from Claude Code394All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section:
319* `idle_prompt` - When Claude is waiting for user input (after 60+ seconds of idle time)
320* `auth_success` - Authentication success notifications
321* `elicitation_dialog` - When Claude Code needs input for MCP tool elicitation
322 395
323You can use matchers to run different hooks for different notification types, or omit the matcher to run hooks for all notifications.396| Field | Description |
397| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
398| `session_id` | Current session identifier |
399| `transcript_path` | Path to conversation JSON |
400| `cwd` | Current working directory when the hook is invoked |
401| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |
402| `hook_event_name` | Name of the event that fired |
324 403
325**Example: Different notifications for different types**404For example, a `PreToolUse` hook for a Bash command receives this on stdin:
326 405
327```json theme={null}406```json theme={null}
328{407{
329 "hooks": {408 "session_id": "abc123",
330 "Notification": [409 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
331 {410 "cwd": "/home/user/my-project",
332 "matcher": "permission_prompt",411 "permission_mode": "default",
333 "hooks": [412 "hook_event_name": "PreToolUse",
413 "tool_name": "Bash",
414 "tool_input": {
415 "command": "npm test"
416 }
417}
418```
419
420The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.
421
422### Exit code output
423
424The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.
425
426**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.
427
428**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.
429
430**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.
431
432For example, a hook command script that blocks dangerous Bash commands:
433
434```bash theme={null}
435#!/bin/bash
436# Reads JSON input from stdin, checks the command
437command=$(jq -r '.tool_input.command' < /dev/stdin)
438
439if [[ "$command" == rm* ]]; then
440 echo "Blocked: rm commands are not allowed" >&2
441 exit 2 # Blocking error: tool call is prevented
442fi
443
444exit 0 # Success: tool call proceeds
445```
446
447#### Exit code 2 behavior per event
448
449Exit 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.
450
451| Hook event | Can block? | What happens on exit 2 |
452| :------------------- | :--------- | :---------------------------------------------------------------------------- |
453| `PreToolUse` | Yes | Blocks the tool call |
454| `PermissionRequest` | Yes | Denies the permission |
455| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
456| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
457| `SubagentStop` | Yes | Prevents the subagent from stopping |
458| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |
459| `TaskCompleted` | Yes | Prevents the task from being marked as completed |
460| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |
461| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
462| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
463| `Notification` | No | Shows stderr to user only |
464| `SubagentStart` | No | Shows stderr to user only |
465| `SessionStart` | No | Shows stderr to user only |
466| `SessionEnd` | No | Shows stderr to user only |
467| `PreCompact` | No | Shows stderr to user only |
468| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |
469| `WorktreeRemove` | No | Failures are logged in debug mode only |
470
471### JSON output
472
473Exit 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.
474
475<Note>
476 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.
477</Note>
478
479Your 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.
480
481The JSON object supports three kinds of fields:
482
483* **Universal fields** like `continue` work across all events. These are listed in the table below.
484* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.
485* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.
486
487| Field | Default | Description |
488| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |
489| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |
490| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |
491| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |
492| `systemMessage` | none | Warning message shown to the user |
493
494To stop Claude entirely regardless of event type:
495
496```json theme={null}
497{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
498```
499
500#### Decision control
501
502Not 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:
503
504| Events | Decision pattern | Key fields |
505| :---------------------------------------------------------------------------------- | :------------------- | :-------------------------------------------------------------------------- |
506| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |
507| TeammateIdle, TaskCompleted | Exit code only | Exit code 2 blocks the action, stderr is fed back as feedback |
508| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |
509| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |
510| WorktreeCreate | stdout path | Hook prints absolute path to created worktree. Non-zero exit fails creation |
511| WorktreeRemove, Notification, SessionEnd, PreCompact | None | No decision control. Used for side effects like logging or cleanup |
512
513Here are examples of each pattern in action:
514
515<Tabs>
516 <Tab title="Top-level decision">
517 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:
518
519 ```json theme={null}
334 {520 {
335 "type": "command",521 "decision": "block",
336 "command": "/path/to/permission-alert.sh"522 "reason": "Test suite must pass before proceeding"
337 }523 }
338 ]524 ```
339 },525 </Tab>
526
527 <Tab title="PreToolUse">
528 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.
529
530 ```json theme={null}
340 {531 {
341 "matcher": "idle_prompt",532 "hookSpecificOutput": {
342 "hooks": [533 "hookEventName": "PreToolUse",
534 "permissionDecision": "deny",
535 "permissionDecisionReason": "Database writes are not allowed"
536 }
537 }
538 ```
539 </Tab>
540
541 <Tab title="PermissionRequest">
542 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.
543
544 ```json theme={null}
343 {545 {
344 "type": "command",546 "hookSpecificOutput": {
345 "command": "/path/to/idle-notification.sh"547 "hookEventName": "PermissionRequest",
548 "decision": {
549 "behavior": "allow",
550 "updatedInput": {
551 "command": "npm run lint"
346 }552 }
347 ]
348 }553 }
349 ]
350 }554 }
351}555 }
352```556 ```
557 </Tab>
558</Tabs>
353 559
354### UserPromptSubmit560For 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).
355 561
356Runs when the user submits a prompt, before Claude processes it. This allows you562## Hook events
357to add additional context based on the prompt/conversation, validate prompts, or
358block certain types of prompts.
359 563
360### Stop564Each 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.
361 565
362Runs when the main Claude Code agent has finished responding. Does not run if566### SessionStart
363the stoppage occurred due to a user interrupt.
364 567
365### SubagentStop568Runs 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.
366 569
367Runs when a Claude Code subagent (Task tool call) has finished responding.570SessionStart runs on every session, so keep these hooks fast.
368 571
369### PreCompact572The matcher value corresponds to how the session was initiated:
370 573
371Runs before Claude Code is about to run a compact operation.574| Matcher | When it fires |
575| :-------- | :------------------------------------- |
576| `startup` | New session |
577| `resume` | `--resume`, `--continue`, or `/resume` |
578| `clear` | `/clear` |
579| `compact` | Auto or manual compaction |
372 580
373**Matchers:**581#### SessionStart input
374 582
375* `manual` - Invoked from `/compact`583In 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.
376* `auto` - Invoked from auto-compact (due to full context window)
377 584
378### SessionStart585```json theme={null}
586{
587 "session_id": "abc123",
588 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
589 "cwd": "/Users/...",
590 "permission_mode": "default",
591 "hook_event_name": "SessionStart",
592 "source": "startup",
593 "model": "claude-sonnet-4-6"
594}
595```
379 596
380Runs when Claude Code starts a new session or resumes an existing session (which597#### SessionStart decision control
381currently does start a new session under the hood). Useful for loading in
382development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables.
383 598
384**Matchers:**599Any 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:
385 600
386* `startup` - Invoked from startup601| Field | Description |
387* `resume` - Invoked from `--resume`, `--continue`, or `/resume`602| :------------------ | :------------------------------------------------------------------------ |
388* `clear` - Invoked from `/clear`603| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |
389* `compact` - Invoked from auto or manual compact.604
605```json theme={null}
606{
607 "hookSpecificOutput": {
608 "hookEventName": "SessionStart",
609 "additionalContext": "My additional context here"
610 }
611}
612```
390 613
391#### Persisting environment variables614#### Persist environment variables
392 615
393SessionStart 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.616SessionStart 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.
394 617
395**Example: Setting individual environment variables**618To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:
396 619
397```bash theme={null}620```bash theme={null}
398#!/bin/bash621#!/bin/bash
399 622
400if [ -n "$CLAUDE_ENV_FILE" ]; then623if [ -n "$CLAUDE_ENV_FILE" ]; then
401 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"624 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
402 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"625 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
403 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"626 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
404fi627fi
405 628
406exit 0629exit 0
407```630```
408 631
409**Example: Persisting all environment changes from the hook**632To capture all environment changes from setup commands, compare the exported variables before and after:
410
411When your setup modifies the environment (for example, `nvm use`), capture and persist all changes by diffing the environment:
412 633
413```bash theme={null}634```bash theme={null}
414#!/bin/bash635#!/bin/bash
427exit 0648exit 0
428```649```
429 650
430Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session.651Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
431 652
432<Note>653<Note>
433 `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable.654 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.
434</Note>655</Note>
435 656
436### SessionEnd657### UserPromptSubmit
437
438Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
439statistics, or saving session state.
440
441The `reason` field in the hook input will be one of:
442
443* `clear` - Session cleared with /clear command
444* `logout` - User logged out
445* `prompt_input_exit` - User exited while prompt input was visible
446* `other` - Other exit reasons
447
448## Hook Input
449
450Hooks receive JSON data via stdin containing session information and
451event-specific data:
452 658
453```typescript theme={null}659Runs when the user submits a prompt, before Claude processes it. This allows you
454{660to add additional context based on the prompt/conversation, validate prompts, or
455 // Common fields661block certain types of prompts.
456 session_id: string
457 transcript_path: string // Path to conversation JSON
458 cwd: string // The current working directory when the hook is invoked
459 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", "dontAsk", or "bypassPermissions"
460
461 // Event-specific fields
462 hook_event_name: string
463 ...
464}
465```
466 662
467### PreToolUse Input663#### UserPromptSubmit input
468 664
469The exact schema for `tool_input` depends on the tool.665In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
470 666
471```json theme={null}667```json theme={null}
472{668{
474 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",670 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
475 "cwd": "/Users/...",671 "cwd": "/Users/...",
476 "permission_mode": "default",672 "permission_mode": "default",
477 "hook_event_name": "PreToolUse",673 "hook_event_name": "UserPromptSubmit",
478 "tool_name": "Write",674 "prompt": "Write a function to calculate the factorial of a number"
675}
676```
677
678#### UserPromptSubmit decision control
679
680`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.
681
682There are two ways to add context to the conversation on exit code 0:
683
684* **Plain text stdout**: any non-JSON text written to stdout is added as context
685* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
686
687Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.
688
689To block a prompt, return a JSON object with `decision` set to `"block"`:
690
691| Field | Description |
692| :------------------ | :----------------------------------------------------------------------------------------------------------------- |
693| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |
694| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |
695| `additionalContext` | String added to Claude's context |
696
697```json theme={null}
698{
699 "decision": "block",
700 "reason": "Explanation for decision",
701 "hookSpecificOutput": {
702 "hookEventName": "UserPromptSubmit",
703 "additionalContext": "My additional context here"
704 }
705}
706```
707
708<Note>
709 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
710 block prompts or want more structured control.
711</Note>
712
713### PreToolUse
714
715Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Task`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).
716
717Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.
718
719#### PreToolUse input
720
721In 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:
722
723##### Bash
724
725Executes shell commands.
726
727| Field | Type | Example | Description |
728| :------------------ | :------ | :----------------- | :-------------------------------------------- |
729| `command` | string | `"npm test"` | The shell command to execute |
730| `description` | string | `"Run test suite"` | Optional description of what the command does |
731| `timeout` | number | `120000` | Optional timeout in milliseconds |
732| `run_in_background` | boolean | `false` | Whether to run the command in background |
733
734##### Write
735
736Creates or overwrites a file.
737
738| Field | Type | Example | Description |
739| :---------- | :----- | :-------------------- | :--------------------------------- |
740| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |
741| `content` | string | `"file content"` | Content to write to the file |
742
743##### Edit
744
745Replaces a string in an existing file.
746
747| Field | Type | Example | Description |
748| :------------ | :------ | :-------------------- | :--------------------------------- |
749| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |
750| `old_string` | string | `"original text"` | Text to find and replace |
751| `new_string` | string | `"replacement text"` | Replacement text |
752| `replace_all` | boolean | `false` | Whether to replace all occurrences |
753
754##### Read
755
756Reads file contents.
757
758| Field | Type | Example | Description |
759| :---------- | :----- | :-------------------- | :----------------------------------------- |
760| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |
761| `offset` | number | `10` | Optional line number to start reading from |
762| `limit` | number | `50` | Optional number of lines to read |
763
764##### Glob
765
766Finds files matching a glob pattern.
767
768| Field | Type | Example | Description |
769| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |
770| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |
771| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |
772
773##### Grep
774
775Searches file contents with regular expressions.
776
777| Field | Type | Example | Description |
778| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |
779| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |
780| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |
781| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |
782| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |
783| `-i` | boolean | `true` | Case insensitive search |
784| `multiline` | boolean | `false` | Enable multiline matching |
785
786##### WebFetch
787
788Fetches and processes web content.
789
790| Field | Type | Example | Description |
791| :------- | :----- | :---------------------------- | :----------------------------------- |
792| `url` | string | `"https://example.com/api"` | URL to fetch content from |
793| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |
794
795##### WebSearch
796
797Searches the web.
798
799| Field | Type | Example | Description |
800| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |
801| `query` | string | `"react hooks best practices"` | Search query |
802| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |
803| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |
804
805##### Task
806
807Spawns a [subagent](/en/sub-agents).
808
809| Field | Type | Example | Description |
810| :-------------- | :----- | :------------------------- | :------------------------------------------- |
811| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |
812| `description` | string | `"Find API endpoints"` | Short description of the task |
813| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |
814| `model` | string | `"sonnet"` | Optional model alias to override the default |
815
816#### PreToolUse decision control
817
818`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.
819
820| Field | Description |
821| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |
822| `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm |
823| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |
824| `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 |
825| `additionalContext` | String added to Claude's context before the tool executes |
826
827```json theme={null}
828{
829 "hookSpecificOutput": {
830 "hookEventName": "PreToolUse",
831 "permissionDecision": "allow",
832 "permissionDecisionReason": "My reason here",
833 "updatedInput": {
834 "field_to_modify": "new value"
835 },
836 "additionalContext": "Current environment: production. Proceed with caution."
837 }
838}
839```
840
841<Note>
842 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.
843</Note>
844
845### PermissionRequest
846
847Runs when the user is shown a permission dialog.
848Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.
849
850Matches on tool name, same values as PreToolUse.
851
852#### PermissionRequest input
853
854PermissionRequest 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.
855
856```json theme={null}
857{
858 "session_id": "abc123",
859 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
860 "cwd": "/Users/...",
861 "permission_mode": "default",
862 "hook_event_name": "PermissionRequest",
863 "tool_name": "Bash",
479 "tool_input": {864 "tool_input": {
480 "file_path": "/path/to/file.txt",865 "command": "rm -rf node_modules",
481 "content": "file content"866 "description": "Remove node_modules directory"
482 },867 },
483 "tool_use_id": "toolu_01ABC123..."868 "permission_suggestions": [
869 { "type": "toolAlwaysAllow", "tool": "Bash" }
870 ]
484}871}
485```872```
486 873
487### PostToolUse Input874#### PermissionRequest decision control
875
876`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:
488 877
489The exact schema for `tool_input` and `tool_response` depends on the tool.878| Field | Description |
879| :------------------- | :------------------------------------------------------------------------------------------------------------- |
880| `behavior` | `"allow"` grants the permission, `"deny"` denies it |
881| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |
882| `updatedPermissions` | For `"allow"` only: applies permission rule updates, equivalent to the user selecting an "always allow" option |
883| `message` | For `"deny"` only: tells Claude why the permission was denied |
884| `interrupt` | For `"deny"` only: if `true`, stops Claude |
885
886```json theme={null}
887{
888 "hookSpecificOutput": {
889 "hookEventName": "PermissionRequest",
890 "decision": {
891 "behavior": "allow",
892 "updatedInput": {
893 "command": "npm run lint"
894 }
895 }
896 }
897}
898```
899
900### PostToolUse
901
902Runs immediately after a tool completes successfully.
903
904Matches on tool name, same values as PreToolUse.
905
906#### PostToolUse input
907
908`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.
490 909
491```json theme={null}910```json theme={null}
492{911{
508}927}
509```928```
510 929
511### Notification Input930#### PostToolUse decision control
931
932`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:
933
934| Field | Description |
935| :--------------------- | :----------------------------------------------------------------------------------------- |
936| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |
937| `reason` | Explanation shown to Claude when `decision` is `"block"` |
938| `additionalContext` | Additional context for Claude to consider |
939| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |
940
941```json theme={null}
942{
943 "decision": "block",
944 "reason": "Explanation for decision",
945 "hookSpecificOutput": {
946 "hookEventName": "PostToolUse",
947 "additionalContext": "Additional information for Claude"
948 }
949}
950```
951
952### PostToolUseFailure
953
954Runs 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.
955
956Matches on tool name, same values as PreToolUse.
957
958#### PostToolUseFailure input
959
960PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:
961
962```json theme={null}
963{
964 "session_id": "abc123",
965 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
966 "cwd": "/Users/...",
967 "permission_mode": "default",
968 "hook_event_name": "PostToolUseFailure",
969 "tool_name": "Bash",
970 "tool_input": {
971 "command": "npm test",
972 "description": "Run test suite"
973 },
974 "tool_use_id": "toolu_01ABC123...",
975 "error": "Command exited with non-zero status code 1",
976 "is_interrupt": false
977}
978```
979
980| Field | Description |
981| :------------- | :------------------------------------------------------------------------------ |
982| `error` | String describing what went wrong |
983| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |
984
985#### PostToolUseFailure decision control
986
987`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:
988
989| Field | Description |
990| :------------------ | :------------------------------------------------------------ |
991| `additionalContext` | Additional context for Claude to consider alongside the error |
992
993```json theme={null}
994{
995 "hookSpecificOutput": {
996 "hookEventName": "PostToolUseFailure",
997 "additionalContext": "Additional information about the failure for Claude"
998 }
999}
1000```
1001
1002### Notification
1003
1004Runs 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.
1005
1006Use 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:
1007
1008```json theme={null}
1009{
1010 "hooks": {
1011 "Notification": [
1012 {
1013 "matcher": "permission_prompt",
1014 "hooks": [
1015 {
1016 "type": "command",
1017 "command": "/path/to/permission-alert.sh"
1018 }
1019 ]
1020 },
1021 {
1022 "matcher": "idle_prompt",
1023 "hooks": [
1024 {
1025 "type": "command",
1026 "command": "/path/to/idle-notification.sh"
1027 }
1028 ]
1029 }
1030 ]
1031 }
1032}
1033```
1034
1035#### Notification input
1036
1037In 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.
512 1038
513```json theme={null}1039```json theme={null}
514{1040{
518 "permission_mode": "default",1044 "permission_mode": "default",
519 "hook_event_name": "Notification",1045 "hook_event_name": "Notification",
520 "message": "Claude needs your permission to use Bash",1046 "message": "Claude needs your permission to use Bash",
1047 "title": "Permission needed",
521 "notification_type": "permission_prompt"1048 "notification_type": "permission_prompt"
522}1049}
523```1050```
524 1051
525### UserPromptSubmit Input1052Notification 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:
1053
1054| Field | Description |
1055| :------------------ | :------------------------------- |
1056| `additionalContext` | String added to Claude's context |
1057
1058### SubagentStart
1059
1060Runs when a Claude Code subagent is spawned via the Task tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).
1061
1062#### SubagentStart input
1063
1064In 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).
526 1065
527```json theme={null}1066```json theme={null}
528{1067{
530 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1069 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
531 "cwd": "/Users/...",1070 "cwd": "/Users/...",
532 "permission_mode": "default",1071 "permission_mode": "default",
533 "hook_event_name": "UserPromptSubmit",1072 "hook_event_name": "SubagentStart",
534 "prompt": "Write a function to calculate the factorial of a number"1073 "agent_id": "agent-abc123",
1074 "agent_type": "Explore"
535}1075}
536```1076```
537 1077
538### Stop and SubagentStop Input1078SubagentStart 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:
539 1079
540`stop_hook_active` is true when Claude Code is already continuing as a result of1080| Field | Description |
541a stop hook. Check this value or process the transcript to prevent Claude Code1081| :------------------ | :------------------------------------- |
542from running indefinitely.1082| `additionalContext` | String added to the subagent's context |
1083
1084```json theme={null}
1085{
1086 "hookSpecificOutput": {
1087 "hookEventName": "SubagentStart",
1088 "additionalContext": "Follow security guidelines for this task"
1089 }
1090}
1091```
1092
1093### SubagentStop
1094
1095Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.
1096
1097#### SubagentStop input
1098
1099In 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.
543 1100
544```json theme={null}1101```json theme={null}
545{1102{
546 "session_id": "abc123",1103 "session_id": "abc123",
547 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1104 "transcript_path": "~/.claude/projects/.../abc123.jsonl",
1105 "cwd": "/Users/...",
548 "permission_mode": "default",1106 "permission_mode": "default",
549 "hook_event_name": "Stop",1107 "hook_event_name": "SubagentStop",
550 "stop_hook_active": true1108 "stop_hook_active": false,
1109 "agent_id": "def456",
1110 "agent_type": "Explore",
1111 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
1112 "last_assistant_message": "Analysis complete. Found 3 potential issues..."
551}1113}
552```1114```
553 1115
554### PreCompact Input1116SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).
555 1117
556For `manual`, `custom_instructions` comes from what the user passes into1118### Stop
557`/compact`. For `auto`, `custom_instructions` is empty.1119
1120Runs when the main Claude Code agent has finished responding. Does not run if
1121the stoppage occurred due to a user interrupt.
1122
1123#### Stop input
1124
1125In 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.
558 1126
559```json theme={null}1127```json theme={null}
560{1128{
561 "session_id": "abc123",1129 "session_id": "abc123",
562 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1130 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1131 "cwd": "/Users/...",
563 "permission_mode": "default",1132 "permission_mode": "default",
564 "hook_event_name": "PreCompact",1133 "hook_event_name": "Stop",
565 "trigger": "manual",1134 "stop_hook_active": true,
566 "custom_instructions": ""1135 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1136}
1137```
1138
1139#### Stop decision control
1140
1141`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:
1142
1143| Field | Description |
1144| :--------- | :------------------------------------------------------------------------- |
1145| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |
1146| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |
1147
1148```json theme={null}
1149{
1150 "decision": "block",
1151 "reason": "Must be provided when Claude is blocked from stopping"
567}1152}
568```1153```
569 1154
570### SessionStart Input1155### TeammateIdle
1156
1157Runs 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.
1158
1159When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. TeammateIdle hooks do not support matchers and fire on every occurrence.
1160
1161#### TeammateIdle input
1162
1163In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
571 1164
572```json theme={null}1165```json theme={null}
573{1166{
574 "session_id": "abc123",1167 "session_id": "abc123",
575 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1168 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1169 "cwd": "/Users/...",
576 "permission_mode": "default",1170 "permission_mode": "default",
577 "hook_event_name": "SessionStart",1171 "hook_event_name": "TeammateIdle",
578 "source": "startup"1172 "teammate_name": "researcher",
1173 "team_name": "my-project"
579}1174}
580```1175```
581 1176
582### SessionEnd Input1177| Field | Description |
1178| :-------------- | :-------------------------------------------- |
1179| `teammate_name` | Name of the teammate that is about to go idle |
1180| `team_name` | Name of the team |
1181
1182#### TeammateIdle decision control
1183
1184TeammateIdle hooks use exit codes only, not JSON decision control. This example checks that a build artifact exists before allowing a teammate to go idle:
1185
1186```bash theme={null}
1187#!/bin/bash
1188
1189if [ ! -f "./dist/output.js" ]; then
1190 echo "Build artifact missing. Run the build before stopping." >&2
1191 exit 2
1192fi
1193
1194exit 0
1195```
1196
1197### TaskCompleted
1198
1199Runs 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.
1200
1201When 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. TaskCompleted hooks do not support matchers and fire on every occurrence.
1202
1203#### TaskCompleted input
1204
1205In 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`.
583 1206
584```json theme={null}1207```json theme={null}
585{1208{
586 "session_id": "abc123",1209 "session_id": "abc123",
587 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1210 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
588 "cwd": "/Users/...",1211 "cwd": "/Users/...",
589 "permission_mode": "default",1212 "permission_mode": "default",
590 "hook_event_name": "SessionEnd",1213 "hook_event_name": "TaskCompleted",
591 "reason": "exit"1214 "task_id": "task-001",
1215 "task_subject": "Implement user authentication",
1216 "task_description": "Add login and signup endpoints",
1217 "teammate_name": "implementer",
1218 "team_name": "my-project"
592}1219}
593```1220```
594 1221
595## Hook Output1222| Field | Description |
596 1223| :----------------- | :------------------------------------------------------ |
597There are two mutually exclusive ways for hooks to return output back to Claude Code. The output1224| `task_id` | Identifier of the task being completed |
598communicates whether to block and any feedback that should be shown to Claude1225| `task_subject` | Title of the task |
599and the user.1226| `task_description` | Detailed description of the task. May be absent |
1227| `teammate_name` | Name of the teammate completing the task. May be absent |
1228| `team_name` | Name of the team. May be absent |
600 1229
601### Simple: Exit Code1230#### TaskCompleted decision control
602 1231
603Hooks communicate status through exit codes, stdout, and stderr:1232TaskCompleted hooks use exit codes only, not JSON decision control. This example runs tests and blocks task completion if they fail:
604 1233
605* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode1234```bash theme={null}
606 (ctrl+o), except for `UserPromptSubmit` and `SessionStart`, where stdout is1235#!/bin/bash
607 added to the context. JSON output in `stdout` is parsed for structured control1236INPUT=$(cat)
608 (see [Advanced: JSON Output](#advanced-json-output)).1237TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
609* **Exit code 2**: Blocking error. Only `stderr` is used as the error message
610 and fed back to Claude. The format is `[command]: {stderr}`. JSON in `stdout`
611 is **not** processed for exit code 2. See per-hook-event behavior below.
612* **Other exit codes**: Non-blocking error. `stderr` is shown to the user in verbose mode (ctrl+o) with
613 format `Failed with non-blocking status code: {stderr}`. If `stderr` is empty,
614 it shows `No stderr output`. Execution continues.
615 1238
616<Warning>1239# Run the test suite
617 Reminder: Claude Code does not see stdout if the exit code is 0, except for1240if ! npm test 2>&1; then
618 the `UserPromptSubmit` hook where stdout is injected as context.1241 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
619</Warning>1242 exit 2
1243fi
620 1244
621#### Exit Code 2 Behavior1245exit 0
1246```
622 1247
623| Hook Event | Behavior |1248### ConfigChange
624| ------------------- | ------------------------------------------------------------------ |
625| `PreToolUse` | Blocks the tool call, shows stderr to Claude |
626| `PermissionRequest` | Denies the permission, shows stderr to Claude |
627| `PostToolUse` | Shows stderr to Claude (tool already ran) |
628| `Notification` | N/A, shows stderr to user only |
629| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |
630| `Stop` | Blocks stoppage, shows stderr to Claude |
631| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |
632| `PreCompact` | N/A, shows stderr to user only |
633| `SessionStart` | N/A, shows stderr to user only |
634| `SessionEnd` | N/A, shows stderr to user only |
635 1249
636### Advanced: JSON Output1250Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
637 1251
638Hooks can return structured JSON in `stdout` for more sophisticated control.1252ConfigChange 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.
639 1253
640<Warning>1254The matcher filters on the configuration source:
641 JSON output is only processed when the hook exits with code 0. If your hook
642 exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout`
643 is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o).
644</Warning>
645 1255
646#### Common JSON Fields1256| Matcher | When it fires |
1257| :----------------- | :---------------------------------------- |
1258| `user_settings` | `~/.claude/settings.json` changes |
1259| `project_settings` | `.claude/settings.json` changes |
1260| `local_settings` | `.claude/settings.local.json` changes |
1261| `policy_settings` | Managed policy settings change |
1262| `skills` | A skill file in `.claude/skills/` changes |
647 1263
648All hook types can include these optional fields:1264This example logs all configuration changes for security auditing:
649 1265
650```json theme={null}1266```json theme={null}
651{1267{
652 "continue": true, // Whether Claude should continue after hook execution (default: true)1268 "hooks": {
653 "stopReason": "string", // Message shown when continue is false1269 "ConfigChange": [
1270 {
1271 "hooks": [
1272 {
1273 "type": "command",
1274 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
1275 }
1276 ]
1277 }
1278 ]
1279 }
1280}
1281```
1282
1283#### ConfigChange input
1284
1285In 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.
654 1286
655 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1287```json theme={null}
656 "systemMessage": "string" // Optional warning message shown to the user1288{
1289 "session_id": "abc123",
1290 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1291 "cwd": "/Users/...",
1292 "permission_mode": "default",
1293 "hook_event_name": "ConfigChange",
1294 "source": "project_settings",
1295 "file_path": "/Users/.../my-project/.claude/settings.json"
657}1296}
658```1297```
659 1298
660If `continue` is false, Claude stops processing after the hooks run.1299#### ConfigChange decision control
661 1300
662* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which1301ConfigChange 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.
663 only blocks a specific tool call and provides automatic feedback to Claude.
664* For `PostToolUse`, this is different from `"decision": "block"`, which
665 provides automated feedback to Claude.
666* For `UserPromptSubmit`, this prevents the prompt from being processed.
667* For `Stop` and `SubagentStop`, this takes precedence over any
668 `"decision": "block"` output.
669* In all cases, `"continue" = false` takes precedence over any
670 `"decision": "block"` output.
671 1302
672`stopReason` accompanies `continue` with a reason shown to the user, not shown1303| Field | Description |
673to Claude.1304| :--------- | :--------------------------------------------------------------------------------------- |
1305| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |
1306| `reason` | Explanation shown to the user when `decision` is `"block"` |
674 1307
675#### `PreToolUse` Decision Control1308```json theme={null}
1309{
1310 "decision": "block",
1311 "reason": "Configuration changes to project settings require admin approval"
1312}
1313```
1314
1315`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.
676 1316
677`PreToolUse` hooks can control whether a tool call proceeds.1317### WorktreeCreate
678 1318
679* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown1319When 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.
680 to the user but not to Claude.
681* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is
682 shown to Claude.
683* `"ask"` asks the user to confirm the tool call in the UI.
684 `permissionDecisionReason` is shown to the user but not to Claude.
685 1320
686Additionally, hooks can modify tool inputs before execution using `updatedInput`:1321The hook must print the absolute path to the created worktree directory on stdout. Claude Code uses this path as the working directory for the isolated session.
687 1322
688* `updatedInput` allows you to modify the tool's input parameters before the tool executes.1323This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
689* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.
690 1324
691```json theme={null}1325```json theme={null}
692{1326{
693 "hookSpecificOutput": {1327 "hooks": {
694 "hookEventName": "PreToolUse",1328 "WorktreeCreate": [
695 "permissionDecision": "allow"1329 {
696 "permissionDecisionReason": "My reason here",1330 "hooks": [
697 "updatedInput": {1331 {
698 "field_to_modify": "new value"1332 "type": "command",
1333 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
699 }1334 }
1335 ]
1336 }
1337 ]
700 }1338 }
701}1339}
702```1340```
703 1341
704<Note>1342The 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.
705 The `decision` and `reason` fields are deprecated for PreToolUse hooks.1343
706 Use `hookSpecificOutput.permissionDecision` and1344#### WorktreeCreate input
707 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields1345
708 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.1346In 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`).
709</Note>1347
1348```json theme={null}
1349{
1350 "session_id": "abc123",
1351 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1352 "cwd": "/Users/...",
1353 "hook_event_name": "WorktreeCreate",
1354 "name": "feature-auth"
1355}
1356```
1357
1358#### WorktreeCreate output
1359
1360The hook must print the absolute path to the created worktree directory on stdout. If the hook fails or produces no output, worktree creation fails with an error.
710 1361
711#### `PermissionRequest` Decision Control1362WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook's success or failure determines the outcome. Only `type: "command"` hooks are supported.
712 1363
713`PermissionRequest` hooks can allow or deny permission requests shown to the user.1364### WorktreeRemove
714 1365
715* For `"behavior": "allow"` you can also optionally pass in an `"updatedInput"` that modifies the tool's input parameters before the tool executes.1366The 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.
716* 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.1367
1368Claude Code passes the path that WorktreeCreate printed on stdout as `worktree_path` in the hook input. This example reads that path and removes the directory:
717 1369
718```json theme={null}1370```json theme={null}
719{1371{
720 "hookSpecificOutput": {1372 "hooks": {
721 "hookEventName": "PermissionRequest",1373 "WorktreeRemove": [
722 "decision": {1374 {
723 "behavior": "allow",1375 "hooks": [
724 "updatedInput": {1376 {
725 "command": "npm run lint"1377 "type": "command",
1378 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
726 }1379 }
1380 ]
727 }1381 }
1382 ]
728 }1383 }
729}1384}
730```1385```
731 1386
732#### `PostToolUse` Decision Control1387#### WorktreeRemove input
733
734`PostToolUse` hooks can provide feedback to Claude after tool execution.
735 1388
736* `"block"` automatically prompts Claude with `reason`.1389In 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.
737* `undefined` does nothing. `reason` is ignored.
738* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.
739 1390
740```json theme={null}1391```json theme={null}
741{1392{
742 "decision": "block" | undefined,1393 "session_id": "abc123",
743 "reason": "Explanation for decision",1394 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
744 "hookSpecificOutput": {1395 "cwd": "/Users/...",
745 "hookEventName": "PostToolUse",1396 "hook_event_name": "WorktreeRemove",
746 "additionalContext": "Additional information for Claude"1397 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
747 }
748}1398}
749```1399```
750 1400
751#### `UserPromptSubmit` Decision Control1401WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only. Only `type: "command"` hooks are supported.
752 1402
753`UserPromptSubmit` hooks can control whether a user prompt is processed and add context.1403### PreCompact
754
755**Adding context (exit code 0):**
756There are two ways to add context to the conversation:
757 1404
7581. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added1405Runs before Claude Code is about to run a compact operation.
759 as context. This is the easiest way to inject information.
760 1406
7612. **JSON with `additionalContext`** (structured): Use the JSON format below for1407The matcher value indicates whether compaction was triggered manually or automatically:
762 more control. The `additionalContext` field is added as context.
763 1408
764Both methods work with exit code 0. Plain stdout is shown as hook output in1409| Matcher | When it fires |
765the transcript; `additionalContext` is added more discretely.1410| :------- | :------------------------------------------- |
1411| `manual` | `/compact` |
1412| `auto` | Auto-compact when the context window is full |
766 1413
767**Blocking prompts:**1414#### PreCompact input
768 1415
769* `"decision": "block"` prevents the prompt from being processed. The submitted1416In 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.
770 prompt is erased from context. `"reason"` is shown to the user but not added
771 to context.
772* `"decision": undefined` (or omitted) allows the prompt to proceed normally.
773 1417
774```json theme={null}1418```json theme={null}
775{1419{
776 "decision": "block" | undefined,1420 "session_id": "abc123",
777 "reason": "Explanation for decision",1421 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
778 "hookSpecificOutput": {1422 "cwd": "/Users/...",
779 "hookEventName": "UserPromptSubmit",1423 "permission_mode": "default",
780 "additionalContext": "My additional context here"1424 "hook_event_name": "PreCompact",
781 }1425 "trigger": "manual",
1426 "custom_instructions": ""
782}1427}
783```1428```
784 1429
785<Note>1430### SessionEnd
786 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 to1431
787 block prompts or want more structured control.1432Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
788</Note>1433statistics, or saving session state. Supports matchers to filter by exit reason.
789 1434
790#### `Stop`/`SubagentStop` Decision Control1435The `reason` field in the hook input indicates why the session ended:
791 1436
792`Stop` and `SubagentStop` hooks can control whether Claude must continue.1437| Reason | Description |
1438| :---------------------------- | :----------------------------------------- |
1439| `clear` | Session cleared with `/clear` command |
1440| `logout` | User logged out |
1441| `prompt_input_exit` | User exited while prompt input was visible |
1442| `bypass_permissions_disabled` | Bypass permissions mode was disabled |
1443| `other` | Other exit reasons |
793 1444
794* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1445#### SessionEnd input
795 to know how to proceed.1446
796* `undefined` allows Claude to stop. `reason` is ignored.1447In 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.
797 1448
798```json theme={null}1449```json theme={null}
799{1450{
800 "decision": "block" | undefined,1451 "session_id": "abc123",
801 "reason": "Must be provided when Claude is blocked from stopping"1452 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1453 "cwd": "/Users/...",
1454 "permission_mode": "default",
1455 "hook_event_name": "SessionEnd",
1456 "reason": "other"
802}1457}
803```1458```
804 1459
805#### `SessionStart` Decision Control1460SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
1461
1462## Prompt-based hooks
806 1463
807`SessionStart` hooks allow you to load in context at the start of a session.1464In 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, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type.
808 1465
809* `"hookSpecificOutput.additionalContext"` adds the string to the context.1466Events that support all three hook types (`command`, `prompt`, and `agent`):
810* Multiple hooks' `additionalContext` values are concatenated.1467
1468* `PermissionRequest`
1469* `PostToolUse`
1470* `PostToolUseFailure`
1471* `PreToolUse`
1472* `Stop`
1473* `SubagentStop`
1474* `TaskCompleted`
1475* `UserPromptSubmit`
1476
1477Events that only support `type: "command"` hooks:
1478
1479* `ConfigChange`
1480* `Notification`
1481* `PreCompact`
1482* `SessionEnd`
1483* `SessionStart`
1484* `SubagentStart`
1485* `TeammateIdle`
1486* `WorktreeCreate`
1487* `WorktreeRemove`
1488
1489### How prompt-based hooks work
1490
1491Instead of executing a Bash command, prompt-based hooks:
1492
14931. Send the hook input and your prompt to a Claude model, Haiku by default
14942. The LLM responds with structured JSON containing a decision
14953. Claude Code processes the decision automatically
1496
1497### Prompt hook configuration
1498
1499Set `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.
1500
1501This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
811 1502
812```json theme={null}1503```json theme={null}
813{1504{
814 "hookSpecificOutput": {1505 "hooks": {
815 "hookEventName": "SessionStart",1506 "Stop": [
816 "additionalContext": "My additional context here"1507 {
1508 "hooks": [
1509 {
1510 "type": "prompt",
1511 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."
1512 }
1513 ]
1514 }
1515 ]
817 }1516 }
818}1517}
819```1518```
820 1519
821#### `SessionEnd` Decision Control1520| Field | Required | Description |
822 1521| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
823`SessionEnd` hooks run when a session ends. They cannot block session termination1522| `type` | yes | Must be `"prompt"` |
824but can perform cleanup tasks.1523| `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 |
825 1524| `model` | no | Model to use for evaluation. Defaults to a fast model |
826#### Exit Code Example: Bash Command Validation1525| `timeout` | no | Timeout in seconds. Default: 30 |
827
828```python theme={null}
829#!/usr/bin/env python3
830import json
831import re
832import sys
833
834# Define validation rules as a list of (regex pattern, message) tuples
835VALIDATION_RULES = [
836 (
837 r"\bgrep\b(?!.*\|)",
838 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
839 ),
840 (
841 r"\bfind\s+\S+\s+-name\b",
842 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
843 ),
844]
845
846
847def validate_command(command: str) -> list[str]:
848 issues = []
849 for pattern, message in VALIDATION_RULES:
850 if re.search(pattern, command):
851 issues.append(message)
852 return issues
853
854
855try:
856 input_data = json.load(sys.stdin)
857except json.JSONDecodeError as e:
858 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
859 sys.exit(1)
860
861tool_name = input_data.get("tool_name", "")
862tool_input = input_data.get("tool_input", {})
863command = tool_input.get("command", "")
864
865if tool_name != "Bash" or not command:
866 sys.exit(1)
867
868# Validate the command
869issues = validate_command(command)
870
871if issues:
872 for message in issues:
873 print(f"• {message}", file=sys.stderr)
874 # Exit code 2 blocks tool call and shows stderr to Claude
875 sys.exit(2)
876```
877 1526
878#### JSON Output Example: UserPromptSubmit to Add Context and Validation1527### Response schema
879 1528
880<Note>1529The LLM must respond with JSON containing:
881 For `UserPromptSubmit` hooks, you can inject context using either method:1530
1531```json theme={null}
1532{
1533 "ok": true | false,
1534 "reason": "Explanation for the decision"
1535}
1536```
882 1537
883 * **Plain text stdout** with exit code 0: Simplest approach, prints text1538| Field | Description |
884 * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts,1539| :------- | :--------------------------------------------------------- |
885 or `additionalContext` for structured context injection1540| `ok` | `true` allows the action, `false` prevents it |
1541| `reason` | Required when `ok` is `false`. Explanation shown to Claude |
886 1542
887 Remember: Exit code 2 only uses `stderr` for the error message. To block using1543### Example: Multi-criteria Stop hook
888 JSON (with a custom reason), use `"decision": "block"` with exit code 0.
889</Note>
890 1544
891```python theme={null}1545This `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:
892#!/usr/bin/env python31546
893import json1547```json theme={null}
894import sys1548{
895import re1549 "hooks": {
896import datetime1550 "Stop": [
897 1551 {
898# Load input from stdin1552 "hooks": [
899try:1553 {
900 input_data = json.load(sys.stdin)1554 "type": "prompt",
901except json.JSONDecodeError as e:1555 "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.",
902 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)1556 "timeout": 30
903 sys.exit(1)
904
905prompt = input_data.get("prompt", "")
906
907# Check for sensitive patterns
908sensitive_patterns = [
909 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
910]
911
912for pattern, message in sensitive_patterns:
913 if re.search(pattern, prompt):
914 # Use JSON output to block with a specific reason
915 output = {
916 "decision": "block",
917 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
918 }1557 }
919 print(json.dumps(output))1558 ]
920 sys.exit(0)1559 }
1560 ]
1561 }
1562}
1563```
921 1564
922# Add current time to context1565## Agent-based hooks
923context = f"Current time: {datetime.datetime.now()}"
924print(context)
925 1566
926"""1567Agent-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.
927The following is also equivalent:
928print(json.dumps({
929 "hookSpecificOutput": {
930 "hookEventName": "UserPromptSubmit",
931 "additionalContext": context,
932 },
933}))
934"""
935 1568
936# Allow the prompt to proceed with the additional context1569### How agent hooks work
937sys.exit(0)
938```
939 1570
940#### JSON Output Example: PreToolUse with Approval1571When an agent hook fires:
941
942```python theme={null}
943#!/usr/bin/env python3
944import json
945import sys
946
947# Load input from stdin
948try:
949 input_data = json.load(sys.stdin)
950except json.JSONDecodeError as e:
951 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
952 sys.exit(1)
953
954tool_name = input_data.get("tool_name", "")
955tool_input = input_data.get("tool_input", {})
956
957# Example: Auto-approve file reads for documentation files
958if tool_name == "Read":
959 file_path = tool_input.get("file_path", "")
960 if file_path.endswith((".md", ".mdx", ".txt", ".json")):
961 # Use JSON output to auto-approve the tool call
962 output = {
963 "decision": "approve",
964 "reason": "Documentation file auto-approved",
965 "suppressOutput": True # Don't show in verbose mode
966 }
967 print(json.dumps(output))
968 sys.exit(0)
969
970# For other cases, let the normal permission flow proceed
971sys.exit(0)
972```
973 1572
974## Working with MCP Tools15731. Claude Code spawns a subagent with your prompt and the hook's JSON input
15742. The subagent can use tools like Read, Grep, and Glob to investigate
15753. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision
15764. Claude Code processes the decision the same way as a prompt hook
975 1577
976Claude Code hooks work seamlessly with1578Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.
977[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers
978provide tools, they appear with a special naming pattern that you can match in
979your hooks.
980 1579
981### MCP Tool Naming1580### Agent hook configuration
982 1581
983MCP tools follow the pattern `mcp__<server>__<tool>`, for example:1582Set `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:
984 1583
985* `mcp__memory__create_entities` - Memory server's create entities tool1584| Field | Required | Description |
986* `mcp__filesystem__read_file` - Filesystem server's read file tool1585| :-------- | :------- | :------------------------------------------------------------------------------------------ |
987* `mcp__github__search_repositories` - GitHub server's search tool1586| `type` | yes | Must be `"agent"` |
1587| `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON |
1588| `model` | no | Model to use. Defaults to a fast model |
1589| `timeout` | no | Timeout in seconds. Default: 60 |
988 1590
989### Configuring Hooks for MCP Tools1591The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.
990 1592
991You can target specific MCP tools or entire MCP servers:1593This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
992 1594
993```json theme={null}1595```json theme={null}
994{1596{
995 "hooks": {1597 "hooks": {
996 "PreToolUse": [1598 "Stop": [
997 {1599 {
998 "matcher": "mcp__memory__.*",
999 "hooks": [1600 "hooks": [
1000 {1601 {
1001 "type": "command",1602 "type": "agent",
1002 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"1603 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",
1604 "timeout": 120
1003 }1605 }
1004 ]1606 ]
1005 },1607 }
1608 ]
1609 }
1610}
1611```
1612
1613## Run hooks in the background
1614
1615By 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.
1616
1617### Configure an async hook
1618
1619Add `"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.
1620
1621This 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:
1622
1623```json theme={null}
1624{
1625 "hooks": {
1626 "PostToolUse": [
1006 {1627 {
1007 "matcher": "mcp__.*__write.*",1628 "matcher": "Write",
1008 "hooks": [1629 "hooks": [
1009 {1630 {
1010 "type": "command",1631 "type": "command",
1011 "command": "/home/user/scripts/validate-mcp-write.py"1632 "command": "/path/to/run-tests.sh",
1633 "async": true,
1634 "timeout": 120
1012 }1635 }
1013 ]1636 ]
1014 }1637 }
1017}1640}
1018```1641```
1019 1642
1020## Examples1643The `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.
1021 1644
1022<Tip>1645### How async hooks execute
1023 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/hooks-guide#more-examples) in the get started guide.
1024</Tip>
1025
1026## Security Considerations
1027 1646
1028### Disclaimer1647When 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.
1029 1648
1030**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on1649After 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.
1031your system automatically. By using hooks, you acknowledge that:
1032 1650
1033* You are solely responsible for the commands you configure1651### Example: run tests after file changes
1034* Hooks can modify, delete, or access any files your user account can access
1035* Malicious or poorly written hooks can cause data loss or system damage
1036* Anthropic provides no warranty and assumes no liability for any damages
1037 resulting from hook usage
1038* You should thoroughly test hooks in a safe environment before production use
1039 1652
1040Always review and understand any hook commands before adding them to your1653This 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`:
1041configuration.
1042 1654
1043### Security Best Practices1655```bash theme={null}
1044 1656#!/bin/bash
1045Here are some key practices for writing more secure hooks:1657# run-tests-async.sh
1046 1658
10471. **Validate and sanitize inputs** - Never trust input data blindly1659# Read hook input from stdin
10482. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1660INPUT=$(cat)
10493. **Block path traversal** - Check for `..` in file paths1661FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
10504. **Use absolute paths** - Specify full paths for scripts (use
1051 "\$CLAUDE\_PROJECT\_DIR" for the project path)
10525. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.
1053 1662
1054### Configuration Safety1663# Only run tests for source files
1664if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
1665 exit 0
1666fi
1055 1667
1056Direct edits to hooks in settings files don't take effect immediately. Claude1668# Run tests and report results via systemMessage
1057Code:1669RESULT=$(npm test 2>&1)
1670EXIT_CODE=$?
1058 1671
10591. Captures a snapshot of hooks at startup1672if [ $EXIT_CODE -eq 0 ]; then
10602. Uses this snapshot throughout the session1673 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
10613. Warns if hooks are modified externally1674else
10624. Requires review in `/hooks` menu for changes to apply1675 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
1676fi
1677```
1063 1678
1064This prevents malicious hook modifications from affecting your current session.1679Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:
1065 1680
1066## Hook Execution Details1681```json theme={null}
1682{
1683 "hooks": {
1684 "PostToolUse": [
1685 {
1686 "matcher": "Write|Edit",
1687 "hooks": [
1688 {
1689 "type": "command",
1690 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",
1691 "async": true,
1692 "timeout": 300
1693 }
1694 ]
1695 }
1696 ]
1697 }
1698}
1699```
1067 1700
1068* **Timeout**: 60-second execution limit by default, configurable per command.1701### Limitations
1069 * A timeout for an individual command does not affect the other commands.
1070* **Parallelization**: All matching hooks run in parallel
1071* **Deduplication**: Multiple identical hook commands are deduplicated automatically
1072* **Environment**: Runs in current directory with Claude Code's environment
1073 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the
1074 absolute path to the project root directory (where Claude Code was started)
1075 * 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.
1076* **Input**: JSON via stdin
1077* **Output**:
1078 * PreToolUse/PermissionRequest/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o)
1079 * Notification/SessionEnd: Logged to debug only (`--debug`)
1080 * UserPromptSubmit/SessionStart: stdout added as context for Claude
1081 1702
1082## Debugging1703Async hooks have several constraints compared to synchronous hooks:
1083 1704
1084### Basic Troubleshooting1705* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.
1706* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
1707* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.
1708* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
1085 1709
1086If your hooks aren't working:1710## Security considerations
1087 1711
10881. **Check configuration** - Run `/hooks` to see if your hook is registered1712### Disclaimer
10892. **Verify syntax** - Ensure your JSON settings are valid
10903. **Test commands** - Run hook commands manually first
10914. **Check permissions** - Make sure scripts are executable
10925. **Review logs** - Use `claude --debug` to see hook execution details
1093 1713
1094Common issues:1714Hooks run with your system user's full permissions.
1095 1715
1096* **Quotes not escaped** - Use `\"` inside JSON strings1716<Warning>
1097* **Wrong matcher** - Check tool names match exactly (case-sensitive)1717 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.
1098* **Command not found** - Use full paths for scripts1718</Warning>
1099 1719
1100### Advanced Debugging1720### Security best practices
1101 1721
1102For complex hook issues:1722Keep these practices in mind when writing hooks:
1103 1723
11041. **Inspect hook execution** - Use `claude --debug` to see detailed hook1724* **Validate and sanitize inputs**: never trust input data blindly
1105 execution1725* **Always quote shell variables**: use `"$VAR"` not `$VAR`
11062. **Validate JSON schemas** - Test hook input/output with external tools1726* **Block path traversal**: check for `..` in file paths
11073. **Check environment variables** - Verify Claude Code's environment is correct1727* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root
11084. **Test edge cases** - Try hooks with unusual file paths or inputs1728* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.
11095. **Monitor system resources** - Check for resource exhaustion during hook
1110 execution
11116. **Use structured logging** - Implement logging in your hook scripts
1112 1729
1113### Debug Output Example1730## Debug hooks
1114 1731
1115Use `claude --debug` to see hook execution details:1732Run `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.
1116 1733
1117```1734```
1118[DEBUG] Executing hooks for PostToolUse:Write1735[DEBUG] Executing hooks for PostToolUse:Write
1120[DEBUG] Found 1 hook matchers in settings1737[DEBUG] Found 1 hook matchers in settings
1121[DEBUG] Matched 1 hooks for query "Write"1738[DEBUG] Matched 1 hooks for query "Write"
1122[DEBUG] Found 1 hook commands to execute1739[DEBUG] Found 1 hook commands to execute
1123[DEBUG] Executing hook command: <Your command> with timeout 60000ms1740[DEBUG] Executing hook command: <Your command> with timeout 600000ms
1124[DEBUG] Hook command completed with status 0: <Your stdout>1741[DEBUG] Hook command completed with status 0: <Your stdout>
1125```1742```
1126 1743
1127Progress messages appear in verbose mode (ctrl+o) showing:1744For 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.
1128
1129* Which hook is running
1130* Command being executed
1131* Success/failure status
1132* Output or error messages
1133
1134
1135
1136> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt