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/docs/claude-code/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/docs/claude-code/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` 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`, `Notification`, `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/docs/claude-code/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/docs/claude-code/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 273
215### Example: Intelligent Stop hook274In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:
216 275
217```json theme={null}276| Field | Required | Description |
218{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 {
219 "hooks": {296 "hooks": {
220 "Stop": [297 "PostToolUse": [
221 {298 {
299 "matcher": "Write|Edit",
222 "hooks": [300 "hooks": [
223 {301 {
224 "type": "prompt",302 "type": "command",
225 "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"
226 "timeout": 30
227 }304 }
228 ]305 ]
229 }306 }
230 ]307 ]
231 }308 }
232}309 }
233```310 ```
311 </Tab>
234 312
235### 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.
236 315
237```json theme={null}316 This example runs a formatting script bundled with the plugin:
238{317
318 ```json theme={null}
319 {
320 "description": "Automatic code formatting",
239 "hooks": {321 "hooks": {
240 "SubagentStop": [322 "PostToolUse": [
241 {323 {
324 "matcher": "Write|Edit",
242 "hooks": [325 "hooks": [
243 {326 {
244 "type": "prompt",327 "type": "command",
245 "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
246 }330 }
247 ]331 ]
248 }332 }
249 ]333 ]
250 }334 }
251}335 }
336 ```
337
338 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.
339 </Tab>
340</Tabs>
341
342### Hooks in skills and agents
343
344In 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.
345
346All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes.
347
348Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.
349
350This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
351
352```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---
252```363```
253 364
254### Comparison with bash command hooks365Agents use the same format in their YAML frontmatter.
255 366
256| Feature | Bash Command Hooks | Prompt-Based Hooks |367### The `/hooks` menu
257| --------------------- | ----------------------- | ------------------------------ |
258| **Execution** | Runs bash script | Queries LLM |
259| **Decision logic** | You implement in code | LLM evaluates context |
260| **Setup complexity** | Requires script file | Just configure prompt |
261| **Context awareness** | Limited to script logic | Natural language understanding |
262| **Performance** | Fast (local execution) | Slower (API call) |
263| **Use case** | Deterministic rules | Context-aware decisions |
264 368
265### Best practices369Type `/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.
266 370
267* **Be specific in prompts**: Clearly state what you want the LLM to evaluate371Each hook in the menu is labeled with a bracket prefix indicating its source:
268* **Include decision criteria**: List the factors the LLM should consider
269* **Test your prompts**: Verify the LLM makes correct decisions for your use cases
270* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed
271* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules
272 372
273See the [plugin components reference](/en/docs/claude-code/plugins-reference#hooks) for details on creating plugin hooks.373* `[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
274 377
275## Hook Events378### Disable or remove hooks
276 379
277### PreToolUse380To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it.
278 381
279Runs after Claude creates tool parameters and before processing the tool call.382To 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.
280 383
281**Common matchers:**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.
282 385
283* `Task` - Subagent tasks (see [subagents documentation](/en/docs/claude-code/sub-agents))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.
284* `Bash` - Shell commands
285* `Glob` - File pattern matching
286* `Grep` - Content search
287* `Read` - File reading
288* `Edit` - File editing
289* `Write` - File writing
290* `WebFetch`, `WebSearch` - Web operations
291 387
292### PostToolUse388## Hook input and output
293 389
294Runs immediately after a tool completes successfully.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.
295 391
296Recognizes the same matcher values as PreToolUse.392### Common input fields
297 393
298### PostCustomToolCall394All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section:
299 395
300Runs after an MCP tool completes but **before** `PostToolUse` hooks execute. This hook allows you to modify the tool's output before it's processed further or shown to the model.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 |
301 403
302**Key characteristics:**404For example, a `PreToolUse` hook for a Bash command receives this on stdin:
303 405
304* **Only runs for MCP tools** (tools starting with `mcp__`)406```json theme={null}
305* Executes after the tool completes but before `PostToolUse` hooks407{
306* Can modify tool output using the `updatedOutput` field408 "session_id": "abc123",
307* Original tool response is replaced with modified output409 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
410 "cwd": "/home/user/my-project",
411 "permission_mode": "default",
412 "hook_event_name": "PreToolUse",
413 "tool_name": "Bash",
414 "tool_input": {
415 "command": "npm test"
416 }
417}
418```
308 419
309**Common use cases:**420The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.
310 421
311* Adding metadata to MCP tool responses422### Exit code output
312* Filtering sensitive information from tool outputs
313* Transforming response formats
314* Logging MCP tool usage with enriched data
315 423
316**Important**: If multiple hooks provide `updatedOutput` for the same tool call, they may conflict. Hook execution order is non-deterministic when hooks run in parallel. Only configure one hook per tool to modify output.424The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.
317 425
318**Matchers:**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.
319Recognizes the same matcher values as PreToolUse, but will only execute for MCP tools (`mcp__*`).
320 427
321### Notification428**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.
322 429
323Runs when Claude Code sends notifications. Notifications are sent when:430**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.
324 431
3251. Claude needs your permission to use a tool. Example: "Claude needs your432For example, a hook command script that blocks dangerous Bash commands:
326 permission to use Bash"
3272. The prompt input has been idle for at least 60 seconds. "Claude is waiting
328 for your input"
329 433
330### UserPromptSubmit434```bash theme={null}
435#!/bin/bash
436# Reads JSON input from stdin, checks the command
437command=$(jq -r '.tool_input.command' < /dev/stdin)
331 438
332Runs when the user submits a prompt, before Claude processes it. This allows you439if [[ "$command" == rm* ]]; then
333to add additional context based on the prompt/conversation, validate prompts, or440 echo "Blocked: rm commands are not allowed" >&2
334block certain types of prompts.441 exit 2 # Blocking error: tool call is prevented
442fi
335 443
336### Stop444exit 0 # Success: tool call proceeds
445```
337 446
338Runs when the main Claude Code agent has finished responding. Does not run if447#### Exit code 2 behavior per event
339the stoppage occurred due to a user interrupt.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.
340 474
341### SubagentStop475<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>
342 478
343Runs when a Claude Code subagent (Task tool call) has finished responding.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.
344 480
345### PreCompact481The JSON object supports three kinds of fields:
346 482
347Runs before Claude Code is about to run a compact operation.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.
348 486
349**Matchers:**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 |
350 493
351* `manual` - Invoked from `/compact`494To stop Claude entirely regardless of event type:
352* `auto` - Invoked from auto-compact (due to full context window)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}
520 {
521 "decision": "block",
522 "reason": "Test suite must pass before proceeding"
523 }
524 ```
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}
531 {
532 "hookSpecificOutput": {
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}
545 {
546 "hookSpecificOutput": {
547 "hookEventName": "PermissionRequest",
548 "decision": {
549 "behavior": "allow",
550 "updatedInput": {
551 "command": "npm run lint"
552 }
553 }
554 }
555 }
556 ```
557 </Tab>
558</Tabs>
559
560For 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).
561
562## Hook events
563
564Each 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.
353 565
354### SessionStart566### SessionStart
355 567
356Runs when Claude Code starts a new session or resumes an existing session (which568Runs 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.
357currently does start a new session under the hood). Useful for loading in569
358development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables.570SessionStart runs on every session, so keep these hooks fast.
359 571
360**Matchers:**572The matcher value corresponds to how the session was initiated:
361 573
362* `startup` - Invoked from startup574| Matcher | When it fires |
363* `resume` - Invoked from `--resume`, `--continue`, or `/resume`575| :-------- | :------------------------------------- |
364* `clear` - Invoked from `/clear`576| `startup` | New session |
365* `compact` - Invoked from auto or manual compact.577| `resume` | `--resume`, `--continue`, or `/resume` |
578| `clear` | `/clear` |
579| `compact` | Auto or manual compaction |
366 580
367#### Persisting environment variables581#### SessionStart input
368 582
369SessionStart 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.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.
370 584
371**Example: Setting individual environment variables**585```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
598
599Any text your hook script prints to stdout is added as context for Claude. In addition to the [JSON output fields](#json-output) available to all hooks, you can return these event-specific fields:
600
601| Field | Description |
602| :------------------ | :------------------------------------------------------------------------ |
603| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |
604
605```json theme={null}
606{
607 "hookSpecificOutput": {
608 "hookEventName": "SessionStart",
609 "additionalContext": "My additional context here"
610 }
611}
612```
613
614#### Persist environment variables
615
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.
617
618To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:
372 619
373```bash theme={null}620```bash theme={null}
374#!/bin/bash621#!/bin/bash
375 622
376if [ -n "$CLAUDE_ENV_FILE" ]; then623if [ -n "$CLAUDE_ENV_FILE" ]; then
377 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"624 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
378 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"625 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
379 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"626 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
380fi627fi
381 628
382exit 0629exit 0
383```630```
384 631
385**Example: Persisting all environment changes from the hook**632To capture all environment changes from setup commands, compare the exported variables before and after:
386
387When your setup modifies the environment (e.g., `nvm use`), capture and persist all changes by diffing the environment:
388 633
389```bash theme={null}634```bash theme={null}
390#!/bin/bash635#!/bin/bash
403exit 0648exit 0
404```649```
405 650
406Any 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.
407 652
408<Note>653<Note>
409 `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.
410</Note>655</Note>
411 656
412### SessionEnd657### UserPromptSubmit
413
414Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
415statistics, or saving session state.
416
417The `reason` field in the hook input will be one of:
418 658
419* `clear` - Session cleared with /clear command659Runs when the user submits a prompt, before Claude processes it. This allows you
420* `logout` - User logged out660to add additional context based on the prompt/conversation, validate prompts, or
421* `prompt_input_exit` - User exited while prompt input was visible661block certain types of prompts.
422* `other` - Other exit reasons
423 662
424## Hook Input663#### UserPromptSubmit input
425 664
426Hooks receive JSON data via stdin containing session information and665In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
427event-specific data:
428 666
429```typescript theme={null}667```json theme={null}
430{668{
431 // Common fields669 "session_id": "abc123",
432 session_id: string670 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
433 transcript_path: string // Path to conversation JSON671 "cwd": "/Users/...",
434 cwd: string // The current working directory when the hook is invoked672 "permission_mode": "default",
435 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions"673 "hook_event_name": "UserPromptSubmit",
436 674 "prompt": "Write a function to calculate the factorial of a number"
437 // Event-specific fields
438 hook_event_name: string
439 ...
440}675}
441```676```
442 677
443### PreToolUse Input678#### UserPromptSubmit decision control
444 679
445The exact schema for `tool_input` depends on the tool.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 |
446 696
447```json theme={null}697```json theme={null}
448{698{
449 "session_id": "abc123",699 "decision": "block",
450 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",700 "reason": "Explanation for decision",
451 "cwd": "/Users/...",701 "hookSpecificOutput": {
452 "permission_mode": "default",702 "hookEventName": "UserPromptSubmit",
453 "hook_event_name": "PreToolUse",703 "additionalContext": "My additional context here"
454 "tool_name": "Write",
455 "tool_input": {
456 "file_path": "/path/to/file.txt",
457 "content": "file content"
458 }704 }
459}705}
460```706```
461 707
462### PostToolUse Input708<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>
463 712
464The exact schema for `tool_input` and `tool_response` depends on the tool.713### PreToolUse
465 714
466```json theme={null}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).
467{716
717Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.
718
719#### PreToolUse input
720
721In addition to the [common input fields](#common-input-fields), PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool:
722
723##### Bash
724
725Executes shell commands.
726
727| Field | Type | Example | Description |
728| :------------------ | :------ | :----------------- | :-------------------------------------------- |
729| `command` | string | `"npm test"` | The shell command to execute |
730| `description` | string | `"Run test suite"` | Optional description of what the command does |
731| `timeout` | number | `120000` | Optional timeout in milliseconds |
732| `run_in_background` | boolean | `false` | Whether to run the command in background |
733
734##### Write
735
736Creates or overwrites a file.
737
738| Field | Type | Example | Description |
739| :---------- | :----- | :-------------------- | :--------------------------------- |
740| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |
741| `content` | string | `"file content"` | Content to write to the file |
742
743##### Edit
744
745Replaces a string in an existing file.
746
747| Field | Type | Example | Description |
748| :------------ | :------ | :-------------------- | :--------------------------------- |
749| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |
750| `old_string` | string | `"original text"` | Text to find and replace |
751| `new_string` | string | `"replacement text"` | Replacement text |
752| `replace_all` | boolean | `false` | Whether to replace all occurrences |
753
754##### Read
755
756Reads file contents.
757
758| Field | Type | Example | Description |
759| :---------- | :----- | :-------------------- | :----------------------------------------- |
760| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |
761| `offset` | number | `10` | Optional line number to start reading from |
762| `limit` | number | `50` | Optional number of lines to read |
763
764##### Glob
765
766Finds files matching a glob pattern.
767
768| Field | Type | Example | Description |
769| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |
770| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |
771| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |
772
773##### Grep
774
775Searches file contents with regular expressions.
776
777| Field | Type | Example | Description |
778| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |
779| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |
780| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |
781| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |
782| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |
783| `-i` | boolean | `true` | Case insensitive search |
784| `multiline` | boolean | `false` | Enable multiline matching |
785
786##### WebFetch
787
788Fetches and processes web content.
789
790| Field | Type | Example | Description |
791| :------- | :----- | :---------------------------- | :----------------------------------- |
792| `url` | string | `"https://example.com/api"` | URL to fetch content from |
793| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |
794
795##### WebSearch
796
797Searches the web.
798
799| Field | Type | Example | Description |
800| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |
801| `query` | string | `"react hooks best practices"` | Search query |
802| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |
803| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |
804
805##### Task
806
807Spawns a [subagent](/en/sub-agents).
808
809| Field | Type | Example | Description |
810| :-------------- | :----- | :------------------------- | :------------------------------------------- |
811| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |
812| `description` | string | `"Find API endpoints"` | Short description of the task |
813| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |
814| `model` | string | `"sonnet"` | Optional model alias to override the default |
815
816#### PreToolUse decision control
817
818`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: three outcomes (allow, deny, or ask) plus the ability to modify tool input before execution.
819
820| Field | Description |
821| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |
822| `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm |
823| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |
824| `updatedInput` | Modifies the tool's input parameters before execution. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user |
825| `additionalContext` | String added to Claude's context before the tool executes |
826
827```json theme={null}
828{
829 "hookSpecificOutput": {
830 "hookEventName": "PreToolUse",
831 "permissionDecision": "allow",
832 "permissionDecisionReason": "My reason here",
833 "updatedInput": {
834 "field_to_modify": "new value"
835 },
836 "additionalContext": "Current environment: production. Proceed with caution."
837 }
838}
839```
840
841<Note>
842 PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.
843</Note>
844
845### PermissionRequest
846
847Runs when the user is shown a permission dialog.
848Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.
849
850Matches on tool name, same values as PreToolUse.
851
852#### PermissionRequest input
853
854PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the "always allow" options the user would normally see in the permission dialog. The difference is when the hook fires: PermissionRequest hooks run when a permission dialog is about to be shown to the user, while PreToolUse hooks run before tool execution regardless of permission status.
855
856```json theme={null}
857{
858 "session_id": "abc123",
859 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
860 "cwd": "/Users/...",
861 "permission_mode": "default",
862 "hook_event_name": "PermissionRequest",
863 "tool_name": "Bash",
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 ]
871}
872```
873
874#### PermissionRequest decision control
875
876`PermissionRequest` hooks can allow or deny permission requests. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return a `decision` object with these event-specific fields:
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.
909
910```json theme={null}
911{
468 "session_id": "abc123",912 "session_id": "abc123",
469 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",913 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
470 "cwd": "/Users/...",914 "cwd": "/Users/...",
478 "tool_response": {922 "tool_response": {
479 "filePath": "/path/to/file.txt",923 "filePath": "/path/to/file.txt",
480 "success": true924 "success": true
925 },
926 "tool_use_id": "toolu_01ABC123..."
927}
928```
929
930#### 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"
481 }948 }
482}949}
483```950```
484 951
485### PostCustomToolCall Input952### 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.
486 957
487The exact schema for `tool_input` and `tool_response` depends on the MCP tool.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:
488 961
489```json theme={null}962```json theme={null}
490{963{
492 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",965 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
493 "cwd": "/Users/...",966 "cwd": "/Users/...",
494 "permission_mode": "default",967 "permission_mode": "default",
495 "hook_event_name": "PostCustomToolCall",968 "hook_event_name": "PostToolUseFailure",
496 "tool_name": "mcp__github__create_issue",969 "tool_name": "Bash",
497 "tool_input": {970 "tool_input": {
498 "title": "Bug report",971 "command": "npm test",
499 "body": "Description of the issue"972 "description": "Run test suite"
500 },973 },
501 "tool_response": {974 "tool_use_id": "toolu_01ABC123...",
502 "issue_number": 42,975 "error": "Command exited with non-zero status code 1",
503 "url": "https://github.com/org/repo/issues/42"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"
504 }998 }
505}999}
506```1000```
507 1001
508### Notification Input1002### 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.
509 1038
510```json theme={null}1039```json theme={null}
511{1040{
514 "cwd": "/Users/...",1043 "cwd": "/Users/...",
515 "permission_mode": "default",1044 "permission_mode": "default",
516 "hook_event_name": "Notification",1045 "hook_event_name": "Notification",
517 "message": "Task completed successfully"1046 "message": "Claude needs your permission to use Bash",
1047 "title": "Permission needed",
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).
551 1117
552For `manual`, `custom_instructions` comes from what the user passes into1118### Stop
553`/compact`. For `auto`, `custom_instructions` is empty.1119
1120Runs when the main Claude Code agent has finished responding. Does not run if
1121the stoppage occurred due to a user interrupt.
1122
1123#### Stop input
1124
1125In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active` and `last_assistant_message`. The `stop_hook_active` field is `true` when Claude Code is already continuing as a result of a stop hook. Check this value or process the transcript to prevent Claude Code from running indefinitely. The `last_assistant_message` field contains the text content of Claude's final response, so hooks can access it without parsing the transcript file.
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 |
1223| :----------------- | :------------------------------------------------------ |
1224| `task_id` | Identifier of the task being completed |
1225| `task_subject` | Title of the task |
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 |
592 1229
593There are two ways for hooks to return output back to Claude Code. The output1230#### TaskCompleted decision control
594communicates whether to block and any feedback that should be shown to Claude
595and the user.
596 1231
597### Simple: Exit Code1232TaskCompleted hooks use exit codes only, not JSON decision control. This example runs tests and blocks task completion if they fail:
598 1233
599Hooks communicate status through exit codes, stdout, and stderr:1234```bash theme={null}
1235#!/bin/bash
1236INPUT=$(cat)
1237TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
600 1238
601* **Exit code 0**: Success. `stdout` is shown to the user in transcript mode1239# Run the test suite
602 (CTRL-R), except for `UserPromptSubmit` and `SessionStart`, where stdout is1240if ! npm test 2>&1; then
603 added to the context.1241 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
604* **Exit code 2**: Blocking error. `stderr` is fed back to Claude to process1242 exit 2
605 automatically. See per-hook-event behavior below.1243fi
606* **Other exit codes**: Non-blocking error. `stderr` is shown to the user and
607 execution continues.
608 1244
609<Warning>1245exit 0
610 Reminder: Claude Code does not see stdout if the exit code is 0, except for1246```
611 the `UserPromptSubmit` hook where stdout is injected as context.
612</Warning>
613 1247
614#### Exit Code 2 Behavior1248### ConfigChange
615 1249
616| Hook Event | Behavior |1250Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
617| ------------------ | ------------------------------------------------------------------ |
618| `PreToolUse` | Blocks the tool call, shows stderr to Claude |
619| `PostToolUse` | Shows stderr to Claude (tool already ran) |
620| `Notification` | N/A, shows stderr to user only |
621| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |
622| `Stop` | Blocks stoppage, shows stderr to Claude |
623| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |
624| `PreCompact` | N/A, shows stderr to user only |
625| `SessionStart` | N/A, shows stderr to user only |
626| `SessionEnd` | N/A, shows stderr to user only |
627 1251
628### Advanced: JSON Output1252ConfigChange 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.
629 1253
630Hooks can return structured JSON in `stdout` for more sophisticated control:1254The matcher filters on the configuration source:
631 1255
632#### 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 |
633 1263
634All hook types can include these optional fields:1264This example logs all configuration changes for security auditing:
635 1265
636```json theme={null}1266```json theme={null}
637{1267{
638 "continue": true, // Whether Claude should continue after hook execution (default: true)1268 "hooks": {
639 "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
640 1284
641 "suppressOutput": true, // Hide stdout from transcript mode (default: false)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.
642 "systemMessage": "string" // Optional warning message shown to the user1286
1287```json theme={null}
1288{
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"
643}1296}
644```1297```
645 1298
646If `continue` is false, Claude stops processing after the hooks run.1299#### ConfigChange decision control
647 1300
648* 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.
649 only blocks a specific tool call and provides automatic feedback to Claude.
650* For `PostToolUse`, this is different from `"decision": "block"`, which
651 provides automated feedback to Claude.
652* For `UserPromptSubmit`, this prevents the prompt from being processed.
653* For `Stop` and `SubagentStop`, this takes precedence over any
654 `"decision": "block"` output.
655* In all cases, `"continue" = false` takes precedence over any
656 `"decision": "block"` output.
657 1302
658`stopReason` accompanies `continue` with a reason shown to the user, not shown1303| Field | Description |
659to 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"` |
660 1307
661#### `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.
662 1316
663`PreToolUse` hooks can control whether a tool call proceeds.1317### WorktreeCreate
664 1318
665* `"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.
666 to the user but not to Claude.
667* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is
668 shown to Claude.
669* `"ask"` asks the user to confirm the tool call in the UI.
670 `permissionDecisionReason` is shown to the user but not to Claude.
671 1320
672Additionally, 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.
673 1322
674* `updatedInput` allows you to modify the tool's input parameters before the tool executes. This is a `Record<string, unknown>` object containing the fields you want to change or add.1323This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
675* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.
676 1324
677```json theme={null}1325```json theme={null}
678{1326{
679 "hookSpecificOutput": {1327 "hooks": {
680 "hookEventName": "PreToolUse",1328 "WorktreeCreate": [
681 "permissionDecision": "allow"1329 {
682 "permissionDecisionReason": "My reason here",1330 "hooks": [
683 "updatedInput": {1331 {
684 "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\"'"
685 }1334 }
1335 ]
1336 }
1337 ]
686 }1338 }
687}1339}
688```1340```
689 1341
690<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.
691 The `decision` and `reason` fields are deprecated for PreToolUse hooks.
692 Use `hookSpecificOutput.permissionDecision` and
693 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields
694 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.
695</Note>
696 1343
697#### `PostToolUse` Decision Control1344#### WorktreeCreate input
698 1345
699`PostToolUse` hooks can provide feedback to Claude after tool execution.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`).
700
701* `"block"` automatically prompts Claude with `reason`.
702* `undefined` does nothing. `reason` is ignored.
703* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.
704 1347
705```json theme={null}1348```json theme={null}
706{1349{
707 "decision": "block" | undefined,1350 "session_id": "abc123",
708 "reason": "Explanation for decision",1351 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
709 "hookSpecificOutput": {1352 "cwd": "/Users/...",
710 "hookEventName": "PostToolUse",1353 "hook_event_name": "WorktreeCreate",
711 "additionalContext": "Additional information for Claude"1354 "name": "feature-auth"
712 }
713}1355}
714```1356```
715 1357
716#### `PostCustomToolCall` Output Control1358#### 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.
717 1361
718`PostCustomToolCall` hooks can modify MCP tool outputs before they're processed further.1362WorktreeCreate 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.
719 1363
720* `"hookSpecificOutput.updatedOutput"` replaces the original tool response1364### WorktreeRemove
721* The modified output is shown to Claude instead of the original response1365
722* This runs **before** `PostToolUse` hooks, so they see the modified output1366The 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.
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:
723 1369
724```json theme={null}1370```json theme={null}
725{1371{
726 "hookSpecificOutput": {1372 "hooks": {
727 "hookEventName": "PostCustomToolCall",1373 "WorktreeRemove": [
728 "updatedOutput": {1374 {
729 "issue_number": 42,1375 "hooks": [
730 "url": "https://github.com/org/repo/issues/42",1376 {
731 "hook_processed": true,1377 "type": "command",
732 "processed_at": "2025-01-01T00:00:00Z"1378 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
1379 }
1380 ]
733 }1381 }
1382 ]
734 }1383 }
735}1384}
736```1385```
737 1386
738**Example: Adding metadata to MCP tool responses**1387#### WorktreeRemove input
739 1388
740```bash theme={null}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.
741#!/bin/bash
742# Read JSON input from stdin
743INPUT=$(cat)
744 1390
745# Extract tool information1391```json theme={null}
746TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')1392{
747TOOL_RESPONSE=$(echo "$INPUT" | jq -r '.tool_response')1393 "session_id": "abc123",
1394 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1395 "cwd": "/Users/...",
1396 "hook_event_name": "WorktreeRemove",
1397 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
1398}
1399```
748 1400
749# Only process MCP tools1401WorktreeRemove 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.
750if [[ "$TOOL_NAME" != mcp__* ]]; then
751 exit 0
752fi
753 1402
754# Add metadata to the response1403### PreCompact
755UPDATED_OUTPUT=$(echo "$TOOL_RESPONSE" | jq '. + {"hook_processed": true, "processed_at": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"}')
756 1404
757# Output the modified response1405Runs before Claude Code is about to run a compact operation.
758jq -n --argjson output "$UPDATED_OUTPUT" '{
759 "hookSpecificOutput": {
760 "hookEventName": "PostCustomToolCall",
761 "updatedOutput": $output
762 }
763}'
764```
765 1406
766<Warning>1407The matcher value indicates whether compaction was triggered manually or automatically:
767 If multiple hooks provide `updatedOutput` for the same tool call, conflicts may occur since hooks run in parallel. Only configure one hook per tool to modify output.
768</Warning>
769 1408
770#### `UserPromptSubmit` Decision Control1409| Matcher | When it fires |
1410| :------- | :------------------------------------------- |
1411| `manual` | `/compact` |
1412| `auto` | Auto-compact when the context window is full |
771 1413
772`UserPromptSubmit` hooks can control whether a user prompt is processed.1414#### PreCompact input
773 1415
774* `"block"` prevents the prompt from being processed. The submitted prompt is1416In 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.
775 erased from context. `"reason"` is shown to the user but not added to context.
776* `undefined` allows the prompt to proceed normally. `"reason"` is ignored.
777* `"hookSpecificOutput.additionalContext"` adds the string to the context if not
778 blocked.
779 1417
780```json theme={null}1418```json theme={null}
781{1419{
782 "decision": "block" | undefined,1420 "session_id": "abc123",
783 "reason": "Explanation for decision",1421 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
784 "hookSpecificOutput": {1422 "cwd": "/Users/...",
785 "hookEventName": "UserPromptSubmit",1423 "permission_mode": "default",
786 "additionalContext": "My additional context here"1424 "hook_event_name": "PreCompact",
787 }1425 "trigger": "manual",
1426 "custom_instructions": ""
788}1427}
789```1428```
790 1429
791#### `Stop`/`SubagentStop` Decision Control1430### SessionEnd
792 1431
793`Stop` and `SubagentStop` hooks can control whether Claude must continue.1432Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
1433statistics, or saving session state. Supports matchers to filter by exit reason.
794 1434
795* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1435The `reason` field in the hook input indicates why the session ended:
796 to know how to proceed.1436
797* `undefined` allows Claude to stop. `reason` is ignored.1437| Reason | Description |
1438| :---------------------------- | :----------------------------------------- |
1439| `clear` | Session cleared with `/clear` command |
1440| `logout` | User logged out |
1441| `prompt_input_exit` | User exited while prompt input was visible |
1442| `bypass_permissions_disabled` | Bypass permissions mode was disabled |
1443| `other` | Other exit reasons |
1444
1445#### SessionEnd input
1446
1447In addition to the [common input fields](#common-input-fields), SessionEnd hooks receive a `reason` field indicating why the session ended. See the [reason table](#sessionend) above for all values.
798 1448
799```json theme={null}1449```json theme={null}
800{1450{
801 "decision": "block" | undefined,1451 "session_id": "abc123",
802 "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"
803}1457}
804```1458```
805 1459
806#### `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.
1465
1466Events that support all three hook types (`command`, `prompt`, and `agent`):
1467
1468* `PermissionRequest`
1469* `PostToolUse`
1470* `PostToolUseFailure`
1471* `PreToolUse`
1472* `Stop`
1473* `SubagentStop`
1474* `TaskCompleted`
1475* `UserPromptSubmit`
807 1476
808`SessionStart` hooks allow you to load in context at the start of a session.1477Events that only support `type: "command"` hooks:
809 1478
810* `"hookSpecificOutput.additionalContext"` adds the string to the context.1479* `ConfigChange`
811* Multiple hooks' `additionalContext` values are concatenated.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:
812 1502
813```json theme={null}1503```json theme={null}
814{1504{
815 "hookSpecificOutput": {1505 "hooks": {
816 "hookEventName": "SessionStart",1506 "Stop": [
817 "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 ]
818 }1516 }
819}1517}
820```1518```
821 1519
822#### `SessionEnd` Decision Control1520| Field | Required | Description |
823 1521| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
824`SessionEnd` hooks run when a session ends. They cannot block session termination1522| `type` | yes | Must be `"prompt"` |
825but 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 |
826 1524| `model` | no | Model to use for evaluation. Defaults to a fast model |
827#### Exit Code Example: Bash Command Validation1525| `timeout` | no | Timeout in seconds. Default: 30 |
828 1526
829```python theme={null}1527### Response schema
830#!/usr/bin/env python31528
831import json1529The LLM must respond with JSON containing:
832import re1530
833import sys1531```json theme={null}
834 1532{
835# Define validation rules as a list of (regex pattern, message) tuples1533 "ok": true | false,
836VALIDATION_RULES = [1534 "reason": "Explanation for the decision"
837 (1535}
838 r"\bgrep\b(?!.*\|)",
839 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
840 ),
841 (
842 r"\bfind\s+\S+\s+-name\b",
843 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
844 ),
845]
846
847
848def validate_command(command: str) -> list[str]:
849 issues = []
850 for pattern, message in VALIDATION_RULES:
851 if re.search(pattern, command):
852 issues.append(message)
853 return issues
854
855
856try:
857 input_data = json.load(sys.stdin)
858except json.JSONDecodeError as e:
859 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
860 sys.exit(1)
861
862tool_name = input_data.get("tool_name", "")
863tool_input = input_data.get("tool_input", {})
864command = tool_input.get("command", "")
865
866if tool_name != "Bash" or not command:
867 sys.exit(1)
868
869# Validate the command
870issues = validate_command(command)
871
872if issues:
873 for message in issues:
874 print(f"• {message}", file=sys.stderr)
875 # Exit code 2 blocks tool call and shows stderr to Claude
876 sys.exit(2)
877```1536```
878 1537
879#### JSON Output Example: UserPromptSubmit to Add Context and Validation1538| Field | Description |
1539| :------- | :--------------------------------------------------------- |
1540| `ok` | `true` allows the action, `false` prevents it |
1541| `reason` | Required when `ok` is `false`. Explanation shown to Claude |
880 1542
881<Note>1543### Example: Multi-criteria Stop hook
882 For `UserPromptSubmit` hooks, you can inject context using either method:
883 1544
884 * Exit code 0 with stdout: Claude sees the context (special case for `UserPromptSubmit`)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:
885 * JSON output: Provides more control over the behavior
886</Note>
887 1546
888```python theme={null}1547```json theme={null}
889#!/usr/bin/env python31548{
890import json1549 "hooks": {
891import sys1550 "Stop": [
892import re1551 {
893import datetime1552 "hooks": [
894 1553 {
895# Load input from stdin1554 "type": "prompt",
896try: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.",
897 input_data = json.load(sys.stdin)1556 "timeout": 30
898except json.JSONDecodeError as e:1557 }
899 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)1558 ]
900 sys.exit(1)
901
902prompt = input_data.get("prompt", "")
903
904# Check for sensitive patterns
905sensitive_patterns = [
906 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
907]
908
909for pattern, message in sensitive_patterns:
910 if re.search(pattern, prompt):
911 # Use JSON output to block with a specific reason
912 output = {
913 "decision": "block",
914 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
915 }1559 }
916 print(json.dumps(output))1560 ]
917 sys.exit(0)1561 }
1562}
1563```
918 1564
919# Add current time to context1565## Agent-based hooks
920context = f"Current time: {datetime.datetime.now()}"
921print(context)
922 1566
923"""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.
924The following is also equivalent:
925print(json.dumps({
926 "hookSpecificOutput": {
927 "hookEventName": "UserPromptSubmit",
928 "additionalContext": context,
929 },
930}))
931"""
932 1568
933# Allow the prompt to proceed with the additional context1569### How agent hooks work
934sys.exit(0)
935```
936 1570
937#### JSON Output Example: PreToolUse with Approval1571When an agent hook fires:
938
939```python theme={null}
940#!/usr/bin/env python3
941import json
942import sys
943
944# Load input from stdin
945try:
946 input_data = json.load(sys.stdin)
947except json.JSONDecodeError as e:
948 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
949 sys.exit(1)
950
951tool_name = input_data.get("tool_name", "")
952tool_input = input_data.get("tool_input", {})
953
954# Example: Auto-approve file reads for documentation files
955if tool_name == "Read":
956 file_path = tool_input.get("file_path", "")
957 if file_path.endswith((".md", ".mdx", ".txt", ".json")):
958 # Use JSON output to auto-approve the tool call
959 output = {
960 "decision": "approve",
961 "reason": "Documentation file auto-approved",
962 "suppressOutput": True # Don't show in transcript mode
963 }
964 print(json.dumps(output))
965 sys.exit(0)
966
967# For other cases, let the normal permission flow proceed
968sys.exit(0)
969```
970 1572
971## 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
972 1577
973Claude 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.
974[Model Context Protocol (MCP) tools](/en/docs/claude-code/mcp). When MCP servers
975provide tools, they appear with a special naming pattern that you can match in
976your hooks.
977 1579
978### MCP Tool Naming1580### Agent hook configuration
979 1581
980MCP 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:
981 1583
982* `mcp__memory__create_entities` - Memory server's create entities tool1584| Field | Required | Description |
983* `mcp__filesystem__read_file` - Filesystem server's read file tool1585| :-------- | :------- | :------------------------------------------------------------------------------------------ |
984* `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 |
985 1590
986### Configuring Hooks for MCP Tools1591The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.
987 1592
988You can target specific MCP tools or entire MCP servers:1593This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
989 1594
990```json theme={null}1595```json theme={null}
991{1596{
992 "hooks": {1597 "hooks": {
993 "PreToolUse": [1598 "Stop": [
994 {1599 {
995 "matcher": "mcp__memory__.*",
996 "hooks": [1600 "hooks": [
997 {1601 {
998 "type": "command",1602 "type": "agent",
999 "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
1000 }1605 }
1001 ]1606 ]
1002 },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": [
1003 {1627 {
1004 "matcher": "mcp__.*__write.*",1628 "matcher": "Write",
1005 "hooks": [1629 "hooks": [
1006 {1630 {
1007 "type": "command",1631 "type": "command",
1008 "command": "/home/user/scripts/validate-mcp-write.py"1632 "command": "/path/to/run-tests.sh",
1633 "async": true,
1634 "timeout": 120
1009 }1635 }
1010 ]1636 ]
1011 }1637 }
1014}1640}
1015```1641```
1016 1642
1017## 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.
1018
1019<Tip>
1020 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/docs/claude-code/hooks-guide#more-examples) in the get started guide.
1021</Tip>
1022
1023## Security Considerations
1024 1644
1025### Disclaimer1645### How async hooks execute
1026 1646
1027**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.
1028your system automatically. By using hooks, you acknowledge that:
1029 1648
1030* 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.
1031* Hooks can modify, delete, or access any files your user account can access
1032* Malicious or poorly written hooks can cause data loss or system damage
1033* Anthropic provides no warranty and assumes no liability for any damages
1034 resulting from hook usage
1035* You should thoroughly test hooks in a safe environment before production use
1036 1650
1037Always review and understand any hook commands before adding them to your1651### Example: run tests after file changes
1038configuration.
1039 1652
1040### 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`:
1041 1654
1042Here are some key practices for writing more secure hooks:1655```bash theme={null}
1656#!/bin/bash
1657# run-tests-async.sh
1043 1658
10441. **Validate and sanitize inputs** - Never trust input data blindly1659# Read hook input from stdin
10452. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1660INPUT=$(cat)
10463. **Block path traversal** - Check for `..` in file paths1661FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
10474. **Use absolute paths** - Specify full paths for scripts (use
1048 "\$CLAUDE\_PROJECT\_DIR" for the project path)
10495. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.
1050 1662
1051### Configuration Safety1663# Only run tests for source files
1664if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
1665 exit 0
1666fi
1052 1667
1053Direct edits to hooks in settings files don't take effect immediately. Claude1668# Run tests and report results via systemMessage
1054Code:1669RESULT=$(npm test 2>&1)
1670EXIT_CODE=$?
1055 1671
10561. Captures a snapshot of hooks at startup1672if [ $EXIT_CODE -eq 0 ]; then
10572. Uses this snapshot throughout the session1673 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
10583. Warns if hooks are modified externally1674else
10594. Requires review in `/hooks` menu for changes to apply1675 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
1676fi
1677```
1060 1678
1061This 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:
1062 1680
1063## 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```
1064 1700
1065* **Timeout**: 60-second execution limit by default, configurable per command.1701### Limitations
1066 * A timeout for an individual command does not affect the other commands.
1067* **Parallelization**: All matching hooks run in parallel
1068* **Deduplication**: Multiple identical hook commands are deduplicated automatically
1069* **Environment**: Runs in current directory with Claude Code's environment
1070 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the
1071 absolute path to the project root directory (where Claude Code was started)
1072 * The `CLAUDE_CODE_REMOTE` environment variable indicates whether the hook is running in a remote (web) environment (`"true"`) or local CLI environment (not set or empty). Use this to run different logic based on execution context.
1073* **Input**: JSON via stdin
1074* **Output**:
1075 * PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in transcript (Ctrl-R)
1076 * Notification/SessionEnd: Logged to debug only (`--debug`)
1077 * UserPromptSubmit/SessionStart: stdout added as context for Claude
1078 1702
1079## Debugging1703Async hooks have several constraints compared to synchronous hooks:
1080 1704
1081### 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.
1082 1709
1083If your hooks aren't working:1710## Security considerations
1084 1711
10851. **Check configuration** - Run `/hooks` to see if your hook is registered1712### Disclaimer
10862. **Verify syntax** - Ensure your JSON settings are valid
10873. **Test commands** - Run hook commands manually first
10884. **Check permissions** - Make sure scripts are executable
10895. **Review logs** - Use `claude --debug` to see hook execution details
1090 1713
1091Common issues:1714Hooks run with your system user's full permissions.
1092 1715
1093* **Quotes not escaped** - Use `\"` inside JSON strings1716<Warning>
1094* **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.
1095* **Command not found** - Use full paths for scripts1718</Warning>
1096 1719
1097### Advanced Debugging1720### Security best practices
1098 1721
1099For complex hook issues:1722Keep these practices in mind when writing hooks:
1100 1723
11011. **Inspect hook execution** - Use `claude --debug` to see detailed hook1724* **Validate and sanitize inputs**: never trust input data blindly
1102 execution1725* **Always quote shell variables**: use `"$VAR"` not `$VAR`
11032. **Validate JSON schemas** - Test hook input/output with external tools1726* **Block path traversal**: check for `..` in file paths
11043. **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
11054. **Test edge cases** - Try hooks with unusual file paths or inputs1728* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.
11065. **Monitor system resources** - Check for resource exhaustion during hook
1107 execution
11086. **Use structured logging** - Implement logging in your hook scripts
1109 1729
1110### Debug Output Example1730## Debug hooks
1111 1731
1112Use `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.
1113 1733
1114```1734```
1115[DEBUG] Executing hooks for PostToolUse:Write1735[DEBUG] Executing hooks for PostToolUse:Write
1117[DEBUG] Found 1 hook matchers in settings1737[DEBUG] Found 1 hook matchers in settings
1118[DEBUG] Matched 1 hooks for query "Write"1738[DEBUG] Matched 1 hooks for query "Write"
1119[DEBUG] Found 1 hook commands to execute1739[DEBUG] Found 1 hook commands to execute
1120[DEBUG] Executing hook command: <Your command> with timeout 60000ms1740[DEBUG] Executing hook command: <Your command> with timeout 600000ms
1121[DEBUG] Hook command completed with status 0: <Your stdout>1741[DEBUG] Hook command completed with status 0: <Your stdout>
1122```1742```
1123 1743
1124Progress messages appear in transcript mode (Ctrl-R) 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.
1125
1126* Which hook is running
1127* Command being executed
1128* Success/failure status
1129* Output or error messages