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`)70
42 * Simple strings match exactly: `Write` matches only the Write tool71```bash theme={null}
43 * Supports regex: `Edit|Write` or `Notebook.*`72#!/bin/bash
44 * Use `*` to match all tools. You can also use empty string (`""`) or leave73# .claude/hooks/block-rm.sh
45 `matcher` blank.74COMMAND=$(jq -r '.tool_input.command')
46* **hooks**: Array of commands to execute when the pattern matches75
47 * `type`: Currently only `"command"` is supported76if echo "$COMMAND" | grep -q 'rm -rf'; then
48 * `command`: The bash command to execute (can use `$CLAUDE_PROJECT_DIR`77 jq -n '{
49 environment variable)78 hookSpecificOutput: {
50 * `timeout`: (Optional) How long a command should run, in seconds, before79 hookEventName: "PreToolUse",
51 canceling that specific command.80 permissionDecision: "deny",
81 permissionDecisionReason: "Destructive command blocked by hook"
82 }
83 }'
84else
85 exit 0 # allow the command
86fi
87```
88
89Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
90
91<Frame>
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" />
93</Frame>
94
95<Steps>
96 <Step title="Event fires">
97 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
98
99 ```json theme={null}
100 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
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}
112 {
113 "hookSpecificOutput": {
114 "hookEventName": "PreToolUse",
115 "permissionDecision": "deny",
116 "permissionDecisionReason": "Destructive command blocked by hook"
117 }
118 }
119 ```
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>
52 123
53For events like `UserPromptSubmit`, `Notification`, `Stop`, and `SubagentStop`124 <Step title="Claude Code acts on the result">
54that don't use matchers, you can omit the matcher field: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
138
139See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.
140
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:
163
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 |
175
176The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.
177
178This example runs a linting script only when Claude writes or edits a file:
55 179
56```json theme={null}180```json theme={null}
57{181{
58 "hooks": {182 "hooks": {
59 "UserPromptSubmit": [183 "PostToolUse": [
60 {184 {
185 "matcher": "Edit|Write",
61 "hooks": [186 "hooks": [
62 {187 {
63 "type": "command",188 "type": "command",
64 "command": "/path/to/prompt-validator.py"189 "command": "/path/to/lint-check.sh"
65 }190 }
66 ]191 ]
67 }192 }
70}195}
71```196```
72 197
73### Project-Specific Hook Scripts198`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.
199
200#### Match MCP tools
201
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.
203
204MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
205
206* `mcp__memory__create_entities`: Memory server's create entities tool
207* `mcp__filesystem__read_file`: Filesystem server's read file tool
208* `mcp__github__search_repositories`: GitHub server's search tool
209
210Use regex patterns to target specific MCP tools or groups of tools:
211
212* `mcp__memory__.*` matches all tools from the `memory` server
213* `mcp__.*__write.*` matches any tool containing "write" from any server
74 214
75You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when215This example logs all memory server operations and validates write operations from any MCP server:
76Claude Code spawns the hook command) to reference scripts stored in your project,
77ensuring they work regardless of Claude's current directory:
78 216
79```json theme={null}217```json theme={null}
80{218{
81 "hooks": {219 "hooks": {
82 "PostToolUse": [220 "PreToolUse": [
83 {221 {
84 "matcher": "Write|Edit",222 "matcher": "mcp__memory__.*",
85 "hooks": [223 "hooks": [
86 {224 {
87 "type": "command",225 "type": "command",
88 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"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"
89 }236 }
90 ]237 ]
91 }238 }
94}241}
95```242```
96 243
97### Plugin hooks244### Hook handler fields
98 245
99[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.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:
100 247
101**How plugin hooks work**:248* **[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).
102 251
103* 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.252#### Common fields
104* When a plugin is enabled, its hooks are merged with user and project hooks
105* Multiple hooks from different sources can respond to the same event
106* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files
107 253
108**Example plugin hook configuration**:254These fields apply to all hook types:
109 255
110```json theme={null}256| Field | Required | Description |
111{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) |
262
263#### Command hook fields
264
265In addition to the [common fields](#common-fields), command hooks accept these fields:
266
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) |
271
272#### Prompt and agent hook fields
273
274In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:
275
276| Field | Required | Description |
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 {
296 "hooks": {
297 "PostToolUse": [
298 {
299 "matcher": "Write|Edit",
300 "hooks": [
301 {
302 "type": "command",
303 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
304 }
305 ]
306 }
307 ]
308 }
309 }
310 ```
311 </Tab>
312
313 <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.
315
316 This example runs a formatting script bundled with the plugin:
317
318 ```json theme={null}
319 {
112 "description": "Automatic code formatting",320 "description": "Automatic code formatting",
113 "hooks": {321 "hooks": {
114 "PostToolUse": [322 "PostToolUse": [
124 }332 }
125 ]333 ]
126 }334 }
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---
363```
364
365Agents use the same format in their YAML frontmatter.
366
367### The `/hooks` menu
368
369Type `/hooks` in Claude Code to open the interactive hooks manager, where you can view, add, and delete hooks without editing settings files directly. For a step-by-step walkthrough, see [Set up your first hook](/en/hooks-guide#set-up-your-first-hook) in the guide.
370
371Each hook in the menu is labeled with a bracket prefix indicating its source:
372
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
377
378### Disable or remove hooks
379
380To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it.
381
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.
383
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.
385
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.
387
388## Hook input and output
389
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.
391
392### Common input fields
393
394All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section:
395
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 |
403
404For example, a `PreToolUse` hook for a Bash command receives this on stdin:
405
406```json theme={null}
407{
408 "session_id": "abc123",
409 "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 }
127}417}
128```418```
129 419
130<Note>420The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.
131 Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.421
132</Note>422### Exit code output
423
424The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.
425
426**Exit 0** means success. Claude Code parses stdout for [JSON output fields](#json-output). JSON output is only processed on exit 0. For most events, stdout is only shown in verbose mode (`Ctrl+O`). The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on.
427
428**Exit 2** means a blocking error. Claude Code ignores stdout and any JSON in it. Instead, stderr text is fed back to Claude as an error message. The effect depends on the event: `PreToolUse` blocks the tool call, `UserPromptSubmit` rejects the prompt, and so on. See [exit code 2 behavior](#exit-code-2-behavior-per-event) for the full list.
429
430**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.
431
432For example, a hook command script that blocks dangerous Bash commands:
433
434```bash theme={null}
435#!/bin/bash
436# Reads JSON input from stdin, checks the command
437command=$(jq -r '.tool_input.command' < /dev/stdin)
438
439if [[ "$command" == rm* ]]; then
440 echo "Blocked: rm commands are not allowed" >&2
441 exit 2 # Blocking error: tool call is prevented
442fi
443
444exit 0 # Success: tool call proceeds
445```
446
447#### Exit code 2 behavior per event
448
449Exit code 2 is the way a hook signals "stop, don't do this." The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn't happened yet) and others represent things that already happened or can't be prevented.
450
451| Hook event | Can block? | What happens on exit 2 |
452| :------------------- | :--------- | :---------------------------------------------------------------------------- |
453| `PreToolUse` | Yes | Blocks the tool call |
454| `PermissionRequest` | Yes | Denies the permission |
455| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
456| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
457| `SubagentStop` | Yes | Prevents the subagent from stopping |
458| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |
459| `TaskCompleted` | Yes | Prevents the task from being marked as completed |
460| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |
461| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
462| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
463| `Notification` | No | Shows stderr to user only |
464| `SubagentStart` | No | Shows stderr to user only |
465| `SessionStart` | No | Shows stderr to user only |
466| `SessionEnd` | No | Shows stderr to user only |
467| `PreCompact` | No | Shows stderr to user only |
468| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |
469| `WorktreeRemove` | No | Failures are logged in debug mode only |
470
471### JSON output
472
473Exit codes let you allow or block, but JSON output gives you finer-grained control. Instead of exiting with code 2 to block, exit 0 and print a JSON object to stdout. Claude Code reads specific fields from that JSON to control behavior, including [decision control](#decision-control) for blocking, allowing, or escalating to the user.
133 474
134<Note>475<Note>
135 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.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.
136</Note>477</Note>
137 478
138**Environment variables for plugins**: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.
139 480
140* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory481The JSON object supports three kinds of fields:
141* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)
142* All standard environment variables are available
143 482
144See the [plugin components reference](/en/docs/claude-code/plugins-reference#hooks) for details on creating plugin hooks.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.
145 486
146## Hook Events487| 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 |
147 493
148### PreToolUse494To stop Claude entirely regardless of event type:
149 495
150Runs after Claude creates tool parameters and before processing the tool call.496```json theme={null}
497{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
498```
151 499
152**Common matchers:**500#### Decision control
153 501
154* `Task` - Subagent tasks (see [subagents documentation](/en/docs/claude-code/sub-agents))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:
155* `Bash` - Shell commands
156* `Glob` - File pattern matching
157* `Grep` - Content search
158* `Read` - File reading
159* `Edit` - File editing
160* `Write` - File writing
161* `WebFetch`, `WebSearch` - Web operations
162 503
163### PostToolUse504| 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 |
164 512
165Runs immediately after a tool completes successfully.513Here are examples of each pattern in action:
166 514
167Recognizes the same matcher values as PreToolUse.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:
168 518
169### Notification519 ```json theme={null}
520 {
521 "decision": "block",
522 "reason": "Test suite must pass before proceeding"
523 }
524 ```
525 </Tab>
170 526
171Runs when Claude Code sends notifications. Notifications are sent when: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.
172 529
1731. Claude needs your permission to use a tool. Example: "Claude needs your530 ```json theme={null}
174 permission to use Bash"531 {
1752. The prompt input has been idle for at least 60 seconds. "Claude is waiting532 "hookSpecificOutput": {
176 for your input"533 "hookEventName": "PreToolUse",
534 "permissionDecision": "deny",
535 "permissionDecisionReason": "Database writes are not allowed"
536 }
537 }
538 ```
539 </Tab>
177 540
178### UserPromptSubmit541 <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.
179 543
180Runs when the user submits a prompt, before Claude processes it. This allows you544 ```json theme={null}
181to add additional context based on the prompt/conversation, validate prompts, or545 {
182block certain types of prompts.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>
183 559
184### Stop560For 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).
185 561
186Runs when the main Claude Code agent has finished responding. Does not run if562## Hook events
187the stoppage occurred due to a user interrupt.
188 563
189### SubagentStop564Each 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.
190 565
191Runs when a Claude Code subagent (Task tool call) has finished responding.566### SessionStart
192 567
193### PreCompact568Runs 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.
194 569
195Runs before Claude Code is about to run a compact operation.570SessionStart runs on every session, so keep these hooks fast.
196 571
197**Matchers:**572The matcher value corresponds to how the session was initiated:
198 573
199* `manual` - Invoked from `/compact`574| Matcher | When it fires |
200* `auto` - Invoked from auto-compact (due to full context window)575| :-------- | :------------------------------------- |
576| `startup` | New session |
577| `resume` | `--resume`, `--continue`, or `/resume` |
578| `clear` | `/clear` |
579| `compact` | Auto or manual compaction |
201 580
202### SessionStart581#### SessionStart input
582
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.
584
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```
203 596
204Runs when Claude Code starts a new session or resumes an existing session (which597#### SessionStart decision control
205currently does start a new session under the hood). Useful for loading in
206development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables.
207 598
208**Matchers:**599Any text your hook script prints to stdout is added as context for Claude. In addition to the [JSON output fields](#json-output) available to all hooks, you can return these event-specific fields:
209 600
210* `startup` - Invoked from startup601| Field | Description |
211* `resume` - Invoked from `--resume`, `--continue`, or `/resume`602| :------------------ | :------------------------------------------------------------------------ |
212* `clear` - Invoked from `/clear`603| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |
213* `compact` - Invoked from auto or manual compact.
214 604
215#### Persisting environment variables605```json theme={null}
606{
607 "hookSpecificOutput": {
608 "hookEventName": "SessionStart",
609 "additionalContext": "My additional context here"
610 }
611}
612```
216 613
217SessionStart 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.614#### Persist environment variables
218 615
219**Example: Setting individual environment variables**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:
220 619
221```bash theme={null}620```bash theme={null}
222#!/bin/bash621#!/bin/bash
223 622
224if [ -n "$CLAUDE_ENV_FILE" ]; then623if [ -n "$CLAUDE_ENV_FILE" ]; then
225 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"624 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
226 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"625 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
227 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"626 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
228fi627fi
229 628
230exit 0629exit 0
231```630```
232 631
233**Example: Persisting all environment changes from the hook**632To capture all environment changes from setup commands, compare the exported variables before and after:
234
235When your setup modifies the environment (e.g., `nvm use`), capture and persist all changes by diffing the environment:
236 633
237```bash theme={null}634```bash theme={null}
238#!/bin/bash635#!/bin/bash
251exit 0648exit 0
252```649```
253 650
254Any 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.
255 652
256<Note>653<Note>
257 `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.
258</Note>655</Note>
259 656
260### SessionEnd657### UserPromptSubmit
261 658
262Runs when a Claude Code session ends. Useful for cleanup tasks, logging session659Runs when the user submits a prompt, before Claude processes it. This allows you
263statistics, or saving session state.660to add additional context based on the prompt/conversation, validate prompts, or
661block certain types of prompts.
264 662
265The `reason` field in the hook input will be one of:663#### UserPromptSubmit input
266 664
267* `clear` - Session cleared with /clear command665In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
268* `logout` - User logged out
269* `prompt_input_exit` - User exited while prompt input was visible
270* `other` - Other exit reasons
271 666
272## Hook Input667```json theme={null}
668{
669 "session_id": "abc123",
670 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
671 "cwd": "/Users/...",
672 "permission_mode": "default",
673 "hook_event_name": "UserPromptSubmit",
674 "prompt": "Write a function to calculate the factorial of a number"
675}
676```
677
678#### UserPromptSubmit decision control
273 679
274Hooks receive JSON data via stdin containing session information and680`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.
275event-specific data:
276 681
277```typescript theme={null}682There are two ways to add context to the conversation on exit code 0:
683
684* **Plain text stdout**: any non-JSON text written to stdout is added as context
685* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
686
687Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.
688
689To block a prompt, return a JSON object with `decision` set to `"block"`:
690
691| Field | Description |
692| :------------------ | :----------------------------------------------------------------------------------------------------------------- |
693| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |
694| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |
695| `additionalContext` | String added to Claude's context |
696
697```json theme={null}
278{698{
279 // Common fields699 "decision": "block",
280 session_id: string700 "reason": "Explanation for decision",
281 transcript_path: string // Path to conversation JSON701 "hookSpecificOutput": {
282 cwd: string // The current working directory when the hook is invoked702 "hookEventName": "UserPromptSubmit",
283 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions"703 "additionalContext": "My additional context here"
704 }
705}
706```
707
708<Note>
709 The JSON format isn't required for simple use cases. To add context, you can print plain text to stdout with exit code 0. Use JSON when you need to
710 block prompts or want more structured control.
711</Note>
712
713### PreToolUse
714
715Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Task`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).
716
717Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.
718
719#### PreToolUse input
720
721In addition to the [common input fields](#common-input-fields), PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool:
722
723##### Bash
724
725Executes shell commands.
726
727| Field | Type | Example | Description |
728| :------------------ | :------ | :----------------- | :-------------------------------------------- |
729| `command` | string | `"npm test"` | The shell command to execute |
730| `description` | string | `"Run test suite"` | Optional description of what the command does |
731| `timeout` | number | `120000` | Optional timeout in milliseconds |
732| `run_in_background` | boolean | `false` | Whether to run the command in background |
733
734##### Write
735
736Creates or overwrites a file.
737
738| Field | Type | Example | Description |
739| :---------- | :----- | :-------------------- | :--------------------------------- |
740| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |
741| `content` | string | `"file content"` | Content to write to the file |
742
743##### Edit
744
745Replaces a string in an existing file.
284 746
285 // Event-specific fields747| Field | Type | Example | Description |
286 hook_event_name: string748| :------------ | :------ | :-------------------- | :--------------------------------- |
287 ...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 }
288}838}
289```839```
290 840
291### PreToolUse Input841<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
292 853
293The exact schema for `tool_input` depends on the tool.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.
294 855
295```json theme={null}856```json theme={null}
296{857{
298 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",859 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
299 "cwd": "/Users/...",860 "cwd": "/Users/...",
300 "permission_mode": "default",861 "permission_mode": "default",
301 "hook_event_name": "PreToolUse",862 "hook_event_name": "PermissionRequest",
302 "tool_name": "Write",863 "tool_name": "Bash",
303 "tool_input": {864 "tool_input": {
304 "file_path": "/path/to/file.txt",865 "command": "rm -rf node_modules",
305 "content": "file content"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 }
306 }896 }
307}897}
308```898```
309 899
310### PostToolUse Input900### PostToolUse
311 901
312The exact schema for `tool_input` and `tool_response` depends on the tool.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.
313 909
314```json theme={null}910```json theme={null}
315{911{
326 "tool_response": {922 "tool_response": {
327 "filePath": "/path/to/file.txt",923 "filePath": "/path/to/file.txt",
328 "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"
329 }948 }
330}949}
331```950```
332 951
333### Notification 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.
957
958#### PostToolUseFailure input
959
960PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:
961
962```json theme={null}
963{
964 "session_id": "abc123",
965 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
966 "cwd": "/Users/...",
967 "permission_mode": "default",
968 "hook_event_name": "PostToolUseFailure",
969 "tool_name": "Bash",
970 "tool_input": {
971 "command": "npm test",
972 "description": "Run test suite"
973 },
974 "tool_use_id": "toolu_01ABC123...",
975 "error": "Command exited with non-zero status code 1",
976 "is_interrupt": false
977}
978```
979
980| Field | Description |
981| :------------- | :------------------------------------------------------------------------------ |
982| `error` | String describing what went wrong |
983| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |
984
985#### PostToolUseFailure decision control
986
987`PostToolUseFailure` hooks can provide context to Claude after a tool failure. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:
988
989| Field | Description |
990| :------------------ | :------------------------------------------------------------ |
991| `additionalContext` | Additional context for Claude to consider alongside the error |
992
993```json theme={null}
994{
995 "hookSpecificOutput": {
996 "hookEventName": "PostToolUseFailure",
997 "additionalContext": "Additional information about the failure for Claude"
998 }
999}
1000```
1001
1002### Notification
1003
1004Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`. Omit the matcher to run hooks for all notification types.
1005
1006Use separate matchers to run different handlers depending on the notification type. This configuration triggers a permission-specific alert script when Claude needs permission approval and a different notification when Claude has been idle:
1007
1008```json theme={null}
1009{
1010 "hooks": {
1011 "Notification": [
1012 {
1013 "matcher": "permission_prompt",
1014 "hooks": [
1015 {
1016 "type": "command",
1017 "command": "/path/to/permission-alert.sh"
1018 }
1019 ]
1020 },
1021 {
1022 "matcher": "idle_prompt",
1023 "hooks": [
1024 {
1025 "type": "command",
1026 "command": "/path/to/idle-notification.sh"
1027 }
1028 ]
1029 }
1030 ]
1031 }
1032}
1033```
1034
1035#### Notification input
1036
1037In addition to the [common input fields](#common-input-fields), Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired.
334 1038
335```json theme={null}1039```json theme={null}
336{1040{
339 "cwd": "/Users/...",1043 "cwd": "/Users/...",
340 "permission_mode": "default",1044 "permission_mode": "default",
341 "hook_event_name": "Notification",1045 "hook_event_name": "Notification",
342 "message": "Task completed successfully"1046 "message": "Claude needs your permission to use Bash",
1047 "title": "Permission needed",
1048 "notification_type": "permission_prompt"
1049}
1050```
1051
1052Notification 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).
1065
1066```json theme={null}
1067{
1068 "session_id": "abc123",
1069 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1070 "cwd": "/Users/...",
1071 "permission_mode": "default",
1072 "hook_event_name": "SubagentStart",
1073 "agent_id": "agent-abc123",
1074 "agent_type": "Explore"
1075}
1076```
1077
1078SubagentStart 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:
1079
1080| Field | Description |
1081| :------------------ | :------------------------------------- |
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 }
343}1090}
344```1091```
345 1092
346### UserPromptSubmit Input1093### 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.
347 1100
348```json theme={null}1101```json theme={null}
349{1102{
350 "session_id": "abc123",1103 "session_id": "abc123",
351 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1104 "transcript_path": "~/.claude/projects/.../abc123.jsonl",
352 "cwd": "/Users/...",1105 "cwd": "/Users/...",
353 "permission_mode": "default",1106 "permission_mode": "default",
354 "hook_event_name": "UserPromptSubmit",1107 "hook_event_name": "SubagentStop",
355 "prompt": "Write a function to calculate the factorial of a number"1108 "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..."
356}1113}
357```1114```
358 1115
359### Stop and SubagentStop Input1116SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).
1117
1118### Stop
1119
1120Runs when the main Claude Code agent has finished responding. Does not run if
1121the stoppage occurred due to a user interrupt.
1122
1123#### Stop input
360 1124
361`stop_hook_active` is true when Claude Code is already continuing as a result of1125In 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.
362a stop hook. Check this value or process the transcript to prevent Claude Code
363from running indefinitely.
364 1126
365```json theme={null}1127```json theme={null}
366{1128{
367 "session_id": "abc123",1129 "session_id": "abc123",
368 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1130 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1131 "cwd": "/Users/...",
369 "permission_mode": "default",1132 "permission_mode": "default",
370 "hook_event_name": "Stop",1133 "hook_event_name": "Stop",
371 "stop_hook_active": true1134 "stop_hook_active": true,
1135 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
372}1136}
373```1137```
374 1138
375### PreCompact Input1139#### Stop decision control
376 1140
377For `manual`, `custom_instructions` comes from what the user passes into1141`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:
378`/compact`. For `auto`, `custom_instructions` is empty.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 |
379 1147
380```json theme={null}1148```json theme={null}
381{1149{
382 "session_id": "abc123",1150 "decision": "block",
383 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1151 "reason": "Must be provided when Claude is blocked from stopping"
384 "permission_mode": "default",
385 "hook_event_name": "PreCompact",
386 "trigger": "manual",
387 "custom_instructions": ""
388}1152}
389```1153```
390 1154
391### SessionStart Input1155### TeammateIdle
1156
1157Runs when an [agent team](/en/agent-teams) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist.
1158
1159When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. TeammateIdle hooks do not support matchers and fire on every occurrence.
1160
1161#### TeammateIdle input
1162
1163In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
392 1164
393```json theme={null}1165```json theme={null}
394{1166{
395 "session_id": "abc123",1167 "session_id": "abc123",
396 "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/...",
397 "permission_mode": "default",1170 "permission_mode": "default",
398 "hook_event_name": "SessionStart",1171 "hook_event_name": "TeammateIdle",
399 "source": "startup"1172 "teammate_name": "researcher",
1173 "team_name": "my-project"
400}1174}
401```1175```
402 1176
403### 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`.
404 1206
405```json theme={null}1207```json theme={null}
406{1208{
407 "session_id": "abc123",1209 "session_id": "abc123",
408 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1210 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
409 "cwd": "/Users/...",1211 "cwd": "/Users/...",
410 "permission_mode": "default",1212 "permission_mode": "default",
411 "hook_event_name": "SessionEnd",1213 "hook_event_name": "TaskCompleted",
412 "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"
413}1219}
414```1220```
415 1221
416## 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 |
417 1229
418There are two ways for hooks to return output back to Claude Code. The output1230#### TaskCompleted decision control
419communicates whether to block and any feedback that should be shown to Claude
420and the user.
421 1231
422### Simple: Exit Code1232TaskCompleted hooks use exit codes only, not JSON decision control. This example runs tests and blocks task completion if they fail:
423 1233
424Hooks 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')
425 1238
426* **Exit code 0**: Success. `stdout` is shown to the user in transcript mode1239# Run the test suite
427 (CTRL-R), except for `UserPromptSubmit` and `SessionStart`, where stdout is1240if ! npm test 2>&1; then
428 added to the context.1241 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
429* **Exit code 2**: Blocking error. `stderr` is fed back to Claude to process1242 exit 2
430 automatically. See per-hook-event behavior below.1243fi
431* **Other exit codes**: Non-blocking error. `stderr` is shown to the user and
432 execution continues.
433 1244
434<Warning>1245exit 0
435 Reminder: Claude Code does not see stdout if the exit code is 0, except for1246```
436 the `UserPromptSubmit` hook where stdout is injected as context.
437</Warning>
438 1247
439#### Exit Code 2 Behavior1248### ConfigChange
440 1249
441| 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.
442| ------------------ | ------------------------------------------------------------------ |
443| `PreToolUse` | Blocks the tool call, shows stderr to Claude |
444| `PostToolUse` | Shows stderr to Claude (tool already ran) |
445| `Notification` | N/A, shows stderr to user only |
446| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |
447| `Stop` | Blocks stoppage, shows stderr to Claude |
448| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |
449| `PreCompact` | N/A, shows stderr to user only |
450| `SessionStart` | N/A, shows stderr to user only |
451| `SessionEnd` | N/A, shows stderr to user only |
452 1251
453### 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.
454 1253
455Hooks can return structured JSON in `stdout` for more sophisticated control:1254The matcher filters on the configuration source:
456 1255
457#### 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 |
458 1263
459All hook types can include these optional fields:1264This example logs all configuration changes for security auditing:
460 1265
461```json theme={null}1266```json theme={null}
462{1267{
463 "continue": true, // Whether Claude should continue after hook execution (default: true)1268 "hooks": {
464 "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```
465 1282
466 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1283#### ConfigChange input
467 "systemMessage": "string" // Optional warning message shown to the user1284
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.
1286
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"
468}1296}
469```1297```
470 1298
471If `continue` is false, Claude stops processing after the hooks run.1299#### ConfigChange decision control
472 1300
473* 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.
474 only blocks a specific tool call and provides automatic feedback to Claude.
475* For `PostToolUse`, this is different from `"decision": "block"`, which
476 provides automated feedback to Claude.
477* For `UserPromptSubmit`, this prevents the prompt from being processed.
478* For `Stop` and `SubagentStop`, this takes precedence over any
479 `"decision": "block"` output.
480* In all cases, `"continue" = false` takes precedence over any
481 `"decision": "block"` output.
482 1302
483`stopReason` accompanies `continue` with a reason shown to the user, not shown1303| Field | Description |
484to 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"` |
485 1307
486#### `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.
487 1316
488`PreToolUse` hooks can control whether a tool call proceeds.1317### WorktreeCreate
489 1318
490* `"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.
491 to the user but not to Claude.
492* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is
493 shown to Claude.
494* `"ask"` asks the user to confirm the tool call in the UI.
495 `permissionDecisionReason` is shown to the user but not to Claude.
496 1320
497Additionally, 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.
498 1322
499* `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:
500* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.
501 1324
502```json theme={null}1325```json theme={null}
503{1326{
504 "hookSpecificOutput": {1327 "hooks": {
505 "hookEventName": "PreToolUse",1328 "WorktreeCreate": [
506 "permissionDecision": "allow"1329 {
507 "permissionDecisionReason": "My reason here",1330 "hooks": [
508 "updatedInput": {1331 {
509 "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\"'"
510 }1334 }
1335 ]
1336 }
1337 ]
511 }1338 }
512}1339}
513```1340```
514 1341
515<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.
516 The `decision` and `reason` fields are deprecated for PreToolUse hooks.
517 Use `hookSpecificOutput.permissionDecision` and
518 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields
519 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.
520</Note>
521
522#### `PostToolUse` Decision Control
523 1343
524`PostToolUse` hooks can provide feedback to Claude after tool execution.1344#### WorktreeCreate input
525 1345
526* `"block"` automatically prompts Claude with `reason`.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`).
527* `undefined` does nothing. `reason` is ignored.
528* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.
529 1347
530```json theme={null}1348```json theme={null}
531{1349{
532 "decision": "block" | undefined,1350 "session_id": "abc123",
533 "reason": "Explanation for decision",1351 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
534 "hookSpecificOutput": {1352 "cwd": "/Users/...",
535 "hookEventName": "PostToolUse",1353 "hook_event_name": "WorktreeCreate",
536 "additionalContext": "Additional information for Claude"1354 "name": "feature-auth"
537 }
538}1355}
539```1356```
540 1357
541#### `UserPromptSubmit` Decision 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.
1361
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.
542 1363
543`UserPromptSubmit` hooks can control whether a user prompt is processed.1364### WorktreeRemove
544 1365
545* `"block"` prevents the prompt from being processed. The submitted prompt is1366The 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.
546 erased from context. `"reason"` is shown to the user but not added to context.1367
547* `undefined` allows the prompt to proceed normally. `"reason"` is ignored.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:
548* `"hookSpecificOutput.additionalContext"` adds the string to the context if not
549 blocked.
550 1369
551```json theme={null}1370```json theme={null}
552{1371{
553 "decision": "block" | undefined,1372 "hooks": {
554 "reason": "Explanation for decision",1373 "WorktreeRemove": [
555 "hookSpecificOutput": {1374 {
556 "hookEventName": "UserPromptSubmit",1375 "hooks": [
557 "additionalContext": "My additional context here"1376 {
1377 "type": "command",
1378 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
1379 }
1380 ]
1381 }
1382 ]
558 }1383 }
559}1384}
560```1385```
561 1386
562#### `Stop`/`SubagentStop` Decision Control1387#### WorktreeRemove input
563 1388
564`Stop` and `SubagentStop` hooks can control whether Claude must continue.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.
565
566* `"block"` prevents Claude from stopping. You must populate `reason` for Claude
567 to know how to proceed.
568* `undefined` allows Claude to stop. `reason` is ignored.
569 1390
570```json theme={null}1391```json theme={null}
571{1392{
572 "decision": "block" | undefined,1393 "session_id": "abc123",
573 "reason": "Must be provided when Claude is blocked from stopping"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"
574}1398}
575```1399```
576 1400
577#### `SessionStart` Decision Control1401WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only. Only `type: "command"` hooks are supported.
1402
1403### PreCompact
1404
1405Runs before Claude Code is about to run a compact operation.
1406
1407The matcher value indicates whether compaction was triggered manually or automatically:
578 1408
579`SessionStart` hooks allow you to load in context at the start of a session.1409| Matcher | When it fires |
1410| :------- | :------------------------------------------- |
1411| `manual` | `/compact` |
1412| `auto` | Auto-compact when the context window is full |
580 1413
581* `"hookSpecificOutput.additionalContext"` adds the string to the context.1414#### PreCompact input
582* Multiple hooks' `additionalContext` values are concatenated.1415
1416In 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.
583 1417
584```json theme={null}1418```json theme={null}
585{1419{
586 "hookSpecificOutput": {1420 "session_id": "abc123",
587 "hookEventName": "SessionStart",1421 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
588 "additionalContext": "My additional context here"1422 "cwd": "/Users/...",
589 }1423 "permission_mode": "default",
1424 "hook_event_name": "PreCompact",
1425 "trigger": "manual",
1426 "custom_instructions": ""
590}1427}
591```1428```
592 1429
593#### `SessionEnd` Decision Control1430### SessionEnd
594 1431
595`SessionEnd` hooks run when a session ends. They cannot block session termination1432Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
596but can perform cleanup tasks.1433statistics, or saving session state. Supports matchers to filter by exit reason.
597 1434
598#### Exit Code Example: Bash Command Validation1435The `reason` field in the hook input indicates why the session ended:
599 1436
600```python theme={null}1437| Reason | Description |
601#!/usr/bin/env python31438| :---------------------------- | :----------------------------------------- |
602import json1439| `clear` | Session cleared with `/clear` command |
603import re1440| `logout` | User logged out |
604import sys1441| `prompt_input_exit` | User exited while prompt input was visible |
1442| `bypass_permissions_disabled` | Bypass permissions mode was disabled |
1443| `other` | Other exit reasons |
605 1444
606# Define validation rules as a list of (regex pattern, message) tuples1445#### SessionEnd input
607VALIDATION_RULES = [
608 (
609 r"\bgrep\b(?!.*\|)",
610 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
611 ),
612 (
613 r"\bfind\s+\S+\s+-name\b",
614 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
615 ),
616]
617 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.
618 1448
619def validate_command(command: str) -> list[str]:1449```json theme={null}
620 issues = []1450{
621 for pattern, message in VALIDATION_RULES:1451 "session_id": "abc123",
622 if re.search(pattern, command):1452 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
623 issues.append(message)1453 "cwd": "/Users/...",
624 return issues1454 "permission_mode": "default",
1455 "hook_event_name": "SessionEnd",
1456 "reason": "other"
1457}
1458```
625 1459
1460SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
626 1461
627try:1462## Prompt-based hooks
628 input_data = json.load(sys.stdin)
629except json.JSONDecodeError as e:
630 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
631 sys.exit(1)
632 1463
633tool_name = input_data.get("tool_name", "")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.
634tool_input = input_data.get("tool_input", {})
635command = tool_input.get("command", "")
636 1465
637if tool_name != "Bash" or not command:1466Events that support all three hook types (`command`, `prompt`, and `agent`):
638 sys.exit(1)
639 1467
640# Validate the command1468* `PermissionRequest`
641issues = validate_command(command)1469* `PostToolUse`
1470* `PostToolUseFailure`
1471* `PreToolUse`
1472* `Stop`
1473* `SubagentStop`
1474* `TaskCompleted`
1475* `UserPromptSubmit`
642 1476
643if issues:1477Events that only support `type: "command"` hooks:
644 for message in issues:
645 print(f"• {message}", file=sys.stderr)
646 # Exit code 2 blocks tool call and shows stderr to Claude
647 sys.exit(2)
648```
649 1478
650#### JSON Output Example: UserPromptSubmit to Add Context and Validation1479* `ConfigChange`
1480* `Notification`
1481* `PreCompact`
1482* `SessionEnd`
1483* `SessionStart`
1484* `SubagentStart`
1485* `TeammateIdle`
1486* `WorktreeCreate`
1487* `WorktreeRemove`
651 1488
652<Note>1489### How prompt-based hooks work
653 For `UserPromptSubmit` hooks, you can inject context using either method:
654 1490
655 * Exit code 0 with stdout: Claude sees the context (special case for `UserPromptSubmit`)1491Instead of executing a Bash command, prompt-based hooks:
656 * JSON output: Provides more control over the behavior
657</Note>
658 1492
659```python theme={null}14931. Send the hook input and your prompt to a Claude model, Haiku by default
660#!/usr/bin/env python314942. The LLM responds with structured JSON containing a decision
661import json14953. Claude Code processes the decision automatically
662import sys
663import re
664import datetime
665
666# Load input from stdin
667try:
668 input_data = json.load(sys.stdin)
669except json.JSONDecodeError as e:
670 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
671 sys.exit(1)
672
673prompt = input_data.get("prompt", "")
674
675# Check for sensitive patterns
676sensitive_patterns = [
677 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
678]
679
680for pattern, message in sensitive_patterns:
681 if re.search(pattern, prompt):
682 # Use JSON output to block with a specific reason
683 output = {
684 "decision": "block",
685 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
686 }
687 print(json.dumps(output))
688 sys.exit(0)
689 1496
690# Add current time to context1497### Prompt hook configuration
691context = f"Current time: {datetime.datetime.now()}"
692print(context)
693 1498
694"""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.
695The following is also equivalent:1500
696print(json.dumps({1501This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
697 "hookSpecificOutput": {
698 "hookEventName": "UserPromptSubmit",
699 "additionalContext": context,
700 },
701}))
702"""
703 1502
704# Allow the prompt to proceed with the additional context1503```json theme={null}
705sys.exit(0)1504{
1505 "hooks": {
1506 "Stop": [
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 ]
1516 }
1517}
706```1518```
707 1519
708#### JSON Output Example: PreToolUse with Approval1520| Field | Required | Description |
1521| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1522| `type` | yes | Must be `"prompt"` |
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 |
1524| `model` | no | Model to use for evaluation. Defaults to a fast model |
1525| `timeout` | no | Timeout in seconds. Default: 30 |
709 1526
710```python theme={null}1527### Response schema
711#!/usr/bin/env python31528
712import json1529The LLM must respond with JSON containing:
713import sys1530
1531```json theme={null}
1532{
1533 "ok": true | false,
1534 "reason": "Explanation for the decision"
1535}
1536```
714 1537
715# Load input from stdin1538| Field | Description |
716try:1539| :------- | :--------------------------------------------------------- |
717 input_data = json.load(sys.stdin)1540| `ok` | `true` allows the action, `false` prevents it |
718except json.JSONDecodeError as e:1541| `reason` | Required when `ok` is `false`. Explanation shown to Claude |
719 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
720 sys.exit(1)
721 1542
722tool_name = input_data.get("tool_name", "")1543### Example: Multi-criteria Stop hook
723tool_input = input_data.get("tool_input", {})
724 1544
725# Example: Auto-approve file reads for documentation files1545This `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:
726if tool_name == "Read":
727 file_path = tool_input.get("file_path", "")
728 if file_path.endswith((".md", ".mdx", ".txt", ".json")):
729 # Use JSON output to auto-approve the tool call
730 output = {
731 "decision": "approve",
732 "reason": "Documentation file auto-approved",
733 "suppressOutput": True # Don't show in transcript mode
734 }
735 print(json.dumps(output))
736 sys.exit(0)
737 1546
738# For other cases, let the normal permission flow proceed1547```json theme={null}
739sys.exit(0)1548{
1549 "hooks": {
1550 "Stop": [
1551 {
1552 "hooks": [
1553 {
1554 "type": "prompt",
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.",
1556 "timeout": 30
1557 }
1558 ]
1559 }
1560 ]
1561 }
1562}
740```1563```
741 1564
742## Working with MCP Tools1565## Agent-based hooks
743 1566
744Claude Code hooks work seamlessly with1567Agent-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.
745[Model Context Protocol (MCP) tools](/en/docs/claude-code/mcp). When MCP servers
746provide tools, they appear with a special naming pattern that you can match in
747your hooks.
748 1568
749### MCP Tool Naming1569### How agent hooks work
750 1570
751MCP tools follow the pattern `mcp__<server>__<tool>`, for example:1571When an agent hook fires:
752 1572
753* `mcp__memory__create_entities` - Memory server's create entities tool15731. Claude Code spawns a subagent with your prompt and the hook's JSON input
754* `mcp__filesystem__read_file` - Filesystem server's read file tool15742. The subagent can use tools like Read, Grep, and Glob to investigate
755* `mcp__github__search_repositories` - GitHub server's search tool15753. 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
756 1577
757### Configuring Hooks for MCP Tools1578Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.
758 1579
759You can target specific MCP tools or entire MCP servers:1580### Agent hook configuration
1581
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:
1583
1584| Field | Required | Description |
1585| :-------- | :------- | :------------------------------------------------------------------------------------------ |
1586| `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 |
1590
1591The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.
1592
1593This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
760 1594
761```json theme={null}1595```json theme={null}
762{1596{
763 "hooks": {1597 "hooks": {
764 "PreToolUse": [1598 "Stop": [
765 {1599 {
766 "matcher": "mcp__memory__.*",
767 "hooks": [1600 "hooks": [
768 {1601 {
769 "type": "command",1602 "type": "agent",
770 "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
771 }1605 }
772 ]1606 ]
773 },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": [
774 {1627 {
775 "matcher": "mcp__.*__write.*",1628 "matcher": "Write",
776 "hooks": [1629 "hooks": [
777 {1630 {
778 "type": "command",1631 "type": "command",
779 "command": "/home/user/scripts/validate-mcp-write.py"1632 "command": "/path/to/run-tests.sh",
1633 "async": true,
1634 "timeout": 120
780 }1635 }
781 ]1636 ]
782 }1637 }
785}1640}
786```1641```
787 1642
788## 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.
789
790<Tip>
791 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.
792</Tip>
793
794## Security Considerations
795 1644
796### Disclaimer1645### How async hooks execute
797 1646
798**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.
799your system automatically. By using hooks, you acknowledge that:
800 1648
801* 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.
802* Hooks can modify, delete, or access any files your user account can access
803* Malicious or poorly written hooks can cause data loss or system damage
804* Anthropic provides no warranty and assumes no liability for any damages
805 resulting from hook usage
806* You should thoroughly test hooks in a safe environment before production use
807 1650
808Always review and understand any hook commands before adding them to your1651### Example: run tests after file changes
809configuration.
810 1652
811### 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`:
812 1654
813Here are some key practices for writing more secure hooks:1655```bash theme={null}
1656#!/bin/bash
1657# run-tests-async.sh
814 1658
8151. **Validate and sanitize inputs** - Never trust input data blindly1659# Read hook input from stdin
8162. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1660INPUT=$(cat)
8173. **Block path traversal** - Check for `..` in file paths1661FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
8184. **Use absolute paths** - Specify full paths for scripts (use
819 "\$CLAUDE\_PROJECT\_DIR" for the project path)
8205. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.
821 1662
822### Configuration Safety1663# Only run tests for source files
1664if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
1665 exit 0
1666fi
823 1667
824Direct edits to hooks in settings files don't take effect immediately. Claude1668# Run tests and report results via systemMessage
825Code:1669RESULT=$(npm test 2>&1)
1670EXIT_CODE=$?
826 1671
8271. Captures a snapshot of hooks at startup1672if [ $EXIT_CODE -eq 0 ]; then
8282. Uses this snapshot throughout the session1673 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
8293. Warns if hooks are modified externally1674else
8304. Requires review in `/hooks` menu for changes to apply1675 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
1676fi
1677```
831 1678
832This 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:
833 1680
834## 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```
835 1700
836* **Timeout**: 60-second execution limit by default, configurable per command.1701### Limitations
837 * A timeout for an individual command does not affect the other commands.
838* **Parallelization**: All matching hooks run in parallel
839* **Deduplication**: Multiple identical hook commands are deduplicated automatically
840* **Environment**: Runs in current directory with Claude Code's environment
841 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the
842 absolute path to the project root directory (where Claude Code was started)
843 * 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.
844* **Input**: JSON via stdin
845* **Output**:
846 * PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in transcript (Ctrl-R)
847 * Notification/SessionEnd: Logged to debug only (`--debug`)
848 * UserPromptSubmit/SessionStart: stdout added as context for Claude
849 1702
850## Debugging1703Async hooks have several constraints compared to synchronous hooks:
851 1704
852### 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.
853 1709
854If your hooks aren't working:1710## Security considerations
855 1711
8561. **Check configuration** - Run `/hooks` to see if your hook is registered1712### Disclaimer
8572. **Verify syntax** - Ensure your JSON settings are valid
8583. **Test commands** - Run hook commands manually first
8594. **Check permissions** - Make sure scripts are executable
8605. **Review logs** - Use `claude --debug` to see hook execution details
861 1713
862Common issues:1714Hooks run with your system user's full permissions.
863 1715
864* **Quotes not escaped** - Use `\"` inside JSON strings1716<Warning>
865* **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.
866* **Command not found** - Use full paths for scripts1718</Warning>
867 1719
868### Advanced Debugging1720### Security best practices
869 1721
870For complex hook issues:1722Keep these practices in mind when writing hooks:
871 1723
8721. **Inspect hook execution** - Use `claude --debug` to see detailed hook1724* **Validate and sanitize inputs**: never trust input data blindly
873 execution1725* **Always quote shell variables**: use `"$VAR"` not `$VAR`
8742. **Validate JSON schemas** - Test hook input/output with external tools1726* **Block path traversal**: check for `..` in file paths
8753. **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
8764. **Test edge cases** - Try hooks with unusual file paths or inputs1728* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.
8775. **Monitor system resources** - Check for resource exhaustion during hook
878 execution
8796. **Use structured logging** - Implement logging in your hook scripts
880 1729
881### Debug Output Example1730## Debug hooks
882 1731
883Use `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.
884 1733
885```1734```
886[DEBUG] Executing hooks for PostToolUse:Write1735[DEBUG] Executing hooks for PostToolUse:Write
888[DEBUG] Found 1 hook matchers in settings1737[DEBUG] Found 1 hook matchers in settings
889[DEBUG] Matched 1 hooks for query "Write"1738[DEBUG] Matched 1 hooks for query "Write"
890[DEBUG] Found 1 hook commands to execute1739[DEBUG] Found 1 hook commands to execute
891[DEBUG] Executing hook command: <Your command> with timeout 60000ms1740[DEBUG] Executing hook command: <Your command> with timeout 600000ms
892[DEBUG] Hook command completed with status 0: <Your stdout>1741[DEBUG] Hook command completed with status 0: <Your stdout>
893```1742```
894 1743
895Progress 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.
896
897* Which hook is running
898* Command being executed
899* Success/failure status
900* Output or error messages