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.
14
15## Hook lifecycle
16
17Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, this arrives on stdin. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:
10 18
11Claude Code hooks are configured in your [settings files](/en/settings):19<div style={{maxWidth: "500px", margin: "0 auto"}}>
20 <Frame>
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>
12 24
13* `~/.claude/settings.json` - User settings25The 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.
14* `.claude/settings.json` - Project settings
15* `.claude/settings.local.json` - Local project settings (not committed)
16* Enterprise managed policy settings
17 26
18### Structure27| 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 |
19 46
20Hooks are organized by matchers, where each matcher can have multiple hooks: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:
21 50
22```json theme={null}51```json theme={null}
23{52{
24 "hooks": {53 "hooks": {
25 "EventName": [54 "PreToolUse": [
26 {55 {
27 "matcher": "ToolPattern",56 "matcher": "Bash",
28 "hooks": [57 "hooks": [
29 {58 {
30 "type": "command",59 "type": "command",
31 "command": "your-command-here"60 "command": ".claude/hooks/block-rm.sh"
32 }61 }
33 ]62 ]
34 }63 }
37}66}
38```67```
39 68
40* **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`:
41 `PreToolUse`, `PermissionRequest`, and `PostToolUse`)
42 * Simple strings match exactly: `Write` matches only the Write tool
43 * Supports regex: `Edit|Write` or `Notebook.*`
44 * Use `*` to match all tools. You can also use empty string (`""`) or leave
45 `matcher` blank.
46* **hooks**: Array of hooks to execute when the pattern matches
47 * `type`: Hook execution type - `"command"` for bash commands or `"prompt"` for LLM-based evaluation
48 * `command`: (For `type: "command"`) The bash command to execute (can use `$CLAUDE_PROJECT_DIR` environment variable)
49 * `prompt`: (For `type: "prompt"`) The prompt to send to the LLM for evaluation
50 * `timeout`: (Optional) How long a hook should run, in seconds, before canceling that specific hook
51
52For events like `UserPromptSubmit`, `Stop`, and `SubagentStop`
53that don't use matchers, you can omit the matcher field:
54 70
55```json theme={null}71```bash theme={null}
56{72#!/bin/bash
57 "hooks": {73# .claude/hooks/block-rm.sh
58 "UserPromptSubmit": [74COMMAND=$(jq -r '.tool_input.command')
59 {75
60 "hooks": [76if echo "$COMMAND" | grep -q 'rm -rf'; then
61 {77 jq -n '{
62 "type": "command",78 hookSpecificOutput: {
63 "command": "/path/to/prompt-validator.py"79 hookEventName: "PreToolUse",
64 }80 permissionDecision: "deny",
65 ]81 permissionDecisionReason: "Destructive command blocked by hook"
66 }
67 ]
68 }82 }
69}83 }'
84else
85 exit 0 # allow the command
86fi
70```87```
71 88
72### Project-Specific Hook Scripts89Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
73 90
74You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when91<Frame>
75Claude 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" />
76ensuring they work regardless of Claude's current directory:93</Frame>
77 94
78```json theme={null}95<Steps>
79{96 <Step title="Event fires">
80 "hooks": {97 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
81 "PostToolUse": [98
82 {99 ```json theme={null}
83 "matcher": "Write|Edit",100 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
84 "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}
85 {112 {
86 "type": "command",113 "hookSpecificOutput": {
87 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"114 "hookEventName": "PreToolUse",
88 }115 "permissionDecision": "deny",
89 ]116 "permissionDecisionReason": "Destructive command blocked by hook"
90 }117 }
91 ]
92 }118 }
93}119 ```
94```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:
134
1351. 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
95 138
96### Plugin hooks139See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.
97 140
98[Plugins](/en/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled.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:
99 163
100**How plugin hooks work**:164| Event | What the matcher filters | Example matcher values |
165| :---------------------------------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |
166| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
167| `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 |
101 175
102* Plugin hooks are defined in the plugin's `hooks/hooks.json` file or in a file given by a custom path to the `hooks` field.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.
103* When a plugin is enabled, its hooks are merged with user and project hooks
104* Multiple hooks from different sources can respond to the same event
105* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files
106 177
107**Example plugin hook configuration**:178This example runs a linting script only when Claude writes or edits a file:
108 179
109```json theme={null}180```json theme={null}
110{181{
111 "description": "Automatic code formatting",
112 "hooks": {182 "hooks": {
113 "PostToolUse": [183 "PostToolUse": [
114 {184 {
115 "matcher": "Write|Edit",185 "matcher": "Edit|Write",
116 "hooks": [186 "hooks": [
117 {187 {
118 "type": "command",188 "type": "command",
119 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",189 "command": "/path/to/lint-check.sh"
120 "timeout": 30
121 }190 }
122 ]191 ]
123 }192 }
126}195}
127```196```
128 197
129<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.
130 Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.
131</Note>
132
133<Note>
134 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.
135</Note>
136
137**Environment variables for plugins**:
138 199
139* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory200#### Match MCP tools
140* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)
141* All standard environment variables are available
142 201
143See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.202[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.
144 203
145## Prompt-Based Hooks204MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
146 205
147In addition to bash command hooks (`type: "command"`), Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action. Prompt-based hooks are currently only supported for `Stop` and `SubagentStop` hooks, where they enable intelligent, context-aware decisions.206* `mcp__memory__create_entities`: Memory server's create entities tool
148 207* `mcp__filesystem__read_file`: Filesystem server's read file tool
149### How prompt-based hooks work208* `mcp__github__search_repositories`: GitHub server's search tool
150 209
151Instead of executing a bash command, prompt-based hooks:210Use regex patterns to target specific MCP tools or groups of tools:
152 211
1531. Send the hook input and your prompt to a fast LLM (Haiku)212* `mcp__memory__.*` matches all tools from the `memory` server
1542. The LLM responds with structured JSON containing a decision213* `mcp__.*__write.*` matches any tool containing "write" from any server
1553. Claude Code processes the decision automatically
156 214
157### Configuration215This example logs all memory server operations and validates write operations from any MCP server:
158 216
159```json theme={null}217```json theme={null}
160{218{
161 "hooks": {219 "hooks": {
162 "Stop": [220 "PreToolUse": [
163 {221 {
222 "matcher": "mcp__memory__.*",
164 "hooks": [223 "hooks": [
165 {224 {
166 "type": "prompt",225 "type": "command",
167 "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"
168 }236 }
169 ]237 ]
170 }238 }
173}241}
174```242```
175 243
176**Fields:**244### Hook handler fields
177 245
178* `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:
179* `prompt`: The prompt text to send to the LLM
180 * Use `$ARGUMENTS` as a placeholder for the hook input JSON
181 * If `$ARGUMENTS` is not present, input JSON is appended to the prompt
182* `timeout`: (Optional) Timeout in seconds (default: 30 seconds)
183 247
184### 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).
185 251
186The LLM must respond with JSON containing:252#### Common fields
187 253
188```json theme={null}254These fields apply to all hook types:
189{
190 "decision": "approve" | "block",
191 "reason": "Explanation for the decision",
192 "continue": false, // Optional: stops Claude entirely
193 "stopReason": "Message shown to user", // Optional: custom stop message
194 "systemMessage": "Warning or context" // Optional: shown to user
195}
196```
197 255
198**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) |
199 262
200* `decision`: `"approve"` allows the action, `"block"` prevents it263#### Command hook fields
201* `reason`: Explanation shown to Claude when decision is `"block"`
202* `continue`: (Optional) If `false`, stops Claude's execution entirely
203* `stopReason`: (Optional) Message shown when `continue` is false
204* `systemMessage`: (Optional) Additional message shown to the user
205 264
206### Supported hook events265In addition to the [common fields](#common-fields), command hooks accept these fields:
207 266
208Prompt-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) |
209 271
210* **Stop**: Intelligently decide if Claude should continue working272#### Prompt and agent hook fields
211* **SubagentStop**: Evaluate if a subagent has completed its task
212* **UserPromptSubmit**: Validate user prompts with LLM assistance
213* **PreToolUse**: Make context-aware permission decisions
214* **PermissionRequest**: Intelligently allow or deny permission dialogs
215 273
216### Example: Intelligent Stop hook274In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:
217 275
218```json theme={null}276| Field | Required | Description |
219{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 {
220 "hooks": {296 "hooks": {
221 "Stop": [297 "PostToolUse": [
222 {298 {
299 "matcher": "Write|Edit",
223 "hooks": [300 "hooks": [
224 {301 {
225 "type": "prompt",302 "type": "command",
226 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"decision\": \"approve\" or \"block\", \"reason\": \"your explanation\"}",303 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
227 "timeout": 30
228 }304 }
229 ]305 ]
230 }306 }
231 ]307 ]
232 }308 }
233}309 }
234```310 ```
311 </Tab>
235 312
236### 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.
237 315
238```json theme={null}316 This example runs a formatting script bundled with the plugin:
239{317
318 ```json theme={null}
319 {
320 "description": "Automatic code formatting",
240 "hooks": {321 "hooks": {
241 "SubagentStop": [322 "PostToolUse": [
242 {323 {
324 "matcher": "Write|Edit",
243 "hooks": [325 "hooks": [
244 {326 {
245 "type": "prompt",327 "type": "command",
246 "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"328 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
329 "timeout": 30
247 }330 }
248 ]331 ]
249 }332 }
250 ]333 ]
251 }334 }
252}335 }
253```336 ```
254 337
255### Comparison with bash command hooks338 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.
339 </Tab>
340</Tabs>
256 341
257| Feature | Bash Command Hooks | Prompt-Based Hooks |342### Hooks in skills and agents
258| --------------------- | ----------------------- | ------------------------------ |
259| **Execution** | Runs bash script | Queries LLM |
260| **Decision logic** | You implement in code | LLM evaluates context |
261| **Setup complexity** | Requires script file | Configure prompt |
262| **Context awareness** | Limited to script logic | Natural language understanding |
263| **Performance** | Fast (local execution) | Slower (API call) |
264| **Use case** | Deterministic rules | Context-aware decisions |
265 343
266### 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.
267 345
268* **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.
269* **Include decision criteria**: List the factors the LLM should consider
270* **Test your prompts**: Verify the LLM makes correct decisions for your use cases
271* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed
272* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules
273 347
274See 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.
275 349
276## Hook Events350This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
277 351
278### 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```
279 364
280Runs after Claude creates tool parameters and before processing the tool call.365Agents use the same format in their YAML frontmatter.
281 366
282**Common matchers:**367### The `/hooks` menu
283 368
284* `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.
285* `Bash` - Shell commands
286* `Glob` - File pattern matching
287* `Grep` - Content search
288* `Read` - File reading
289* `Edit` - File editing
290* `Write` - File writing
291* `WebFetch`, `WebSearch` - Web operations
292 370
293Use [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:
294 372
295### 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
296 377
297Runs when the user is shown a permission dialog.378### Disable or remove hooks
298Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.
299 379
300Recognizes 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.
301 381
302### 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.
303 383
304Runs 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.
305 385
306Recognizes 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.
307 387
308### Notification388## Hook input and output
309 389
310Runs 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.
311 391
312**Common matchers:**392### Common input fields
313 393
314* `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:
315* `idle_prompt` - When Claude is waiting for user input (after 60+ seconds of idle time)
316* `auth_success` - Authentication success notifications
317* `elicitation_dialog` - When Claude Code needs input for MCP tool elicitation
318 395
319You 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 |
320 403
321**Example: Different notifications for different types**404For example, a `PreToolUse` hook for a Bash command receives this on stdin:
322 405
323```json theme={null}406```json theme={null}
324{407{
325 "hooks": {408 "session_id": "abc123",
326 "Notification": [409 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
327 {410 "cwd": "/home/user/my-project",
328 "matcher": "permission_prompt",411 "permission_mode": "default",
329 "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}
330 {520 {
331 "type": "command",521 "decision": "block",
332 "command": "/path/to/permission-alert.sh"522 "reason": "Test suite must pass before proceeding"
333 }523 }
334 ]524 ```
335 },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}
336 {531 {
337 "matcher": "idle_prompt",532 "hookSpecificOutput": {
338 "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}
339 {545 {
340 "type": "command",546 "hookSpecificOutput": {
341 "command": "/path/to/idle-notification.sh"547 "hookEventName": "PermissionRequest",
548 "decision": {
549 "behavior": "allow",
550 "updatedInput": {
551 "command": "npm run lint"
342 }552 }
343 ]
344 }553 }
345 ]
346 }554 }
347}555 }
348```556 ```
557 </Tab>
558</Tabs>
349 559
350### 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).
351 561
352Runs when the user submits a prompt, before Claude processes it. This allows you562## Hook events
353to add additional context based on the prompt/conversation, validate prompts, or
354block certain types of prompts.
355 563
356### 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.
357 565
358Runs when the main Claude Code agent has finished responding. Does not run if566### SessionStart
359the stoppage occurred due to a user interrupt.
360 567
361### 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.
362 569
363Runs when a Claude Code subagent (Task tool call) has finished responding.570SessionStart runs on every session, so keep these hooks fast.
364 571
365### PreCompact572The matcher value corresponds to how the session was initiated:
366 573
367Runs 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 |
368 580
369**Matchers:**581#### SessionStart input
370 582
371* `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.
372* `auto` - Invoked from auto-compact (due to full context window)
373 584
374### 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```
596
597#### SessionStart decision control
375 598
376Runs when Claude Code starts a new session or resumes an existing session (which599Any text your hook script prints to stdout is added as context for Claude. In addition to the [JSON output fields](#json-output) available to all hooks, you can return these event-specific fields:
377currently does start a new session under the hood). Useful for loading in
378development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables.
379 600
380**Matchers:**601| Field | Description |
602| :------------------ | :------------------------------------------------------------------------ |
603| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |
381 604
382* `startup` - Invoked from startup605```json theme={null}
383* `resume` - Invoked from `--resume`, `--continue`, or `/resume`606{
384* `clear` - Invoked from `/clear`607 "hookSpecificOutput": {
385* `compact` - Invoked from auto or manual compact.608 "hookEventName": "SessionStart",
609 "additionalContext": "My additional context here"
610 }
611}
612```
386 613
387#### Persisting environment variables614#### Persist environment variables
388 615
389SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent bash commands.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.
390 617
391**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:
392 619
393```bash theme={null}620```bash theme={null}
394#!/bin/bash621#!/bin/bash
395 622
396if [ -n "$CLAUDE_ENV_FILE" ]; then623if [ -n "$CLAUDE_ENV_FILE" ]; then
397 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"624 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
398 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"625 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
399 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"626 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
400fi627fi
401 628
402exit 0629exit 0
403```630```
404 631
405**Example: Persisting all environment changes from the hook**632To capture all environment changes from setup commands, compare the exported variables before and after:
406
407When your setup modifies the environment (for example, `nvm use`), capture and persist all changes by diffing the environment:
408 633
409```bash theme={null}634```bash theme={null}
410#!/bin/bash635#!/bin/bash
423exit 0648exit 0
424```649```
425 650
426Any 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.
427 652
428<Note>653<Note>
429 `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.
430</Note>655</Note>
431 656
432### SessionEnd657### UserPromptSubmit
433
434Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
435statistics, or saving session state.
436
437The `reason` field in the hook input will be one of:
438
439* `clear` - Session cleared with /clear command
440* `logout` - User logged out
441* `prompt_input_exit` - User exited while prompt input was visible
442* `other` - Other exit reasons
443
444## Hook Input
445
446Hooks receive JSON data via stdin containing session information and
447event-specific data:
448 658
449```typescript theme={null}659Runs when the user submits a prompt, before Claude processes it. This allows you
450{660to add additional context based on the prompt/conversation, validate prompts, or
451 // Common fields661block certain types of prompts.
452 session_id: string
453 transcript_path: string // Path to conversation JSON
454 cwd: string // The current working directory when the hook is invoked
455 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions"
456
457 // Event-specific fields
458 hook_event_name: string
459 ...
460}
461```
462 662
463### PreToolUse Input663#### UserPromptSubmit input
464 664
465The 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.
466 666
467```json theme={null}667```json theme={null}
468{668{
470 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",670 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
471 "cwd": "/Users/...",671 "cwd": "/Users/...",
472 "permission_mode": "default",672 "permission_mode": "default",
473 "hook_event_name": "PreToolUse",673 "hook_event_name": "UserPromptSubmit",
474 "tool_name": "Write",674 "prompt": "Write a function to calculate the factorial of a number"
475 "tool_input": {675}
476 "file_path": "/path/to/file.txt",676```
477 "content": "file content"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"
478 },835 },
479 "tool_use_id": "toolu_01ABC123..."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",
864 "tool_input": {
865 "command": "rm -rf node_modules",
866 "description": "Remove node_modules directory"
867 },
868 "permission_suggestions": [
869 { "type": "toolAlwaysAllow", "tool": "Bash" }
870 ]
480}871}
481```872```
482 873
483### PostToolUse Input874#### PermissionRequest decision control
484 875
485The exact schema for `tool_input` and `tool_response` depends on the tool.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:
877
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.
486 909
487```json theme={null}910```json theme={null}
488{911{
504}927}
505```928```
506 929
507### 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.
508 1038
509```json theme={null}1039```json theme={null}
510{1040{
514 "permission_mode": "default",1044 "permission_mode": "default",
515 "hook_event_name": "Notification",1045 "hook_event_name": "Notification",
516 "message": "Claude needs your permission to use Bash",1046 "message": "Claude needs your permission to use Bash",
1047 "title": "Permission needed",
517 "notification_type": "permission_prompt"1048 "notification_type": "permission_prompt"
518}1049}
519```1050```
520 1051
521### 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).
522 1065
523```json theme={null}1066```json theme={null}
524{1067{
526 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1069 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
527 "cwd": "/Users/...",1070 "cwd": "/Users/...",
528 "permission_mode": "default",1071 "permission_mode": "default",
529 "hook_event_name": "UserPromptSubmit",1072 "hook_event_name": "SubagentStart",
530 "prompt": "Write a function to calculate the factorial of a number"1073 "agent_id": "agent-abc123",
1074 "agent_type": "Explore"
531}1075}
532```1076```
533 1077
534### 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:
535 1079
536`stop_hook_active` is true when Claude Code is already continuing as a result of1080| Field | Description |
537a stop hook. Check this value or process the transcript to prevent Claude Code1081| :------------------ | :------------------------------------- |
538from 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.
539 1100
540```json theme={null}1101```json theme={null}
541{1102{
542 "session_id": "abc123",1103 "session_id": "abc123",
543 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1104 "transcript_path": "~/.claude/projects/.../abc123.jsonl",
1105 "cwd": "/Users/...",
544 "permission_mode": "default",1106 "permission_mode": "default",
545 "hook_event_name": "Stop",1107 "hook_event_name": "SubagentStop",
546 "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..."
547}1113}
548```1114```
549 1115
550### PreCompact Input1116SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).
1117
1118### Stop
1119
1120Runs when the main Claude Code agent has finished responding. Does not run if
1121the stoppage occurred due to a user interrupt.
551 1122
552For `manual`, `custom_instructions` comes from what the user passes into1123#### Stop input
553`/compact`. For `auto`, `custom_instructions` is empty.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.
554 1126
555```json theme={null}1127```json theme={null}
556{1128{
557 "session_id": "abc123",1129 "session_id": "abc123",
558 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1130 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1131 "cwd": "/Users/...",
559 "permission_mode": "default",1132 "permission_mode": "default",
560 "hook_event_name": "PreCompact",1133 "hook_event_name": "Stop",
561 "trigger": "manual",1134 "stop_hook_active": true,
562 "custom_instructions": ""1135 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
563}1136}
564```1137```
565 1138
566### SessionStart Input1139#### 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"
1152}
1153```
1154
1155### 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`.
567 1164
568```json theme={null}1165```json theme={null}
569{1166{
570 "session_id": "abc123",1167 "session_id": "abc123",
571 "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/...",
572 "permission_mode": "default",1170 "permission_mode": "default",
573 "hook_event_name": "SessionStart",1171 "hook_event_name": "TeammateIdle",
574 "source": "startup"1172 "teammate_name": "researcher",
1173 "team_name": "my-project"
575}1174}
576```1175```
577 1176
578### 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`.
579 1206
580```json theme={null}1207```json theme={null}
581{1208{
582 "session_id": "abc123",1209 "session_id": "abc123",
583 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1210 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
584 "cwd": "/Users/...",1211 "cwd": "/Users/...",
585 "permission_mode": "default",1212 "permission_mode": "default",
586 "hook_event_name": "SessionEnd",1213 "hook_event_name": "TaskCompleted",
587 "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"
588}1219}
589```1220```
590 1221
591## Hook Output1222| Field | Description |
592 1223| :----------------- | :------------------------------------------------------ |
593There are two mutually exclusive ways for hooks to return output back to Claude Code. The output1224| `task_id` | Identifier of the task being completed |
594communicates whether to block and any feedback that should be shown to Claude1225| `task_subject` | Title of the task |
595and 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 |
596 1229
597### Simple: Exit Code1230#### TaskCompleted decision control
598 1231
599Hooks 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:
600 1233
601* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode1234```bash theme={null}
602 (ctrl+o), except for `UserPromptSubmit` and `SessionStart`, where stdout is1235#!/bin/bash
603 added to the context. JSON output in `stdout` is parsed for structured control1236INPUT=$(cat)
604 (see [Advanced: JSON Output](#advanced-json-output)).1237TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
605* **Exit code 2**: Blocking error. Only `stderr` is used as the error message
606 and fed back to Claude. The format is `[command]: {stderr}`. JSON in `stdout`
607 is **not** processed for exit code 2. See per-hook-event behavior below.
608* **Other exit codes**: Non-blocking error. `stderr` is shown to the user in verbose mode (ctrl+o) with
609 format `Failed with non-blocking status code: {stderr}`. If `stderr` is empty,
610 it shows `No stderr output`. Execution continues.
611 1238
612<Warning>1239# Run the test suite
613 Reminder: Claude Code does not see stdout if the exit code is 0, except for1240if ! npm test 2>&1; then
614 the `UserPromptSubmit` hook where stdout is injected as context.1241 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
615</Warning>1242 exit 2
1243fi
616 1244
617#### Exit Code 2 Behavior1245exit 0
1246```
618 1247
619| Hook Event | Behavior |1248### ConfigChange
620| ------------------- | ------------------------------------------------------------------ |
621| `PreToolUse` | Blocks the tool call, shows stderr to Claude |
622| `PermissionRequest` | Denies the permission, shows stderr to Claude |
623| `PostToolUse` | Shows stderr to Claude (tool already ran) |
624| `Notification` | N/A, shows stderr to user only |
625| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |
626| `Stop` | Blocks stoppage, shows stderr to Claude |
627| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |
628| `PreCompact` | N/A, shows stderr to user only |
629| `SessionStart` | N/A, shows stderr to user only |
630| `SessionEnd` | N/A, shows stderr to user only |
631 1249
632### 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.
633 1251
634Hooks 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.
635 1253
636<Warning>1254The matcher filters on the configuration source:
637 JSON output is only processed when the hook exits with code 0. If your hook
638 exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout`
639 is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o).
640</Warning>
641 1255
642#### 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 |
643 1263
644All hook types can include these optional fields:1264This example logs all configuration changes for security auditing:
645 1265
646```json theme={null}1266```json theme={null}
647{1267{
648 "continue": true, // Whether Claude should continue after hook execution (default: true)1268 "hooks": {
649 "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.
650 1286
651 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1287```json theme={null}
652 "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"
653}1296}
654```1297```
655 1298
656If `continue` is false, Claude stops processing after the hooks run.1299#### ConfigChange decision control
657 1300
658* 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.
659 only blocks a specific tool call and provides automatic feedback to Claude.
660* For `PostToolUse`, this is different from `"decision": "block"`, which
661 provides automated feedback to Claude.
662* For `UserPromptSubmit`, this prevents the prompt from being processed.
663* For `Stop` and `SubagentStop`, this takes precedence over any
664 `"decision": "block"` output.
665* In all cases, `"continue" = false` takes precedence over any
666 `"decision": "block"` output.
667 1302
668`stopReason` accompanies `continue` with a reason shown to the user, not shown1303| Field | Description |
669to 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"` |
670 1307
671#### `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.
672 1316
673`PreToolUse` hooks can control whether a tool call proceeds.1317### WorktreeCreate
674 1318
675* `"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.
676 to the user but not to Claude.
677* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is
678 shown to Claude.
679* `"ask"` asks the user to confirm the tool call in the UI.
680 `permissionDecisionReason` is shown to the user but not to Claude.
681 1320
682Additionally, 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.
683 1322
684* `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:
685* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.
686 1324
687```json theme={null}1325```json theme={null}
688{1326{
689 "hookSpecificOutput": {1327 "hooks": {
690 "hookEventName": "PreToolUse",1328 "WorktreeCreate": [
691 "permissionDecision": "allow"1329 {
692 "permissionDecisionReason": "My reason here",1330 "hooks": [
693 "updatedInput": {1331 {
694 "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\"'"
1334 }
1335 ]
695 }1336 }
1337 ]
696 }1338 }
697}1339}
698```1340```
699 1341
700<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.
701 The `decision` and `reason` fields are deprecated for PreToolUse hooks.1343
702 Use `hookSpecificOutput.permissionDecision` and1344#### WorktreeCreate input
703 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields1345
704 `"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`).
705</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.
706 1361
707#### `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.
708 1363
709`PermissionRequest` hooks can allow or deny permission requests shown to the user.1364### WorktreeRemove
710 1365
711* 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.
712* For `"behavior": "deny"` you can also optionally pass in a `"message"` string that tells the model why the permission was denied, and a boolean `"interrupt"` which will stop Claude.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:
713 1369
714```json theme={null}1370```json theme={null}
715{1371{
716 "hookSpecificOutput": {1372 "hooks": {
717 "hookEventName": "PermissionRequest",1373 "WorktreeRemove": [
718 "decision": {1374 {
719 "behavior": "allow",1375 "hooks": [
720 "updatedInput": {1376 {
721 "command": "npm run lint"1377 "type": "command",
1378 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
722 }1379 }
1380 ]
723 }1381 }
1382 ]
724 }1383 }
725}1384}
726```1385```
727 1386
728#### `PostToolUse` Decision Control1387#### WorktreeRemove input
729
730`PostToolUse` hooks can provide feedback to Claude after tool execution.
731 1388
732* `"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.
733* `undefined` does nothing. `reason` is ignored.
734* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.
735 1390
736```json theme={null}1391```json theme={null}
737{1392{
738 "decision": "block" | undefined,1393 "session_id": "abc123",
739 "reason": "Explanation for decision",1394 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
740 "hookSpecificOutput": {1395 "cwd": "/Users/...",
741 "hookEventName": "PostToolUse",1396 "hook_event_name": "WorktreeRemove",
742 "additionalContext": "Additional information for Claude"1397 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
743 }
744}1398}
745```1399```
746 1400
747#### `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.
748 1402
749`UserPromptSubmit` hooks can control whether a user prompt is processed and add context.1403### PreCompact
750
751**Adding context (exit code 0):**
752There are two ways to add context to the conversation:
753 1404
7541. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added1405Runs before Claude Code is about to run a compact operation.
755 as context. This is the easiest way to inject information.
756 1406
7572. **JSON with `additionalContext`** (structured): Use the JSON format below for1407The matcher value indicates whether compaction was triggered manually or automatically:
758 more control. The `additionalContext` field is added as context.
759 1408
760Both methods work with exit code 0. Plain stdout is shown as hook output in1409| Matcher | When it fires |
761the transcript; `additionalContext` is added more discretely.1410| :------- | :------------------------------------------- |
1411| `manual` | `/compact` |
1412| `auto` | Auto-compact when the context window is full |
762 1413
763**Blocking prompts:**1414#### PreCompact input
764 1415
765* `"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.
766 prompt is erased from context. `"reason"` is shown to the user but not added
767 to context.
768* `"decision": undefined` (or omitted) allows the prompt to proceed normally.
769 1417
770```json theme={null}1418```json theme={null}
771{1419{
772 "decision": "block" | undefined,1420 "session_id": "abc123",
773 "reason": "Explanation for decision",1421 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
774 "hookSpecificOutput": {1422 "cwd": "/Users/...",
775 "hookEventName": "UserPromptSubmit",1423 "permission_mode": "default",
776 "additionalContext": "My additional context here"1424 "hook_event_name": "PreCompact",
777 }1425 "trigger": "manual",
1426 "custom_instructions": ""
778}1427}
779```1428```
780 1429
781<Note>1430### SessionEnd
782 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
783 block prompts or want more structured control.1432Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
784</Note>1433statistics, or saving session state. Supports matchers to filter by exit reason.
1434
1435The `reason` field in the hook input indicates why the session ended:
785 1436
786#### `Stop`/`SubagentStop` Decision Control1437| 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 |
787 1444
788`Stop` and `SubagentStop` hooks can control whether Claude must continue.1445#### SessionEnd input
789 1446
790* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1447In 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.
791 to know how to proceed.
792* `undefined` allows Claude to stop. `reason` is ignored.
793 1448
794```json theme={null}1449```json theme={null}
795{1450{
796 "decision": "block" | undefined,1451 "session_id": "abc123",
797 "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"
798}1457}
799```1458```
800 1459
801#### `SessionStart` Decision Control1460SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
1461
1462## Prompt-based hooks
1463
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.
802 1465
803`SessionStart` hooks allow you to load in context at the start of a session.1466Events that support all three hook types (`command`, `prompt`, and `agent`):
804 1467
805* `"hookSpecificOutput.additionalContext"` adds the string to the context.1468* `PermissionRequest`
806* Multiple hooks' `additionalContext` values are concatenated.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:
807 1502
808```json theme={null}1503```json theme={null}
809{1504{
810 "hookSpecificOutput": {1505 "hooks": {
811 "hookEventName": "SessionStart",1506 "Stop": [
812 "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 ]
813 }1516 }
814}1517}
815```1518```
816 1519
817#### `SessionEnd` Decision Control1520| Field | Required | Description |
818 1521| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
819`SessionEnd` hooks run when a session ends. They cannot block session termination1522| `type` | yes | Must be `"prompt"` |
820but 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 |
821 1524| `model` | no | Model to use for evaluation. Defaults to a fast model |
822#### Exit Code Example: Bash Command Validation1525| `timeout` | no | Timeout in seconds. Default: 30 |
823 1526
824```python theme={null}1527### Response schema
825#!/usr/bin/env python3
826import json
827import re
828import sys
829
830# Define validation rules as a list of (regex pattern, message) tuples
831VALIDATION_RULES = [
832 (
833 r"\bgrep\b(?!.*\|)",
834 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
835 ),
836 (
837 r"\bfind\s+\S+\s+-name\b",
838 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
839 ),
840]
841
842
843def validate_command(command: str) -> list[str]:
844 issues = []
845 for pattern, message in VALIDATION_RULES:
846 if re.search(pattern, command):
847 issues.append(message)
848 return issues
849
850
851try:
852 input_data = json.load(sys.stdin)
853except json.JSONDecodeError as e:
854 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
855 sys.exit(1)
856
857tool_name = input_data.get("tool_name", "")
858tool_input = input_data.get("tool_input", {})
859command = tool_input.get("command", "")
860
861if tool_name != "Bash" or not command:
862 sys.exit(1)
863
864# Validate the command
865issues = validate_command(command)
866
867if issues:
868 for message in issues:
869 print(f"• {message}", file=sys.stderr)
870 # Exit code 2 blocks tool call and shows stderr to Claude
871 sys.exit(2)
872```
873 1528
874#### JSON Output Example: UserPromptSubmit to Add Context and Validation1529The LLM must respond with JSON containing:
875 1530
876<Note>1531```json theme={null}
877 For `UserPromptSubmit` hooks, you can inject context using either method:1532{
1533 "ok": true | false,
1534 "reason": "Explanation for the decision"
1535}
1536```
878 1537
879 * **Plain text stdout** with exit code 0: Simplest approach, prints text1538| Field | Description |
880 * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts,1539| :------- | :--------------------------------------------------------- |
881 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 |
882 1542
883 Remember: Exit code 2 only uses `stderr` for the error message. To block using1543### Example: Multi-criteria Stop hook
884 JSON (with a custom reason), use `"decision": "block"` with exit code 0.
885</Note>
886 1544
887```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:
888#!/usr/bin/env python31546
889import json1547```json theme={null}
890import sys1548{
891import re1549 "hooks": {
892import datetime1550 "Stop": [
893 1551 {
894# Load input from stdin1552 "hooks": [
895try:1553 {
896 input_data = json.load(sys.stdin)1554 "type": "prompt",
897except 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.",
898 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)1556 "timeout": 30
899 sys.exit(1)
900
901prompt = input_data.get("prompt", "")
902
903# Check for sensitive patterns
904sensitive_patterns = [
905 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
906]
907
908for pattern, message in sensitive_patterns:
909 if re.search(pattern, prompt):
910 # Use JSON output to block with a specific reason
911 output = {
912 "decision": "block",
913 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
914 }1557 }
915 print(json.dumps(output))1558 ]
916 sys.exit(0)1559 }
1560 ]
1561 }
1562}
1563```
917 1564
918# Add current time to context1565## Agent-based hooks
919context = f"Current time: {datetime.datetime.now()}"
920print(context)
921 1566
922"""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.
923The following is also equivalent:
924print(json.dumps({
925 "hookSpecificOutput": {
926 "hookEventName": "UserPromptSubmit",
927 "additionalContext": context,
928 },
929}))
930"""
931 1568
932# Allow the prompt to proceed with the additional context1569### How agent hooks work
933sys.exit(0)
934```
935 1570
936#### JSON Output Example: PreToolUse with Approval1571When an agent hook fires:
937
938```python theme={null}
939#!/usr/bin/env python3
940import json
941import sys
942
943# Load input from stdin
944try:
945 input_data = json.load(sys.stdin)
946except json.JSONDecodeError as e:
947 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
948 sys.exit(1)
949
950tool_name = input_data.get("tool_name", "")
951tool_input = input_data.get("tool_input", {})
952
953# Example: Auto-approve file reads for documentation files
954if tool_name == "Read":
955 file_path = tool_input.get("file_path", "")
956 if file_path.endswith((".md", ".mdx", ".txt", ".json")):
957 # Use JSON output to auto-approve the tool call
958 output = {
959 "decision": "approve",
960 "reason": "Documentation file auto-approved",
961 "suppressOutput": True # Don't show in verbose mode
962 }
963 print(json.dumps(output))
964 sys.exit(0)
965
966# For other cases, let the normal permission flow proceed
967sys.exit(0)
968```
969 1572
970## 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
971 1577
972Claude 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.
973[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers
974provide tools, they appear with a special naming pattern that you can match in
975your hooks.
976 1579
977### MCP Tool Naming1580### Agent hook configuration
978 1581
979MCP 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:
980 1583
981* `mcp__memory__create_entities` - Memory server's create entities tool1584| Field | Required | Description |
982* `mcp__filesystem__read_file` - Filesystem server's read file tool1585| :-------- | :------- | :------------------------------------------------------------------------------------------ |
983* `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 |
984 1590
985### Configuring Hooks for MCP Tools1591The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.
986 1592
987You can target specific MCP tools or entire MCP servers:1593This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
988 1594
989```json theme={null}1595```json theme={null}
990{1596{
991 "hooks": {1597 "hooks": {
992 "PreToolUse": [1598 "Stop": [
993 {1599 {
994 "matcher": "mcp__memory__.*",
995 "hooks": [1600 "hooks": [
996 {1601 {
997 "type": "command",1602 "type": "agent",
998 "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
999 }1605 }
1000 ]1606 ]
1001 },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": [
1002 {1627 {
1003 "matcher": "mcp__.*__write.*",1628 "matcher": "Write",
1004 "hooks": [1629 "hooks": [
1005 {1630 {
1006 "type": "command",1631 "type": "command",
1007 "command": "/home/user/scripts/validate-mcp-write.py"1632 "command": "/path/to/run-tests.sh",
1633 "async": true,
1634 "timeout": 120
1008 }1635 }
1009 ]1636 ]
1010 }1637 }
1013}1640}
1014```1641```
1015 1642
1016## 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.
1017 1644
1018<Tip>1645### How async hooks execute
1019 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/hooks-guide#more-examples) in the get started guide.
1020</Tip>
1021
1022## Security Considerations
1023
1024### Disclaimer
1025 1646
1026**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on1647When 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.
1027your system automatically. By using hooks, you acknowledge that:
1028 1648
1029* You are solely responsible for the commands you configure1649After 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.
1030* Hooks can modify, delete, or access any files your user account can access
1031* Malicious or poorly written hooks can cause data loss or system damage
1032* Anthropic provides no warranty and assumes no liability for any damages
1033 resulting from hook usage
1034* You should thoroughly test hooks in a safe environment before production use
1035 1650
1036Always review and understand any hook commands before adding them to your1651### Example: run tests after file changes
1037configuration.
1038 1652
1039### Security Best Practices1653This 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`:
1040 1654
1041Here are some key practices for writing more secure hooks:1655```bash theme={null}
1656#!/bin/bash
1657# run-tests-async.sh
1042 1658
10431. **Validate and sanitize inputs** - Never trust input data blindly1659# Read hook input from stdin
10442. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1660INPUT=$(cat)
10453. **Block path traversal** - Check for `..` in file paths1661FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
10464. **Use absolute paths** - Specify full paths for scripts (use
1047 "\$CLAUDE\_PROJECT\_DIR" for the project path)
10485. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.
1049 1662
1050### Configuration Safety1663# Only run tests for source files
1664if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
1665 exit 0
1666fi
1051 1667
1052Direct edits to hooks in settings files don't take effect immediately. Claude1668# Run tests and report results via systemMessage
1053Code:1669RESULT=$(npm test 2>&1)
1670EXIT_CODE=$?
1054 1671
10551. Captures a snapshot of hooks at startup1672if [ $EXIT_CODE -eq 0 ]; then
10562. Uses this snapshot throughout the session1673 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
10573. Warns if hooks are modified externally1674else
10584. Requires review in `/hooks` menu for changes to apply1675 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
1676fi
1677```
1059 1678
1060This 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:
1061 1680
1062## 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```
1063 1700
1064* **Timeout**: 60-second execution limit by default, configurable per command.1701### Limitations
1065 * A timeout for an individual command does not affect the other commands.
1066* **Parallelization**: All matching hooks run in parallel
1067* **Deduplication**: Multiple identical hook commands are deduplicated automatically
1068* **Environment**: Runs in current directory with Claude Code's environment
1069 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the
1070 absolute path to the project root directory (where Claude Code was started)
1071 * 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.
1072* **Input**: JSON via stdin
1073* **Output**:
1074 * PreToolUse/PermissionRequest/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o)
1075 * Notification/SessionEnd: Logged to debug only (`--debug`)
1076 * UserPromptSubmit/SessionStart: stdout added as context for Claude
1077 1702
1078## Debugging1703Async hooks have several constraints compared to synchronous hooks:
1079 1704
1080### 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.
1081 1709
1082If your hooks aren't working:1710## Security considerations
1083 1711
10841. **Check configuration** - Run `/hooks` to see if your hook is registered1712### Disclaimer
10852. **Verify syntax** - Ensure your JSON settings are valid
10863. **Test commands** - Run hook commands manually first
10874. **Check permissions** - Make sure scripts are executable
10885. **Review logs** - Use `claude --debug` to see hook execution details
1089 1713
1090Common issues:1714Hooks run with your system user's full permissions.
1091 1715
1092* **Quotes not escaped** - Use `\"` inside JSON strings1716<Warning>
1093* **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.
1094* **Command not found** - Use full paths for scripts1718</Warning>
1095 1719
1096### Advanced Debugging1720### Security best practices
1097 1721
1098For complex hook issues:1722Keep these practices in mind when writing hooks:
1099 1723
11001. **Inspect hook execution** - Use `claude --debug` to see detailed hook1724* **Validate and sanitize inputs**: never trust input data blindly
1101 execution1725* **Always quote shell variables**: use `"$VAR"` not `$VAR`
11022. **Validate JSON schemas** - Test hook input/output with external tools1726* **Block path traversal**: check for `..` in file paths
11033. **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
11044. **Test edge cases** - Try hooks with unusual file paths or inputs1728* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.
11055. **Monitor system resources** - Check for resource exhaustion during hook
1106 execution
11076. **Use structured logging** - Implement logging in your hook scripts
1108 1729
1109### Debug Output Example1730## Debug hooks
1110 1731
1111Use `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.
1112 1733
1113```1734```text theme={null}
1114[DEBUG] Executing hooks for PostToolUse:Write1735[DEBUG] Executing hooks for PostToolUse:Write
1115[DEBUG] Getting matching hook commands for PostToolUse with query: Write1736[DEBUG] Getting matching hook commands for PostToolUse with query: Write
1116[DEBUG] Found 1 hook matchers in settings1737[DEBUG] Found 1 hook matchers in settings
1117[DEBUG] Matched 1 hooks for query "Write"1738[DEBUG] Matched 1 hooks for query "Write"
1118[DEBUG] Found 1 hook commands to execute1739[DEBUG] Found 1 hook commands to execute
1119[DEBUG] Executing hook command: <Your command> with timeout 60000ms1740[DEBUG] Executing hook command: <Your command> with timeout 600000ms
1120[DEBUG] Hook command completed with status 0: <Your stdout>1741[DEBUG] Hook command completed with status 0: <Your stdout>
1121```1742```
1122 1743
1123Progress 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.
1124
1125* Which hook is running
1126* Command being executed
1127* Success/failure status
1128* Output or error messages
1129
1130
1131
1132> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt