Intercept and control agent behavior with hooks
--- a/hooks.md
+++ b/hooks.md
@@ -794,7 +794,7 @@
* `WorktreeCreate`: worktree creation fails with an error.
* `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues. To block compaction when a `PreCompact` callback times out, set `onFailure: "block"`.
-The first time a `Stop` or `SessionStart` callback times out in the main session, Claude Code also adds an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) to the message stream saying the app driving the session didn’t respond. Later timeouts don’t repeat that message while your app stays unresponsive. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
+The first time a `Stop` or `SessionStart` callback times out in the main session, your message stream also includes an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) object saying the app driving the session didn’t respond. While your app stays unresponsive, at most one such message arrives per hook type. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
### Tool blocked unexpectedly
--- a/hooks.md
+++ b/hooks.md
@@ -783,7 +783,7 @@
### Hook timeout
-Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and discards its output, and the session continues rather than hanging. What happens next depends on the event:
+Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and discards its output. On the events below, Claude Code then blocks the action or continues without the callback:
* `PreToolUse`: Claude Code blocks the tool call. If every other hook returned nothing or only an `allow` decision, the tool result tells Claude the hook didn’t respond before its timeout, and the turn continues. If another of your hooks already denied the call, its deny still reaches Claude: the tool result includes that hook’s reason, and the timeout text can follow it. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
* `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.
@@ -792,7 +792,7 @@
* `SessionStart`: the timed-out callback counts as returning no output, and the session continues with the output of your other `SessionStart` hooks.
* `PreModelSwitch`: Claude Code blocks the model switch. A hook that doesn’t answer hasn’t approved the switch.
* `WorktreeCreate`: worktree creation fails with an error.
- * Other events, such as `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues. With `onFailure: "block"`, a timeout on `PreCompact` or `Elicitation` blocks the action.
+ * `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues. To block compaction when a `PreCompact` callback times out, set `onFailure: "block"`.
The first time a `Stop` or `SessionStart` callback times out in the main session, Claude Code also adds an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) to the message stream saying the app driving the session didn’t respond. Later timeouts don’t repeat that message while your app stays unresponsive. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
--- a/hooks.md
+++ b/hooks.md
@@ -149,7 +149,7 @@
`PostToolBatch`| No| Yes| A full batch of tool calls resolves, once per batch before the next model call| Inject conventions once for the whole batch
[`UserPromptSubmit`](</docs/en/hooks#userpromptsubmit>)| Yes| Yes| A prompt is submitted, including a turn Claude Code starts on its own| Inject additional context into prompts
[`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>)| No| Yes| A user-typed command, or an MCP prompt, expands into a prompt before it reaches Claude. Doesn’t fire when Claude invokes a skill itself| Block a command from direct invocation or add context when a skill is typed
-`MessageDisplay`| No| Yes| An assistant message with text completes, once per message with the full message text| Redact or reformat the displayed text without changing the transcript
+`MessageDisplay`| No| Yes| An assistant message with text completes, once per message with the full message text| Reformat the displayed text without changing the transcript
`Stop`| Yes| Yes| Agent execution stop| Save session state before exit
`StopFailure`| No| Yes| The turn ends with an API error instead of a normal stop| Log failures or send alerts
`SubagentStart`| Yes| Yes| Subagent initialization| Track parallel task spawning
@@ -171,7 +171,7 @@
`ElicitationResult`| No| Yes| A user responds to an MCP elicitation| Modify or block the response before it returns to the server
`ConfigChange`| No| Yes| Configuration file changes| Reload settings dynamically
`InstructionsLoaded`| No| Yes| A `CLAUDE.md` or rules file is loaded into context| Audit which instruction files load
-`WorktreeCreate`| No| Yes| Git worktree created| Track isolated workspaces
+`WorktreeCreate`| No| Yes| Claude Code needs a worktree, and the hook creates it instead of git| Create the worktree and return its path in [`hookSpecificOutput.worktreePath`](</docs/en/hooks#worktreecreate-output>)
`WorktreeRemove`| No| Yes| A worktree created by a `WorktreeCreate` hook is being removed| Clean up workspace resources
`CwdChanged`| No| Yes| The working directory changes during a session| Reload environment variables per directory
`FileChanged`| No| Yes| A watched file is modified, created, or deleted| Reload configuration when project files change
@@ -299,7 +299,7 @@
}
};
-To test it, make the callback raise an error and ask Claude to run a Bash command. The tool result includes `failed; blocking because onFailure is "block"`, and Claude doesn’t see your error text. Return `{}` when the callback has no opinion. With `"block"` set, a path with no `return` blocks the action. A callback that catches its own error and returns `{}` isn’t failing, so let the error propagate from a guard.
+To test it, make the callback raise an error and ask Claude to run a Bash command. The tool result includes `failed; blocking because onFailure is "block"`, and Claude doesn’t see your error text. Return `{}` when the callback has no opinion. With `"block"` set, a path with no `return` blocks the action. A callback that catches its own error and returns `{}` isn’t failing, so let the error propagate from a guard. A `WorktreeCreate` callback must return `hookSpecificOutput.worktreePath`.
#### Events that behave differently
@@ -309,7 +309,7 @@
* **`PermissionRequest`** : the block counts only if it arrives before your `canUseTool` callback answers.
* **`PostToolUse`** : the tool has already run, so Claude receives the failure as feedback.
-A callback that exceeds its timeout follows Hook timeout. With `"block"` set, a timeout also blocks `PreCompact`, `Elicitation`, and `WorktreeCreate`.
+A callback that exceeds its timeout follows Hook timeout. With `"block"` set, a timeout also blocks `PreCompact` and `Elicitation`.
#### Startup errors for `onFailure`
@@ -791,7 +791,8 @@
* `Stop` and `SubagentStop`: the timed-out callback counts as returning no decision. The agent or subagent stops as if that callback had allowed it, and a decision from your other hooks on the event still applies. Before Claude Code v2.1.273, a timed-out `Stop` or `SubagentStop` callback counted as a failed hook run, and Claude Code discarded the decisions of your other hooks on the event.
* `SessionStart`: the timed-out callback counts as returning no output, and the session continues with the output of your other `SessionStart` hooks.
* `PreModelSwitch`: Claude Code blocks the model switch. A hook that doesn’t answer hasn’t approved the switch.
- * Other events, such as `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues. With `onFailure: "block"`, a timeout on `PreCompact`, `Elicitation`, or `WorktreeCreate` blocks the action.
+ * `WorktreeCreate`: worktree creation fails with an error.
+ * Other events, such as `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues. With `onFailure: "block"`, a timeout on `PreCompact` or `Elicitation` blocks the action.
The first time a `Stop` or `SessionStart` callback times out in the main session, Claude Code also adds an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) to the message stream saying the app driving the session didn’t respond. Later timeouts don’t repeat that message while your app stays unresponsive. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
--- a/hooks.md
+++ b/hooks.md
@@ -533,7 +533,7 @@
### Track subagent activity
-Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references. This example logs a summary each time a subagent completes:
+Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references. This example logs a summary when a subagent completes:
Python
--- a/hooks.md
+++ b/hooks.md
@@ -69,7 +69,7 @@
}
}
- # Return empty object to allow the operation
+ # Empty object: no decision, normal permissions apply
return {}
async def main():
@@ -113,7 +113,7 @@
};
}
- // Return empty object to allow the operation
+ // Empty object: no decision, normal permissions apply
return {};
};
@@ -133,7 +133,7 @@
}
}
-The hook denies a Write or Edit call whose `file_path` ends in `/.env`, in any letter case. On Windows, `file_path` uses backslashes, such as `C:\project\.env`, and this hook allows a Write or Edit call to `C:\project\.env`.
+The hook denies a Write or Edit call whose `file_path` ends in `/.env`, in any letter case. On Windows, `file_path` uses backslashes, such as `C:\project\.env`, and this hook doesn’t block a Write or Edit call to `C:\project\.env`.
The `Write|Edit` matcher limits this hook to the Write and Edit tools. If Claude writes `.env` with a Bash command, the hook doesn’t run. To block Bash writes to a file where [the sandbox runs](</docs/en/sandboxing>), see the sandbox configuration for [Python](</docs/en/agent-sdk/python#sandbox-configuration>) or [TypeScript](</docs/en/agent-sdk/typescript#sandbox-configuration>).
@@ -245,7 +245,7 @@
* For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for built-in and MCP tools in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only.
* In the TypeScript SDK, a `PostToolUse` callback can also return `classifierContext`, a short note about the tool call’s result for the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) permission classifier. Because your callback runs in your application’s own process, the classifier may weigh a user statement you relay in the note as user intent. The field requires TypeScript Agent SDK v0.3.236 or later. [Annotate a result for the auto mode classifier](</docs/en/hooks#annotate-a-result-for-the-auto-mode-classifier>) covers the length cap, the synchronous-only rule, and what not to put in the note.
-Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
+For `PreToolUse`, return `{}` to make no decision, so the normal [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) applies. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
When multiple `PreToolUse` hooks return different [decisions](</docs/en/hooks#pretooluse-decision-control>), `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`.
--- a/hooks.md
+++ b/hooks.md
@@ -800,6 +800,7 @@
* Check all `PreToolUse` hooks for `permissionDecision: 'deny'` returns
* Add logging to your hooks to see what `permissionDecisionReason` they’re returning
* Verify matcher patterns aren’t too broad: an empty matcher matches all tools
+ * If the tool result says a hook `returned updatedInput that failed schema validation` or `returned updatedInput that the tool refused`, fix that hook’s `updatedInput`. Include the unchanged `tool_input` fields, as in Modify tool input, because `updatedInput` replaces the whole input.
### Modified input not applied
Show diff (379 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -6,11 +6,7 @@
* **Require human approval** for sensitive actions like database writes or API calls
* **Track session lifecycle** to manage state, clean up resources, or send notifications
-##
-
-
-
-How hooks work
+## How hooks work
1
@@ -141,11 +137,7 @@
The `Write|Edit` matcher limits this hook to the Write and Edit tools. If Claude writes `.env` with a Bash command, the hook doesn’t run. To block Bash writes to a file where [the sandbox runs](</docs/en/sandboxing>), see the sandbox configuration for [Python](</docs/en/agent-sdk/python#sandbox-configuration>) or [TypeScript](</docs/en/agent-sdk/typescript#sandbox-configuration>).
-##
-
-
-
-Available hooks
+## Available hooks
The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only.
@@ -185,11 +177,7 @@
`FileChanged`| No| Yes| A watched file is modified, created, or deleted| Reload configuration when project files change
`DirectoryAdded`| No| Yes| A working directory is added during a session| Install dependencies for a repository added mid-session
-##
-
-
-
-Configure hooks
+## Configure hooks
To configure a hook, pass it in the `hooks` field of your agent options (`ClaudeAgentOptions` in Python, the `options` object in TypeScript). This snippet assumes you have already defined a hook callback, like `protect_env_files` in Python or `protectEnvFiles` in TypeScript from the example above:
@@ -222,11 +210,7 @@
* **Keys** : hook event names such as `'PreToolUse'`, `'PostToolUse'`, and `'Stop'`
* **Values** : arrays of matchers, each containing an optional filter pattern and your callback functions
-###
-
-
-
-Matchers
+### Matchers
Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). That section documents the exact-string and regular-expression evaluation paths, their version requirements, and the matcher values for each event type.
@@ -239,17 +223,9 @@
Use the `matcher` pattern to target specific tools whenever possible. With a `'Bash'` matcher, your callbacks run for Bash commands. On Claude Code v2.1.314 or later, they also run on `PreToolUse` and `PermissionRequest` for Monitor commands, which they [can deny but not approve](</docs/en/hooks#match-monitor-commands>). With no matcher, they run for every occurrence of the event.
-###
-
-
-
-Callback functions
-
-####
-
-
-
-Inputs
+### Callback functions
+
+#### Inputs
Every hook callback receives three arguments:
@@ -259,11 +235,7 @@
* **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call.
* **Context:** in TypeScript, contains a `signal` property (`AbortSignal`) for cancellation. In Python, this argument is reserved for future use.
-####
-
-
-
-Outputs
+#### Outputs
Your callback returns an object with two categories of fields:
@@ -277,11 +249,7 @@
When multiple `PreToolUse` hooks return different [decisions](</docs/en/hooks#pretooluse-decision-control>), `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`.
-####
-
-
-
-Asynchronous output
+#### Asynchronous output
By default, the agent waits for your hook to return before proceeding. If your hook performs a side effect, such as logging or sending a webhook, and doesn’t need to influence the agent’s behavior, you can return an async output instead. This tells the agent to continue immediately without waiting for the hook to finish. In this snippet, `send_to_logging_service` in Python and `sendToLoggingService` in TypeScript stand in for any logging function you define:
@@ -307,11 +275,7 @@
Async outputs can’t block, modify, or inject context into the operation since the agent has already moved on. Use them only for side effects like logging, metrics, or notifications.
-###
-
-
-
-Block the action when a callback fails
+### Block the action when a callback fails
On most events, if a callback throws or returns output that fails validation, the action goes ahead and your app receives an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) warning whose `tag` is `hook_callback_failed`. A `PreToolUse` guard that crashes then lets the tool call reach the normal permission flow. A callback that returns nothing, such as a path with no `return`, also counts as failing. In Python, read `tag` from `SystemMessage.data`. To block the action instead, set `onFailure: "block"` in TypeScript or `on_failure="block"` in Python on the matcher. Requires TypeScript Agent SDK v0.3.317 or later, or Python Agent SDK v0.2.177 or later. This example blocks a Bash call when `check_policy` in Python or `checkPolicy` in TypeScript fails:
@@ -337,11 +301,7 @@
To test it, make the callback raise an error and ask Claude to run a Bash command. The tool result includes `failed; blocking because onFailure is "block"`, and Claude doesn’t see your error text. Return `{}` when the callback has no opinion. With `"block"` set, a path with no `return` blocks the action. A callback that catches its own error and returns `{}` isn’t failing, so let the error propagate from a guard.
-####
-
-
-
-Events that behave differently
+#### Events that behave differently
These events don’t always block with `"block"` set:
@@ -351,30 +311,18 @@
A callback that exceeds its timeout follows Hook timeout. With `"block"` set, a timeout also blocks `PreCompact`, `Elicitation`, and `WorktreeCreate`.
-####
-
-
-
-Startup errors for `onFailure`
+#### Startup errors for `onFailure`
With `"block"` set, the query fails at startup and sends no prompt when it can’t honor the option:
* **Claude Code doesn’t support the option** : the error includes `does not honor`. Update Claude Code, or remove the option.
* **The session was already running and didn’t register your hooks** : the error includes `did not register your hooks`. Start a new session.
-##
-
-
-
-Examples
+## Examples
Several examples in this section show only the callback function. To run one, register the callback under the matching event in the `hooks` field of your options, as shown in Configure hooks.
-###
-
-
-
-Modify tool input
+### Modify tool input
This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation:
@@ -425,11 +373,7 @@
To confirm the redirect, set the prefix to a path you can write to, such as `./sandbox` or `/tmp/sandbox` (macOS doesn’t allow creating a root-level `/sandbox` directory), then ask the agent to write a file: the Write tool’s result in the message stream names the path with your sandbox prefix rather than the one Claude requested.
-###
-
-
-
-Add context and block a tool
+### Add context and block a tool
This example denies tool calls whose `file_path` starts with `/etc` and explains why to both the model and the user:
@@ -479,11 +423,7 @@
To confirm the block, register the callback under `PreToolUse` with a `Write|Edit` matcher and ask the agent to create a file under `/etc`: the Write tool’s result in the message stream contains `Writing to /etc is not allowed`, and no file is created.
-###
-
-
-
-Auto-approve specific tools
+### Auto-approve specific tools
By default, the agent may prompt for permission before using certain tools. This example auto-approves read-only filesystem tools (Read, Glob, Grep) by returning `permissionDecision: 'allow'`, letting them run without user confirmation, apart from reads from [network paths](</docs/en/permissions#network-paths>), while leaving all other tools subject to normal permission checks:
@@ -523,11 +463,7 @@
return {};
};
-###
-
-
-
-Register multiple hooks
+### Register multiple hooks
When an event fires, the matching hooks run in parallel. For permission decisions, the most restrictive result applies. One hook’s `deny` blocks the tool call. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks, each with an [omitted matcher](</docs/en/hooks#matcher-patterns>). The hook names in it, such as `audit_logger` in Python or `auditLogger` in TypeScript, stand in for callbacks you define:
@@ -555,11 +491,7 @@
}
};
-###
-
-
-
-Filter with multi-tool matchers
+### Filter with multi-tool matchers
Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes, and each hook it names stands in for a callback you define:
@@ -599,11 +531,7 @@
}
};
-###
-
-
-
-Track subagent activity
+### Track subagent activity
Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references. This example logs a summary each time a subagent completes:
@@ -645,11 +573,7 @@
To confirm the hook fires, register the callback and ask the agent to delegate a small task to a subagent, such as listing the files in the current directory: when the subagent finishes, the callback prints the `[SUBAGENT] Completed:` lines with the subagent’s ID and transcript path.
-###
-
-
-
-Make HTTP requests from hooks
+### Make HTTP requests from hooks
Hooks can perform asynchronous operations like HTTP requests. Catch errors inside your hook instead of letting them propagate. This example sends a webhook after each tool completes, logging which tool ran and when. The hook catches errors from a failed webhook:
@@ -734,11 +658,7 @@
To confirm the hook fires, point the webhook URL at an endpoint you can watch and send a prompt that uses a tool: the hook sends a POST with the tool name and timestamp after each tool completes.
-###
-
-
-
-Forward notifications to Slack
+### Forward notifications to Slack
Use `Notification` hooks to receive system notifications from the agent and forward them to external services. In SDK sessions, Claude Code runs this hook for the following notification types:
@@ -838,17 +758,9 @@
When a `Notification` event fires, the hook posts the notification’s `message`, prefixed with `Agent status:`, to the channel your webhook targets.
-##
-
-
-
-Fix common issues
-
-###
-
-
-
-Hook not firing
+## Fix common issues
+
+### Hook not firing
* Verify the hook event name is correct and case-sensitive (`PreToolUse`, not `preToolUse`)
* Check that your matcher pattern matches the tool name exactly
@@ -856,11 +768,7 @@
* For non-tool hooks that support matchers, like `Notification` and `SubagentStop`, matchers match against different fields, and `Stop` ignores matchers entirely (see [matcher patterns](</docs/en/hooks#matcher-patterns>))
* Hooks may not fire when the agent hits the [`max_turns`](</docs/en/agent-sdk/python#claudeagentoptions>) limit because the session ends before hooks can execute
-###
-
-
-
-Matcher not filtering as expected
+### Matcher not filtering as expected
Matchers only match tool names, not file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your hook:
@@ -873,11 +781,7 @@
return {};
};
-###
-
-
-
-Hook timeout
+### Hook timeout
Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and discards its output, and the session continues rather than hanging. What happens next depends on the event:
@@ -891,21 +795,13 @@
The first time a `Stop` or `SessionStart` callback times out in the main session, Claude Code also adds an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) to the message stream saying the app driving the session didn’t respond. Later timeouts don’t repeat that message while your app stays unresponsive. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
-###
-
-
-
-Tool blocked unexpectedly
+### Tool blocked unexpectedly
* Check all `PreToolUse` hooks for `permissionDecision: 'deny'` returns
* Add logging to your hooks to see what `permissionDecisionReason` they’re returning
* Verify matcher patterns aren’t too broad: an empty matcher matches all tools
-###
-
-
-
-Modified input not applied
+### Modified input not applied
* Ensure `updatedInput` is inside `hookSpecificOutput`, not at the top level:
@@ -920,11 +816,7 @@
* Don’t pair `updatedInput` with `permissionDecision: 'defer'`, which drops the modified input. Omitting `permissionDecision` is fine: the modified input still applies through the normal permission evaluation. You can also return `'allow'` to auto-approve the modified input or `'ask'` to show it to the user for approval
* Include `hookEventName` in `hookSpecificOutput` to identify which hook type the output is for
-###
-
-
-
-Session hooks not available in Python
+### Session hooks not available in Python
`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren’t available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](</docs/en/hooks#hook-events>) defined in settings files such as `.claude/settings.json`. Which settings files your SDK application loads depends on [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) or [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>). If you set that option, include the source that holds the hooks:
@@ -942,38 +834,22 @@
To run initialization logic as a Python SDK callback instead, use the first message from `client.receive_response()` as your trigger.
-###
-
-
-
-Subagent permission prompts multiplying
+### Subagent permission prompts multiplying
When spawning multiple subagents, each one may request permissions separately for its own tool calls. To avoid repeated prompts, use `PreToolUse` hooks to auto-approve specific tools, or configure permission rules, which subagents [inherit from the parent conversation](</docs/en/sub-agents#permission-modes>).
-###
-
-
-
-Recursive hook loops with subagents
+### Recursive hook loops with subagents
A `UserPromptSubmit` hook that spawns subagents can create infinite loops if those subagents trigger the same hook. To prevent this:
* Use a shared variable or session state to track whether you’re already inside a subagent
* Scope hooks to only run for the top-level agent session
-###
-
-
-
-systemMessage not appearing in output
+### systemMessage not appearing in output
The `systemMessage` field shows a message to the user, not the model. On Claude Code v2.1.227 or later, a hook’s `systemMessage` can surface in the message stream as an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>). Whether it does depends on the event. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says how output surfaces. To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). Before v2.1.227, the SDK surfaced hook output in the message stream only for `SessionStart` and `Setup` hooks. For any other event, the output appeared only in the lifecycle events that [`includeHookEvents`](</docs/en/agent-sdk/typescript#options>) (`include_hook_events` in Python) adds. That option’s entry covers which lifecycle events each hook event produces. If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel.
-##
-
-
-
-Related resources
+## Related resources
* [Claude Code hooks reference](</docs/en/hooks>): full JSON input/output schemas, event documentation, and matcher patterns
* [Claude Code hooks guide](</docs/en/hooks-guide>): shell command hook examples and walkthroughs
--- a/hooks.md
+++ b/hooks.md
@@ -270,7 +270,7 @@
* **Top-level fields** are accepted on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. Some events discard them or deliver them elsewhere. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says where they land.
* **`hookSpecificOutput`** controls the current operation. The fields you set inside depend on the hook event type:
* For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. If you return `"defer"`, the turn ends with a result message whose `stop_reason` is `"tool_deferred"`, so you can [resume the call later](</docs/en/hooks#defer-a-tool-call-for-later>).
- * For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only.
+ * For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for built-in and MCP tools in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only.
* In the TypeScript SDK, a `PostToolUse` callback can also return `classifierContext`, a short note about the tool call’s result for the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) permission classifier. Because your callback runs in your application’s own process, the classifier may weigh a user statement you relay in the note as user intent. The field requires TypeScript Agent SDK v0.3.236 or later. [Annotate a result for the auto mode classifier](</docs/en/hooks#annotate-a-result-for-the-auto-mode-classifier>) covers the length cap, the synchronous-only rule, and what not to put in the note.
Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
--- a/hooks.md
+++ b/hooks.md
@@ -237,7 +237,7 @@
`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout. Your SDK callbacks follow the `command` hook defaults
`onFailure`| `"continue" | "block"`| `undefined`| What a failed callback does. Set `"block"` to block the action when a callback fails. In Python, use `on_failure`
-Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event.
+Use the `matcher` pattern to target specific tools whenever possible. With a `'Bash'` matcher, your callbacks run for Bash commands. On Claude Code v2.1.314 or later, they also run on `PreToolUse` and `PermissionRequest` for Monitor commands, which they [can deny but not approve](</docs/en/hooks#match-monitor-commands>). With no matcher, they run for every occurrence of the event.
###
--- a/hooks.md
+++ b/hooks.md
@@ -235,6 +235,7 @@
`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the [rules for matchers in settings files](</docs/en/hooks#matcher-patterns>). For tool hooks, that field is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others. See [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list. MCP tools use the pattern `mcp__<server>__<action>`, where `<server>` is the key you use in the `mcpServers` configuration, spelled as the [tool naming convention](</docs/en/agent-sdk/mcp#tool-naming-convention>) describes.
`hooks`| `HookCallback[]`| -| Required. Array of callback functions to execute when the pattern matches
`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout. Your SDK callbacks follow the `command` hook defaults
+`onFailure`| `"continue" | "block"`| `undefined`| What a failed callback does. Set `"block"` to block the action when a callback fails. In Python, use `on_failure`
Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event.
@@ -305,6 +306,61 @@
`asyncTimeout`| `number`| Optional timeout in milliseconds for the background operation
Async outputs can’t block, modify, or inject context into the operation since the agent has already moved on. Use them only for side effects like logging, metrics, or notifications.
+
+###
+
+
+
+Block the action when a callback fails
+
+On most events, if a callback throws or returns output that fails validation, the action goes ahead and your app receives an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) warning whose `tag` is `hook_callback_failed`. A `PreToolUse` guard that crashes then lets the tool call reach the normal permission flow. A callback that returns nothing, such as a path with no `return`, also counts as failing. In Python, read `tag` from `SystemMessage.data`. To block the action instead, set `onFailure: "block"` in TypeScript or `on_failure="block"` in Python on the matcher. Requires TypeScript Agent SDK v0.3.317 or later, or Python Agent SDK v0.2.177 or later. This example blocks a Bash call when `check_policy` in Python or `checkPolicy` in TypeScript fails:
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ hooks={
+ "PreToolUse": [
+ HookMatcher(matcher="Bash", hooks=[check_policy], on_failure="block")
+ ]
+ }
+ )
+
+ import type { Options } from "@anthropic-ai/claude-agent-sdk";
+
+ const options: Options = {
+ hooks: {
+ PreToolUse: [{ matcher: "Bash", hooks: [checkPolicy], onFailure: "block" }]
+ }
+ };
+
+To test it, make the callback raise an error and ask Claude to run a Bash command. The tool result includes `failed; blocking because onFailure is "block"`, and Claude doesn’t see your error text. Return `{}` when the callback has no opinion. With `"block"` set, a path with no `return` blocks the action. A callback that catches its own error and returns `{}` isn’t failing, so let the error propagate from a guard.
+
+####
+
+
+
+Events that behave differently
+
+These events don’t always block with `"block"` set:
+
+ * **`Stop`, `SubagentStop`, `TaskCompleted`, and `TeammateIdle`**: these events ignore the option, so the action goes ahead.
+ * **`PermissionRequest`** : the block counts only if it arrives before your `canUseTool` callback answers.
+ * **`PostToolUse`** : the tool has already run, so Claude receives the failure as feedback.
+
+A callback that exceeds its timeout follows Hook timeout. With `"block"` set, a timeout also blocks `PreCompact`, `Elicitation`, and `WorktreeCreate`.
+
+####
+
+
+
+Startup errors for `onFailure`
+
+With `"block"` set, the query fails at startup and sends no prompt when it can’t honor the option:
+
+ * **Claude Code doesn’t support the option** : the error includes `does not honor`. Update Claude Code, or remove the option.
+ * **The session was already running and didn’t register your hooks** : the error includes `did not register your hooks`. Start a new session.
##
@@ -831,7 +887,7 @@
* `Stop` and `SubagentStop`: the timed-out callback counts as returning no decision. The agent or subagent stops as if that callback had allowed it, and a decision from your other hooks on the event still applies. Before Claude Code v2.1.273, a timed-out `Stop` or `SubagentStop` callback counted as a failed hook run, and Claude Code discarded the decisions of your other hooks on the event.
* `SessionStart`: the timed-out callback counts as returning no output, and the session continues with the output of your other `SessionStart` hooks.
* `PreModelSwitch`: Claude Code blocks the model switch. A hook that doesn’t answer hasn’t approved the switch.
- * Other events, such as `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues.
+ * Other events, such as `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues. With `onFailure: "block"`, a timeout on `PreCompact`, `Elicitation`, or `WorktreeCreate` blocks the action.
The first time a `Stop` or `SessionStart` callback times out in the main session, Claude Code also adds an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) to the message stream saying the app driving the session didn’t respond. Later timeouts don’t repeat that message while your app stays unresponsive. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
--- a/hooks.md
+++ b/hooks.md
@@ -825,7 +825,7 @@
Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and discards its output, and the session continues rather than hanging. What happens next depends on the event:
- * `PreToolUse`: Claude Code blocks the tool call. In its place, Claude receives a tool result saying the hook didn’t respond before its timeout, and the turn continues. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
+ * `PreToolUse`: Claude Code blocks the tool call. If every other hook returned nothing or only an `allow` decision, the tool result tells Claude the hook didn’t respond before its timeout, and the turn continues. If another of your hooks already denied the call, its deny still reaches Claude: the tool result includes that hook’s reason, and the timeout text can follow it. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
* `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.
* `UserPromptSubmit` and [`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>): Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out.
* `Stop` and `SubagentStop`: the timed-out callback counts as returning no decision. The agent or subagent stops as if that callback had allowed it, and a decision from your other hooks on the event still applies. Before Claude Code v2.1.273, a timed-out `Stop` or `SubagentStop` callback counted as a failed hook run, and Claude Code discarded the decisions of your other hooks on the event.
--- a/hooks.md
+++ b/hooks.md
@@ -688,6 +688,7 @@
* [`permission_prompt`](</docs/en/hooks#notification>) once a permission request has waited about six seconds on your [`canUseTool` callback](</docs/en/agent-sdk/user-input>). Requires TypeScript Agent SDK v0.3.233 or later, or Python Agent SDK v0.2.139 or later
* `elicitation_complete` and `elicitation_response` for user-prompt elicitation flows
+ * `plugin_notification` when a [mod](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>) calls `$.ui.notify`
Claude Code emits the other types, such as `idle_prompt`, `auth_success`, and `elicitation_dialog`, from interactive UI that SDK sessions don’t run. Each notification includes a `message` field with a human-readable description and optionally a `title`. This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](<https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/>), which you create by adding an app to your Slack workspace and enabling incoming webhooks:
Show diff (136 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -1,7 +1,7 @@
Hooks are callback functions that run your code in response to agent events, like a tool being called, a session starting, or execution stopping. With hooks, you can:
* **Block dangerous operations** before they execute, like destructive shell commands or unauthorized file access
- * **Log and audit** every tool call for compliance, debugging, or analytics
+ * **Log and audit** tool calls for compliance, debugging, or analytics
* **Transform inputs and outputs** to sanitize data, inject credentials, or redirect file paths
* **Require human approval** for sensitive actions like database writes or API calls
* **Track session lifecycle** to manage state, clean up resources, or send notifications
@@ -42,7 +42,7 @@
After performing any operations (logging, API calls, validation), your callback returns an output object that tells the agent what to do: allow the operation, block it, modify the input, or inject context into the conversation.
-The following example puts these steps together. It registers a `PreToolUse` hook (step 1) with a `"Write|Edit"` matcher (step 3) so the callback only fires for file-writing tools. When triggered, the callback receives the tool’s input (step 4), checks if the file path targets a `.env` file, and returns `permissionDecision: "deny"` to block the operation (step 5):
+This example registers a `PreToolUse` hook (step 1) with a `"Write|Edit"` matcher (step 3) so the callback fires for the Write and Edit tools. When triggered, the callback receives the tool’s input (step 4), checks if the file path targets a `.env` file, and returns `permissionDecision: "deny"` to block the operation (step 5):
Python
@@ -64,7 +64,7 @@
file_name = file_path.split("/")[-1]
# Block the operation if targeting a .env file
- if file_name == ".env":
+ if file_name.lower() == ".env":
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
@@ -107,7 +107,7 @@
const fileName = filePath?.split("/").pop();
// Block the operation if targeting a .env file
- if (fileName === ".env") {
+ if (fileName?.toLowerCase() === ".env") {
return {
hookSpecificOutput: {
hookEventName: preInput.hook_event_name,
@@ -137,7 +137,9 @@
}
}
-When you run either script, Claude attempts to create the `.env` file and the hook denies the tool call.
+The hook denies a Write or Edit call whose `file_path` ends in `/.env`, in any letter case. On Windows, `file_path` uses backslashes, such as `C:\project\.env`, and this hook allows a Write or Edit call to `C:\project\.env`.
+
+The `Write|Edit` matcher limits this hook to the Write and Edit tools. If Claude writes `.env` with a Bash command, the hook doesn’t run. To block Bash writes to a file where [the sandbox runs](</docs/en/sandboxing>), see the sandbox configuration for [Python](</docs/en/agent-sdk/python#sandbox-configuration>) or [TypeScript](</docs/en/agent-sdk/typescript#sandbox-configuration>).
##
@@ -150,7 +152,7 @@
Hook Event| Python SDK| TypeScript SDK| What triggers it| Example use case
---|---|---|---|---
`PreToolUse`| Yes| Yes| Tool call request (can block or modify)| Block dangerous shell commands
-`PostToolUse`| Yes| Yes| Tool execution result| Log all file changes to audit trail
+`PostToolUse`| Yes| Yes| Tool execution result| Log file changes to an audit trail
`PostToolUseFailure`| Yes| Yes| Tool execution failure| Handle or log tool errors
`PostToolBatch`| No| Yes| A full batch of tool calls resolves, once per batch before the next model call| Inject conventions once for the whole batch
[`UserPromptSubmit`](</docs/en/hooks#userpromptsubmit>)| Yes| Yes| A prompt is submitted, including a turn Claude Code starts on its own| Inject additional context into prompts
@@ -230,11 +232,11 @@
Option| Type| Default| Description
---|---|---|---
-`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the [rules for matchers in settings files](</docs/en/hooks#matcher-patterns>). For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`, where `<server>` is the key you use in the `mcpServers` configuration.
+`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the [rules for matchers in settings files](</docs/en/hooks#matcher-patterns>). For tool hooks, that field is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others. See [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list. MCP tools use the pattern `mcp__<server>__<action>`, where `<server>` is the key you use in the `mcpServers` configuration, spelled as the [tool naming convention](</docs/en/agent-sdk/mcp#tool-naming-convention>) describes.
`hooks`| `HookCallback[]`| -| Required. Array of callback functions to execute when the pattern matches
`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout. Your SDK callbacks follow the `command` hook defaults
-Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event. Omit it on purpose to log every tool call your session makes.
+Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event.
###
@@ -272,7 +274,7 @@
Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
-When multiple hooks or permission rules apply, `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`. If any hook returns `deny`, the operation is blocked regardless of other hooks.
+When multiple `PreToolUse` hooks return different [decisions](</docs/en/hooks#pretooluse-decision-control>), `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`.
####
@@ -318,7 +320,7 @@
Modify tool input
-This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`, redirecting all file writes to a sandboxed directory. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation:
+This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation:
Python
@@ -373,10 +375,10 @@
Add context and block a tool
-This example blocks writes to the `/etc` directory and explains why to both the model and the user:
+This example denies tool calls whose `file_path` starts with `/etc` and explains why to both the model and the user:
* `permissionDecision: 'deny'` stops the tool call.
- * `permissionDecisionReason` tells the model why, so it avoids retrying.
+ * `permissionDecisionReason` tells the model why.
* `systemMessage` shows the user what happened.
Python
@@ -471,7 +473,7 @@
Register multiple hooks
-When an event fires, all matching hooks run in parallel. For permission decisions, the most restrictive result applies: a single `deny` blocks the tool call regardless of what the other hooks return. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks for every tool call. The hook names in it, such as `audit_logger` in Python or `auditLogger` in TypeScript, stand in for callbacks you define:
+When an event fires, the matching hooks run in parallel. For permission decisions, the most restrictive result applies. One hook’s `deny` blocks the tool call. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks, each with an [omitted matcher](</docs/en/hooks#matcher-patterns>). The hook names in it, such as `audit_logger` in Python or `auditLogger` in TypeScript, stand in for callbacks you define:
Python
@@ -505,9 +507,9 @@
Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes, and each hook it names stands in for a callback you define:
- * A pipe-separated exact list (`Write|Edit|NotebookEdit`) triggers `file_security_hook` only for file modification tools.
+ * A pipe-separated exact list (`Write|Edit|NotebookEdit`) triggers `file_security_hook` for the Write, Edit, and NotebookEdit tools.
* A regex (`^mcp__`) triggers `mcp_audit_hook` for any MCP tool whose name starts with `mcp__`.
- * An omitted matcher triggers `global_logger` for every tool call regardless of name.
+ * An omitted matcher triggers `global_logger` without filtering by tool name.
Python
@@ -822,9 +824,9 @@
Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and discards its output, and the session continues rather than hanging. What happens next depends on the event:
- * `PreToolUse`: Claude Code doesn’t run the tool call, Claude receives a tool result stating the hook didn’t respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
+ * `PreToolUse`: Claude Code blocks the tool call. In its place, Claude receives a tool result saying the hook didn’t respond before its timeout, and the turn continues. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
* `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.
- * `UserPromptSubmit` and [`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>): Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Because a callback on these events can act as a policy gate, Claude Code never lets a timed-out prompt through unscreened. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out.
+ * `UserPromptSubmit` and [`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>): Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out.
* `Stop` and `SubagentStop`: the timed-out callback counts as returning no decision. The agent or subagent stops as if that callback had allowed it, and a decision from your other hooks on the event still applies. Before Claude Code v2.1.273, a timed-out `Stop` or `SubagentStop` callback counted as a failed hook run, and Claude Code discarded the decisions of your other hooks on the event.
* `SessionStart`: the timed-out callback counts as returning no output, and the session continues with the output of your other `SessionStart` hooks.
* `PreModelSwitch`: Claude Code blocks the model switch. A hook that doesn’t answer hasn’t approved the switch.
--- a/hooks.md
+++ b/hooks.md
@@ -427,7 +427,7 @@
Auto-approve specific tools
-By default, the agent may prompt for permission before using certain tools. This example auto-approves read-only filesystem tools (Read, Glob, Grep) by returning `permissionDecision: 'allow'`, letting them run without user confirmation while leaving all other tools subject to normal permission checks:
+By default, the agent may prompt for permission before using certain tools. This example auto-approves read-only filesystem tools (Read, Glob, Grep) by returning `permissionDecision: 'allow'`, letting them run without user confirmation, apart from reads from [network paths](</docs/en/permissions#network-paths>), while leaving all other tools subject to normal permission checks:
Python
--- a/hooks.md
+++ b/hooks.md
@@ -137,7 +137,7 @@
}
}
-When you run either script, Claude attempts to create the `.env` file, the hook denies the tool call, and Claude’s final response explains that it can’t create `.env` files.
+When you run either script, Claude attempts to create the `.env` file and the hook denies the tool call.
##
@@ -178,7 +178,7 @@
`ConfigChange`| No| Yes| Configuration file changes| Reload settings dynamically
`InstructionsLoaded`| No| Yes| A `CLAUDE.md` or rules file is loaded into context| Audit which instruction files load
`WorktreeCreate`| No| Yes| Git worktree created| Track isolated workspaces
-`WorktreeRemove`| No| Yes| Git worktree removed| Clean up workspace resources
+`WorktreeRemove`| No| Yes| A worktree created by a `WorktreeCreate` hook is being removed| Clean up workspace resources
`CwdChanged`| No| Yes| The working directory changes during a session| Reload environment variables per directory
`FileChanged`| No| Yes| A watched file is modified, created, or deleted| Reload configuration when project files change
`DirectoryAdded`| No| Yes| A working directory is added during a session| Install dependencies for a repository added mid-session
@@ -267,7 +267,7 @@
* **Top-level fields** are accepted on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. Some events discard them or deliver them elsewhere. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says where they land.
* **`hookSpecificOutput`** controls the current operation. The fields you set inside depend on the hook event type:
* For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. If you return `"defer"`, the turn ends with a result message whose `stop_reason` is `"tool_deferred"`, so you can [resume the call later](</docs/en/hooks#defer-a-tool-call-for-later>).
- * For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.
+ * For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only.
* In the TypeScript SDK, a `PostToolUse` callback can also return `classifierContext`, a short note about the tool call’s result for the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) permission classifier. Because your callback runs in your application’s own process, the classifier may weigh a user statement you relay in the note as user intent. The field requires TypeScript Agent SDK v0.3.236 or later. [Annotate a result for the auto mode classifier](</docs/en/hooks#annotate-a-result-for-the-auto-mode-classifier>) covers the length cap, the synchronous-only rule, and what not to put in the note.
Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
@@ -867,7 +867,7 @@
Session hooks not available in Python
-`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren’t available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](</docs/en/hooks#hook-events>) defined in settings files such as `.claude/settings.json`. To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) or [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>):
+`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren’t available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](</docs/en/hooks#hook-events>) defined in settings files such as `.claude/settings.json`. Which settings files your SDK application loads depends on [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) or [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>). If you set that option, include the source that holds the hooks:
Python
--- a/hooks.md
+++ b/hooks.md
@@ -153,7 +153,7 @@
`PostToolUse`| Yes| Yes| Tool execution result| Log all file changes to audit trail
`PostToolUseFailure`| Yes| Yes| Tool execution failure| Handle or log tool errors
`PostToolBatch`| No| Yes| A full batch of tool calls resolves, once per batch before the next model call| Inject conventions once for the whole batch
-`UserPromptSubmit`| Yes| Yes| User prompt submission| Inject additional context into prompts
+[`UserPromptSubmit`](</docs/en/hooks#userpromptsubmit>)| Yes| Yes| A prompt is submitted, including a turn Claude Code starts on its own| Inject additional context into prompts
[`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>)| No| Yes| A user-typed command, or an MCP prompt, expands into a prompt before it reaches Claude. Doesn’t fire when Claude invokes a skill itself| Block a command from direct invocation or add context when a skill is typed
`MessageDisplay`| No| Yes| An assistant message with text completes, once per message with the full message text| Redact or reformat the displayed text without changing the transcript
`Stop`| Yes| Yes| Agent execution stop| Save session state before exit
--- a/hooks.md
+++ b/hooks.md
@@ -266,7 +266,7 @@
* **Top-level fields** are accepted on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. Some events discard them or deliver them elsewhere. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says where they land.
* **`hookSpecificOutput`** controls the current operation. The fields you set inside depend on the hook event type:
- * For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. If you return `"defer"`, the query ends so you can [resume it later](</docs/en/hooks#defer-a-tool-call-for-later>).
+ * For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. If you return `"defer"`, the turn ends with a result message whose `stop_reason` is `"tool_deferred"`, so you can [resume the call later](</docs/en/hooks#defer-a-tool-call-for-later>).
* For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.
* In the TypeScript SDK, a `PostToolUse` callback can also return `classifierContext`, a short note about the tool call’s result for the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) permission classifier. Because your callback runs in your application’s own process, the classifier may weigh a user statement you relay in the note as user intent. The field requires TypeScript Agent SDK v0.3.236 or later. [Annotate a result for the auto mode classifier](</docs/en/hooks#annotate-a-result-for-the-auto-mode-classifier>) covers the length cap, the synchronous-only rule, and what not to put in the note.
--- a/hooks.md
+++ b/hooks.md
@@ -419,6 +419,8 @@
return {};
};
+To confirm the block, register the callback under `PreToolUse` with a `Write|Edit` matcher and ask the agent to create a file under `/etc`: the Write tool’s result in the message stream contains `Writing to /etc is not allowed`, and no file is created.
+
###
@@ -469,7 +471,7 @@
Register multiple hooks
-When an event fires, all matching hooks run in parallel. For permission decisions, the most restrictive result applies: a single `deny` blocks the tool call regardless of what the other hooks return. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks for every tool call:
+When an event fires, all matching hooks run in parallel. For permission decisions, the most restrictive result applies: a single `deny` blocks the tool call regardless of what the other hooks return. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks for every tool call. The hook names in it, such as `audit_logger` in Python or `auditLogger` in TypeScript, stand in for callbacks you define:
Python
@@ -501,7 +503,7 @@
Filter with multi-tool matchers
-Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes:
+Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes, and each hook it names stands in for a callback you define:
* A pipe-separated exact list (`Write|Edit|NotebookEdit`) triggers `file_security_hook` only for file modification tools.
* A regex (`^mcp__`) triggers `mcp_audit_hook` for any MCP tool whose name starts with `mcp__`.
@@ -582,6 +584,8 @@
SubagentStop: [{ hooks: [subagentTracker] }]
}
};
+
+To confirm the hook fires, register the callback and ask the agent to delegate a small task to a subagent, such as listing the files in the current directory: when the subagent finishes, the callback prints the `[SUBAGENT] Completed:` lines with the subagent’s ID and transcript path.
###
--- a/hooks.md
+++ b/hooks.md
@@ -816,16 +816,17 @@
Hook timeout
-Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event:
+Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and discards its output, and the session continues rather than hanging. What happens next depends on the event:
* `PreToolUse`: Claude Code doesn’t run the tool call, Claude receives a tool result stating the hook didn’t respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
* `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.
* `UserPromptSubmit` and [`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>): Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Because a callback on these events can act as a policy gate, Claude Code never lets a timed-out prompt through unscreened. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out.
- * `Stop` and `SubagentStop`: Claude Code shows a warning and the agent stops normally.
+ * `Stop` and `SubagentStop`: the timed-out callback counts as returning no decision. The agent or subagent stops as if that callback had allowed it, and a decision from your other hooks on the event still applies. Before Claude Code v2.1.273, a timed-out `Stop` or `SubagentStop` callback counted as a failed hook run, and Claude Code discarded the decisions of your other hooks on the event.
+ * `SessionStart`: the timed-out callback counts as returning no output, and the session continues with the output of your other `SessionStart` hooks.
* `PreModelSwitch`: Claude Code blocks the model switch. A hook that doesn’t answer hasn’t approved the switch.
* Other events, such as `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues.
-If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
+The first time a `Stop` or `SessionStart` callback times out in the main session, Claude Code also adds an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) to the message stream saying the app driving the session didn’t respond. Later timeouts don’t repeat that message while your app stays unresponsive. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
###
--- a/hooks.md
+++ b/hooks.md
@@ -589,7 +589,7 @@
Make HTTP requests from hooks
-Hooks can perform asynchronous operations like HTTP requests. Catch errors inside your hook instead of letting them propagate, since an unhandled exception can interrupt the agent. This example sends a webhook after each tool completes, logging which tool ran and when. The hook catches errors so a failed webhook doesn’t interrupt the agent:
+Hooks can perform asynchronous operations like HTTP requests. Catch errors inside your hook instead of letting them propagate. This example sends a webhook after each tool completes, logging which tool ran and when. The hook catches errors from a failed webhook:
Python
@@ -625,7 +625,7 @@
# Run the blocking HTTP call in a thread to avoid blocking the event loop
await asyncio.to_thread(_send_webhook, input_data["tool_name"])
except Exception as e:
- # Log the error but don't raise. A failed webhook shouldn't stop the agent
+ # Log the error but don't raise
print(f"Webhook request failed: {e}")
return {}
@@ -652,7 +652,7 @@
if (error instanceof Error && error.name === "AbortError") {
console.log("Webhook request cancelled");
}
- // Don't re-throw. A failed webhook shouldn't stop the agent
+ // Don't re-throw
}
return {};
@@ -894,7 +894,6 @@
A `UserPromptSubmit` hook that spawns subagents can create infinite loops if those subagents trigger the same hook. To prevent this:
- * Check for a subagent indicator in the hook input before spawning
* Use a shared variable or session state to track whether you’re already inside a subagent
* Scope hooks to only run for the top-level agent session
--- a/hooks.md
+++ b/hooks.md
@@ -162,6 +162,8 @@
`SubagentStop`| Yes| Yes| Subagent completion| Aggregate results from parallel tasks
`PreCompact`| Yes| Yes| Conversation compaction request| Archive full transcript before summarizing
`PostCompact`| No| Yes| Conversation compaction completes| Log the generated summary
+[`PreModelSwitch`](</docs/en/hooks#premodelswitch>)| No| Yes| A requested model switch, before it happens (can block)| Block switching to a specific model
+[`PostModelSwitch`](</docs/en/hooks#postmodelswitch>)| No| Yes| The session’s model changes, including an automatic fallback| Give Claude model-specific guidance for the new model
`PermissionRequest`| Yes| Yes| A tool call needs a permission decision| Custom permission handling
`PermissionDenied`| No| Yes| Auto mode denies a tool call, including denials without a classifier verdict| Log denials, or tell the model it may retry; Claude Code ignores `retry: true` for no-verdict denials. See [PermissionDenied](</docs/en/hooks#permissiondenied>)
`SessionStart`| No| Yes| Session initialization| Initialize logging and telemetry
@@ -814,13 +816,14 @@
Hook timeout
-Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event:
+Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event:
* `PreToolUse`: Claude Code doesn’t run the tool call, Claude receives a tool result stating the hook didn’t respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
* `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.
* `UserPromptSubmit` and [`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>): Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Because a callback on these events can act as a policy gate, Claude Code never lets a timed-out prompt through unscreened. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out.
* `Stop` and `SubagentStop`: Claude Code shows a warning and the agent stops normally.
- * Other events, such as `Notification` and `PreCompact`: Claude Code logs the failure and continues.
+ * `PreModelSwitch`: Claude Code blocks the model switch. A hook that doesn’t answer hasn’t approved the switch.
+ * Other events, such as `Notification`, `PreCompact`, and `PostModelSwitch`: Claude Code logs the failure and continues.
If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
--- a/hooks.md
+++ b/hooks.md
@@ -228,13 +228,11 @@
Option| Type| Default| Description
---|---|---|---
-`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the [rules for matchers in settings files](</docs/en/hooks#matcher-patterns>). For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`.
+`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the [rules for matchers in settings files](</docs/en/hooks#matcher-patterns>). For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`, where `<server>` is the key you use in the `mcpServers` configuration.
`hooks`| `HookCallback[]`| -| Required. Array of callback functions to execute when the pattern matches
`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout. Your SDK callbacks follow the `command` hook defaults
-Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event.
-
-**Discovering tool names:** See [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list of built-in tool names, or add a hook without a matcher to log all tool calls your session makes.**MCP tool naming:** MCP tools always start with `mcp__` followed by the server name and action: `mcp__<server>__<action>`. For example, if you configure a server named `playwright`, its tools are named `mcp__playwright__browser_screenshot`, `mcp__playwright__browser_click`, and so on. The server name comes from the key you use in the `mcpServers` configuration.
+Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event. Omit it on purpose to log every tool call your session makes.
###
@@ -265,7 +263,10 @@
Your callback returns an object with two categories of fields:
* **Top-level fields** are accepted on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. Some events discard them or deliver them elsewhere. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says where they land.
- * **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. Returning `"defer"` ends the query so you can [resume it later](</docs/en/hooks#defer-a-tool-call-for-later>). For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.
+ * **`hookSpecificOutput`** controls the current operation. The fields you set inside depend on the hook event type:
+ * For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. If you return `"defer"`, the query ends so you can [resume it later](</docs/en/hooks#defer-a-tool-call-for-later>).
+ * For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.
+ * In the TypeScript SDK, a `PostToolUse` callback can also return `classifierContext`, a short note about the tool call’s result for the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) permission classifier. Because your callback runs in your application’s own process, the classifier may weigh a user statement you relay in the note as user intent. The field requires TypeScript Agent SDK v0.3.236 or later. [Annotate a result for the auto mode classifier](</docs/en/hooks#annotate-a-result-for-the-auto-mode-classifier>) covers the length cap, the synchronous-only rule, and what not to put in the note.
Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
--- a/hooks.md
+++ b/hooks.md
@@ -675,14 +675,12 @@
Forward notifications to Slack
-Use `Notification` hooks to receive system notifications from the agent and forward them to external services. Notifications fire for event types such as:
-
- * `permission_prompt` when Claude needs permission
- * `idle_prompt` when Claude is waiting for input
- * `auth_success` when authentication completes
- * `elicitation_dialog`, `elicitation_complete`, and `elicitation_response` for user-prompt elicitation flows
-
-In headless SDK sessions, only the elicitation events `elicitation_complete` and `elicitation_response` fire this hook; the other types are emitted by interactive UI that SDK sessions don’t run. Permission requests, for example, go to the `canUseTool` callback instead. Each notification includes a `message` field with a human-readable description and optionally a `title`. This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](<https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/>), which you create by adding an app to your Slack workspace and enabling incoming webhooks:
+Use `Notification` hooks to receive system notifications from the agent and forward them to external services. In SDK sessions, Claude Code runs this hook for the following notification types:
+
+ * [`permission_prompt`](</docs/en/hooks#notification>) once a permission request has waited about six seconds on your [`canUseTool` callback](</docs/en/agent-sdk/user-input>). Requires TypeScript Agent SDK v0.3.233 or later, or Python Agent SDK v0.2.139 or later
+ * `elicitation_complete` and `elicitation_response` for user-prompt elicitation flows
+
+Claude Code emits the other types, such as `idle_prompt`, `auth_success`, and `elicitation_dialog`, from interactive UI that SDK sessions don’t run. Each notification includes a `message` field with a human-readable description and optionally a `title`. This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](<https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/>), which you create by adding an app to your Slack workspace and enabling incoming webhooks:
Python
--- a/hooks.md
+++ b/hooks.md
@@ -170,7 +170,7 @@
`Setup`| No| Yes| Session setup/maintenance| Run initialization tasks
`TeammateIdle`| No| Yes| Teammate becomes idle| Reassign work or notify
`TaskCreated`| No| Yes| A task is created via the `TaskCreate` tool| Enforce task naming conventions
-`TaskCompleted`| No| Yes| Background task completes| Aggregate results from parallel tasks
+[`TaskCompleted`](</docs/en/hooks#taskcompleted>)| No| Yes| A task is marked completed| Require passing tests before a task closes
`Elicitation`| No| Yes| An MCP server requests user input mid-task| Respond to MCP input requests programmatically
`ElicitationResult`| No| Yes| A user responds to an MCP elicitation| Modify or block the response before it returns to the server
`ConfigChange`| No| Yes| Configuration file changes| Reload settings dynamically
--- a/hooks.md
+++ b/hooks.md
@@ -163,7 +163,7 @@
`PreCompact`| Yes| Yes| Conversation compaction request| Archive full transcript before summarizing
`PostCompact`| No| Yes| Conversation compaction completes| Log the generated summary
`PermissionRequest`| Yes| Yes| A tool call needs a permission decision| Custom permission handling
-`PermissionDenied`| No| Yes| The auto mode classifier denies a tool call| Log classifier denials or tell the model it may retry
+`PermissionDenied`| No| Yes| Auto mode denies a tool call, including denials without a classifier verdict| Log denials, or tell the model it may retry; Claude Code ignores `retry: true` for no-verdict denials. See [PermissionDenied](</docs/en/hooks#permissiondenied>)
`SessionStart`| No| Yes| Session initialization| Initialize logging and telemetry
`SessionEnd`| No| Yes| Session termination| Clean up temporary resources
`Notification`| Yes| Yes| Agent status messages| Send agent status updates to Slack or PagerDuty
@@ -224,15 +224,15 @@
Matchers
-Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. See the [Claude Code hooks reference](</docs/en/hooks#matcher-patterns>) for the full list of matcher values for each event type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). A matcher containing only letters, digits, `_`, `-`, spaces, `,`, and `|` is compared as an exact string, with alternatives separated by `|` or `,` and optional surrounding whitespace, so `Write|Edit` and `Write, Edit` each match exactly those two tools and `code-reviewer` matches only that agent type. A matcher of `*`, an empty string, or omitting the matcher entirely matches every occurrence of the event. A matcher containing any other character is evaluated as an unanchored regular expression, so `^mcp__` matches every MCP tool and `Edit.*` matches both `Edit` and `NotebookEdit`. Wrap a regular expression in `^` and `$` when you need a whole-string match. A matcher like `mcp__memory` or `mcp__brave-search` contains only exact-match characters, so it is compared as an exact string and matches no tool; use `mcp__memory__.*` to match every tool from that server. Hyphens in the exact-match set require a Claude Code runtime of v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression and must be anchored as `^code-reviewer$` to match exactly. `StopFailure` and `FileChanged` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives, so write `rate_limit|overloaded`, not `rate_limit, overloaded`. `FileChanged` additionally uses its matcher to build the watch list of literal filenames; see [FileChanged in the hooks reference](</docs/en/hooks#filechanged>).
+Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). That section documents the exact-string and regular-expression evaluation paths, their version requirements, and the matcher values for each event type.
Option| Type| Default| Description
---|---|---|---
-`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the comparison rules above. For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`.
+`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the [rules for matchers in settings files](</docs/en/hooks#matcher-patterns>). For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`.
`hooks`| `HookCallback[]`| -| Required. Array of callback functions to execute when the pattern matches
-`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout: 10 minutes for most events, 30 seconds for `UserPromptSubmit`. Claude Code uses shorter limits for a few events, such as 10 seconds for `MessageDisplay` and a 1.5-second default [budget](</docs/en/hooks#sessionend-input>) for `SessionEnd`. Your SDK callbacks follow the `command` hook defaults
-
-Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event. For tool-based hooks, matchers only filter by tool name, not by file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your callback.
+`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout. Your SDK callbacks follow the `command` hook defaults
+
+Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event.
**Discovering tool names:** See [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list of built-in tool names, or add a hook without a matcher to log all tool calls your session makes.**MCP tool naming:** MCP tools always start with `mcp__` followed by the server name and action: `mcp__<server>__<action>`. For example, if you configure a server named `playwright`, its tools are named `mcp__playwright__browser_screenshot`, `mcp__playwright__browser_click`, and so on. The server name comes from the key you use in the `mcpServers` configuration.
@@ -264,7 +264,7 @@
Your callback returns an object with two categories of fields:
- * **Top-level fields** work the same on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.
+ * **Top-level fields** are accepted on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. Some events discard them or deliver them elsewhere. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says where they land.
* **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. Returning `"defer"` ends the query so you can [resume it later](</docs/en/hooks#defer-a-tool-call-for-later>). For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.
Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
@@ -815,7 +815,7 @@
Hook timeout
-Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>). When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event:
+Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event:
* `PreToolUse`: Claude Code doesn’t run the tool call, Claude receives a tool result stating the hook didn’t respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
* `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.
@@ -902,7 +902,7 @@
systemMessage not appearing in output
-The `systemMessage` field shows a message to the user, not the model. By default the SDK surfaces hook output in the message stream only for `SessionStart` and `Setup` hooks, so a message from any other hook event doesn’t appear unless you set `includeHookEvents` (`include_hook_events` in Python). To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel.
+The `systemMessage` field shows a message to the user, not the model. On Claude Code v2.1.227 or later, a hook’s `systemMessage` can surface in the message stream as an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>). Whether it does depends on the event. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says how output surfaces. To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). Before v2.1.227, the SDK surfaced hook output in the message stream only for `SessionStart` and `Setup` hooks. For any other event, the output appeared only in the lifecycle events that [`includeHookEvents`](</docs/en/agent-sdk/typescript#options>) (`include_hook_events` in Python) adds. That option’s entry covers which lifecycle events each hook event produces. If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel.
##
Show diff (4225 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -1,3316 +1,918 @@
-For a quickstart guide with examples, see [Automate actions with hooks](</docs/en/hooks-guide>).
-
-Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Hooks run wherever Claude Code runs: sessions in the terminal, IDE extensions, the [Desktop app](</docs/en/desktop-quickstart>), and [Claude Code on the web](</docs/en/claude-code-on-the-web>) all fire the same hook events. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks.
+Hooks are callback functions that run your code in response to agent events, like a tool being called, a session starting, or execution stopping. With hooks, you can:
+
+ * **Block dangerous operations** before they execute, like destructive shell commands or unauthorized file access
+ * **Log and audit** every tool call for compliance, debugging, or analytics
+ * **Transform inputs and outputs** to sanitize data, inject credentials, or redirect file paths
+ * **Require human approval** for sensitive actions like database writes or API calls
+ * **Track session lifecycle** to manage state, clean up resources, or send notifications
##
-Hook lifecycle
-
-Claude Code runs hooks at specific points during a session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences:
-
- * once per session: `SessionStart` and `SessionEnd`
- * once per turn: `UserPromptSubmit`, `Stop`, and `StopFailure`
- * on every tool call inside the agentic loop: `PreToolUse` and `PostToolUse`, except [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) calls, which skip both
-
-The table below summarizes when each event fires. The Hook events section documents the full input schema and decision control options for each one.
-
-Event| When it fires
----|---
-`SessionStart`| When a session begins or resumes
-`Setup`| When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts
-`UserPromptSubmit`| When you submit a prompt, before Claude processes it
-`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
-`PreToolUse`| Before a tool call executes. Can block it
-`PermissionRequest`| When a tool call needs a permission decision
-`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
-`PostToolUse`| After a tool call succeeds
-`PostToolUseFailure`| After a tool call fails
-`PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call
-`Notification`| When Claude Code sends a notification
-`MessageDisplay`| While assistant message text is displayed
-`SubagentStart`| When a subagent is spawned
-`SubagentStop`| When a subagent finishes
-`TaskCreated`| When a task is being created via `TaskCreate`
-`TaskCompleted`| When a task is being marked as completed
-`Stop`| When Claude finishes responding
-`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored
-`TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle
-`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
-`ConfigChange`| When a configuration file changes during a session
-`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
-`DirectoryAdded`| When a working directory is added mid-session via `/add-dir` or the SDK `register_repo_root` control request
-`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
-`WorktreeCreate`| When a worktree is being created via `--worktree`, `isolation: "worktree"`, or for a background session. Replaces default git behavior
-`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session
-`PreCompact`| Before context compaction
-`PostCompact`| After context compaction completes
-`Elicitation`| When an MCP server requests user input during a tool call
-`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server
-`SessionEnd`| When a session terminates
-
-###
-
-
-
-How a hook resolves
-
-To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands.
-
- * macOS/Linux
-
- * Windows (PowerShell)
-
-The `matcher` narrows to Bash tool calls and the `if` condition narrows further to Bash subcommands matching `rm *`, so `block-rm.sh` only spawns when both filters match:
-
- {
- "hooks": {
- "PreToolUse": [
- {
- "matcher": "Bash",
- "hooks": [
- {
- "type": "command",
- "if": "Bash(rm *)",
- "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
- "args": []
- }
+How hooks work
+
+1
+
+An event fires
+
+Something happens during agent execution and the SDK fires an event: a tool is about to be called (`PreToolUse`), a tool returned a result (`PostToolUse`), a subagent started or stopped, the agent is idle, or execution finished. See the full list of events.
+
+2
+
+The SDK collects registered hooks
+
+The SDK checks for hooks registered for that event type. This includes callback hooks you pass in `options.hooks` and shell command hooks from settings files when the corresponding [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>) or [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) entry is enabled, which it is for default `query()` options.
+
+3
+
+Matchers filter which hooks run
+
+If a hook has a `matcher` pattern (like `"Write|Edit"`), the SDK tests it against the event’s target (for example, the tool name). Hooks without a matcher run for every event of that type.
+
+4
+
+Callback functions execute
+
+Each matching hook’s callback function receives input about what’s happening: the tool name, its arguments, the session ID, and other event-specific details.
+
+5
+
+Your callback returns a decision
+
+After performing any operations (logging, API calls, validation), your callback returns an output object that tells the agent what to do: allow the operation, block it, modify the input, or inject context into the conversation.
+
+The following example puts these steps together. It registers a `PreToolUse` hook (step 1) with a `"Write|Edit"` matcher (step 3) so the callback only fires for file-writing tools. When triggered, the callback receives the tool’s input (step 4), checks if the file path targets a `.env` file, and returns `permissionDecision: "deny"` to block the operation (step 5):
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import (
+ AssistantMessage,
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ HookMatcher,
+ ResultMessage,
+ )
+
+ # Define a hook callback that receives tool call details
+ async def protect_env_files(input_data, tool_use_id, context):
+ # Extract the file path from the tool's input arguments
+ file_path = input_data["tool_input"].get("file_path", "")
+ file_name = file_path.split("/")[-1]
+
+ # Block the operation if targeting a .env file
+ if file_name == ".env":
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": input_data["hook_event_name"],
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Cannot modify .env files",
+ }
+ }
+
+ # Return empty object to allow the operation
+ return {}
+
+ async def main():
+ options = ClaudeAgentOptions(
+ hooks={
+ # Register the hook for PreToolUse events
+ # The matcher filters to only Write and Edit tool calls
+ "PreToolUse": [HookMatcher(matcher="Write|Edit", hooks=[protect_env_files])]
+ }
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query("Create a .env file with the standard local development database configuration")
+ async for message in client.receive_response():
+ # Filter for assistant and result messages
+ if isinstance(message, (AssistantMessage, ResultMessage)):
+ print(message)
+
+ asyncio.run(main())
+
+ import { query, HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define a hook callback with the HookCallback type
+ const protectEnvFiles: HookCallback = async (input, toolUseID, { signal }) => {
+ // Cast input to the specific hook type for type safety
+ const preInput = input as PreToolUseHookInput;
+
+ // Cast tool_input to access its properties (typed as unknown in the SDK)
+ const toolInput = preInput.tool_input as Record<string, unknown>;
+ const filePath = toolInput?.file_path as string;
+ const fileName = filePath?.split("/").pop();
+
+ // Block the operation if targeting a .env file
+ if (fileName === ".env") {
+ return {
+ hookSpecificOutput: {
+ hookEventName: preInput.hook_event_name,
+ permissionDecision: "deny",
+ permissionDecisionReason: "Cannot modify .env files"
+ }
+ };
+ }
+
+ // Return empty object to allow the operation
+ return {};
+ };
+
+ for await (const message of query({
+ prompt: "Create a .env file with the standard local development database configuration",
+ options: {
+ hooks: {
+ // Register the hook for PreToolUse events
+ // The matcher filters to only Write and Edit tool calls
+ PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnvFiles] }]
+ }
+ }
+ })) {
+ // Filter for assistant and result messages
+ if (message.type === "assistant" || message.type === "result") {
+ console.log(message);
+ }
+ }
+
+When you run either script, Claude attempts to create the `.env` file, the hook denies the tool call, and Claude’s final response explains that it can’t create `.env` files.
+
+##
+
+
+
+Available hooks
+
+The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only.
+
+Hook Event| Python SDK| TypeScript SDK| What triggers it| Example use case
+---|---|---|---|---
+`PreToolUse`| Yes| Yes| Tool call request (can block or modify)| Block dangerous shell commands
+`PostToolUse`| Yes| Yes| Tool execution result| Log all file changes to audit trail
+`PostToolUseFailure`| Yes| Yes| Tool execution failure| Handle or log tool errors
+`PostToolBatch`| No| Yes| A full batch of tool calls resolves, once per batch before the next model call| Inject conventions once for the whole batch
+`UserPromptSubmit`| Yes| Yes| User prompt submission| Inject additional context into prompts
+[`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>)| No| Yes| A user-typed command, or an MCP prompt, expands into a prompt before it reaches Claude. Doesn’t fire when Claude invokes a skill itself| Block a command from direct invocation or add context when a skill is typed
+`MessageDisplay`| No| Yes| An assistant message with text completes, once per message with the full message text| Redact or reformat the displayed text without changing the transcript
+`Stop`| Yes| Yes| Agent execution stop| Save session state before exit
+`StopFailure`| No| Yes| The turn ends with an API error instead of a normal stop| Log failures or send alerts
+`SubagentStart`| Yes| Yes| Subagent initialization| Track parallel task spawning
+`SubagentStop`| Yes| Yes| Subagent completion| Aggregate results from parallel tasks
+`PreCompact`| Yes| Yes| Conversation compaction request| Archive full transcript before summarizing
+`PostCompact`| No| Yes| Conversation compaction completes| Log the generated summary
+`PermissionRequest`| Yes| Yes| A tool call needs a permission decision| Custom permission handling
+`PermissionDenied`| No| Yes| The auto mode classifier denies a tool call| Log classifier denials or tell the model it may retry
+`SessionStart`| No| Yes| Session initialization| Initialize logging and telemetry
+`SessionEnd`| No| Yes| Session termination| Clean up temporary resources
+`Notification`| Yes| Yes| Agent status messages| Send agent status updates to Slack or PagerDuty
+`Setup`| No| Yes| Session setup/maintenance| Run initialization tasks
+`TeammateIdle`| No| Yes| Teammate becomes idle| Reassign work or notify
+`TaskCreated`| No| Yes| A task is created via the `TaskCreate` tool| Enforce task naming conventions
+`TaskCompleted`| No| Yes| Background task completes| Aggregate results from parallel tasks
+`Elicitation`| No| Yes| An MCP server requests user input mid-task| Respond to MCP input requests programmatically
+`ElicitationResult`| No| Yes| A user responds to an MCP elicitation| Modify or block the response before it returns to the server
+`ConfigChange`| No| Yes| Configuration file changes| Reload settings dynamically
+`InstructionsLoaded`| No| Yes| A `CLAUDE.md` or rules file is loaded into context| Audit which instruction files load
+`WorktreeCreate`| No| Yes| Git worktree created| Track isolated workspaces
+`WorktreeRemove`| No| Yes| Git worktree removed| Clean up workspace resources
+`CwdChanged`| No| Yes| The working directory changes during a session| Reload environment variables per directory
+`FileChanged`| No| Yes| A watched file is modified, created, or deleted| Reload configuration when project files change
+`DirectoryAdded`| No| Yes| A working directory is added during a session| Install dependencies for a repository added mid-session
+
+##
+
+
+
+Configure hooks
+
+To configure a hook, pass it in the `hooks` field of your agent options (`ClaudeAgentOptions` in Python, the `options` object in TypeScript). This snippet assumes you have already defined a hook callback, like `protect_env_files` in Python or `protectEnvFiles` in TypeScript from the example above:
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[my_callback])]}
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query("Your prompt")
+ async for message in client.receive_response():
+ print(message)
+
+ for await (const message of query({
+ prompt: "Your prompt",
+ options: {
+ hooks: {
+ PreToolUse: [{ matcher: "Bash", hooks: [myCallback] }]
+ }
+ }
+ })) {
+ console.log(message);
+ }
+
+The `hooks` option is a dictionary in Python or an object in TypeScript, where:
+
+ * **Keys** : hook event names such as `'PreToolUse'`, `'PostToolUse'`, and `'Stop'`
+ * **Values** : arrays of matchers, each containing an optional filter pattern and your callback functions
+
+###
+
+
+
+Matchers
+
+Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. See the [Claude Code hooks reference](</docs/en/hooks#matcher-patterns>) for the full list of matcher values for each event type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). A matcher containing only letters, digits, `_`, `-`, spaces, `,`, and `|` is compared as an exact string, with alternatives separated by `|` or `,` and optional surrounding whitespace, so `Write|Edit` and `Write, Edit` each match exactly those two tools and `code-reviewer` matches only that agent type. A matcher of `*`, an empty string, or omitting the matcher entirely matches every occurrence of the event. A matcher containing any other character is evaluated as an unanchored regular expression, so `^mcp__` matches every MCP tool and `Edit.*` matches both `Edit` and `NotebookEdit`. Wrap a regular expression in `^` and `$` when you need a whole-string match. A matcher like `mcp__memory` or `mcp__brave-search` contains only exact-match characters, so it is compared as an exact string and matches no tool; use `mcp__memory__.*` to match every tool from that server. Hyphens in the exact-match set require a Claude Code runtime of v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression and must be anchored as `^code-reviewer$` to match exactly. `StopFailure` and `FileChanged` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives, so write `rate_limit|overloaded`, not `rate_limit, overloaded`. `FileChanged` additionally uses its matcher to build the watch list of literal filenames; see [FileChanged in the hooks reference](</docs/en/hooks#filechanged>).
+
+Option| Type| Default| Description
+---|---|---|---
+`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the comparison rules above. For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`.
+`hooks`| `HookCallback[]`| -| Required. Array of callback functions to execute when the pattern matches
+`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout: 10 minutes for most events, 30 seconds for `UserPromptSubmit`. Claude Code uses shorter limits for a few events, such as 10 seconds for `MessageDisplay` and a 1.5-second default [budget](</docs/en/hooks#sessionend-input>) for `SessionEnd`. Your SDK callbacks follow the `command` hook defaults
+
+Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event. For tool-based hooks, matchers only filter by tool name, not by file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your callback.
+
+**Discovering tool names:** See [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list of built-in tool names, or add a hook without a matcher to log all tool calls your session makes.**MCP tool naming:** MCP tools always start with `mcp__` followed by the server name and action: `mcp__<server>__<action>`. For example, if you configure a server named `playwright`, its tools are named `mcp__playwright__browser_screenshot`, `mcp__playwright__browser_click`, and so on. The server name comes from the key you use in the `mcpServers` configuration.
+
+###
+
+
+
+Callback functions
+
+####
+
+
+
+Inputs
+
+Every hook callback receives three arguments:
+
+ * **Input data:** a typed object containing event details. Each hook type has its own input shape. For example, `PreToolUseHookInput` includes `tool_name` and `tool_input`, while `NotificationHookInput` includes `message`. See the full type definitions in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references.
+ * All hook inputs share `session_id`, `cwd`, and `hook_event_name`.
+ * `agent_id` and `agent_type` are populated when the hook fires inside a subagent. In TypeScript, these are on the base hook input and available to all hook types. In Python, they are optional fields on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`, and required fields on `SubagentStart` and `SubagentStop`.
+ * **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call.
+ * **Context:** in TypeScript, contains a `signal` property (`AbortSignal`) for cancellation. In Python, this argument is reserved for future use.
+
+####
+
+
+
+Outputs
+
+Your callback returns an object with two categories of fields:
+
+ * **Top-level fields** work the same on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.
+ * **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. Returning `"defer"` ends the query so you can [resume it later](</docs/en/hooks#defer-a-tool-call-for-later>). For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.
+
+Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references.
+
+When multiple hooks or permission rules apply, `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`. If any hook returns `deny`, the operation is blocked regardless of other hooks.
+
+####
+
+
+
+Asynchronous output
+
+By default, the agent waits for your hook to return before proceeding. If your hook performs a side effect, such as logging or sending a webhook, and doesn’t need to influence the agent’s behavior, you can return an async output instead. This tells the agent to continue immediately without waiting for the hook to finish. In this snippet, `send_to_logging_service` in Python and `sendToLoggingService` in TypeScript stand in for any logging function you define:
+
+Python
+
+TypeScript
+
+ async def async_hook(input_data, tool_use_id, context):
+ # Start a background task, then return immediately
+ asyncio.create_task(send_to_logging_service(input_data))
+ return {"async_": True, "asyncTimeout": 30000}
+
+ const asyncHook: HookCallback = async (input, toolUseID, { signal }) => {
+ // Start a background task, then return immediately
+ sendToLoggingService(input).catch(console.error);
+ return { async: true, asyncTimeout: 30000 };
+ };
+
+Field| Type| Description
+---|---|---
+`async`| `true`| Signals async mode. The agent proceeds without waiting. In Python, use `async_` to avoid the reserved keyword.
+`asyncTimeout`| `number`| Optional timeout in milliseconds for the background operation
+
+Async outputs can’t block, modify, or inject context into the operation since the agent has already moved on. Use them only for side effects like logging, metrics, or notifications.
+
+##
+
+
+
+Examples
+
+Several examples in this section show only the callback function. To run one, register the callback under the matching event in the `hooks` field of your options, as shown in Configure hooks.
+
+###
+
+
+
+Modify tool input
+
+This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`, redirecting all file writes to a sandboxed directory. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation:
+
+Python
+
+TypeScript
+
+ async def redirect_to_sandbox(input_data, tool_use_id, context):
+ if input_data["hook_event_name"] != "PreToolUse":
+ return {}
+
+ if input_data["tool_name"] == "Write":
+ original_path = input_data["tool_input"].get("file_path", "")
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": input_data["hook_event_name"],
+ "permissionDecision": "allow",
+ "updatedInput": {
+ **input_data["tool_input"],
+ "file_path": f"/sandbox{original_path}",
+ },
+ }
+ }
+ return {}
+
+ const redirectToSandbox: HookCallback = async (input, toolUseID, { signal }) => {
+ if (input.hook_event_name !== "PreToolUse") return {};
+
+ const preInput = input as PreToolUseHookInput;
+ const toolInput = preInput.tool_input as Record<string, unknown>;
+ if (preInput.tool_name === "Write") {
+ const originalPath = toolInput.file_path as string;
+ return {
+ hookSpecificOutput: {
+ hookEventName: preInput.hook_event_name,
+ permissionDecision: "allow",
+ updatedInput: {
+ ...toolInput,
+ file_path: `/sandbox${originalPath}`
+ }
+ }
+ };
+ }
+ return {};
+ };
+
+Pair `updatedInput` with `permissionDecision: 'allow'` to auto-approve the modified input, or `permissionDecision: 'ask'` to show it to the user. If you omit `permissionDecision`, the modified input still applies and flows through the normal permission evaluation. With `'defer'`, `updatedInput` is ignored. Always return a new object rather than mutating the original `tool_input`.
+
+To confirm the redirect, set the prefix to a path you can write to, such as `./sandbox` or `/tmp/sandbox` (macOS doesn’t allow creating a root-level `/sandbox` directory), then ask the agent to write a file: the Write tool’s result in the message stream names the path with your sandbox prefix rather than the one Claude requested.
+
+###
+
+
+
+Add context and block a tool
+
+This example blocks writes to the `/etc` directory and explains why to both the model and the user:
+
+ * `permissionDecision: 'deny'` stops the tool call.
+ * `permissionDecisionReason` tells the model why, so it avoids retrying.
+ * `systemMessage` shows the user what happened.
+
+Python
+
+TypeScript
+
+ async def block_etc_writes(input_data, tool_use_id, context):
+ file_path = input_data["tool_input"].get("file_path", "")
+
+ if file_path.startswith("/etc"):
+ return {
+ # Top-level field: message shown to the user
+ "systemMessage": "Remember: system directories like /etc are protected.",
+ # hookSpecificOutput: block the operation
+ "hookSpecificOutput": {
+ "hookEventName": input_data["hook_event_name"],
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Writing to /etc is not allowed",
+ },
+ }
+ return {}
+
+ const blockEtcWrites: HookCallback = async (input, toolUseID, { signal }) => {
+ const preInput = input as PreToolUseHookInput;
+ const toolInput = preInput.tool_input as Record<string, unknown>;
+ const filePath = toolInput?.file_path as string;
+
+ if (filePath?.startsWith("/etc")) {
+ return {
+ // Top-level field: message shown to the user
+ systemMessage: "Remember: system directories like /etc are protected.",
+ // hookSpecificOutput: block the operation
+ hookSpecificOutput: {
+ hookEventName: preInput.hook_event_name,
+ permissionDecision: "deny",
+ permissionDecisionReason: "Writing to /etc is not allowed"
+ }
+ };
+ }
+ return {};
+ };
+
+###
+
+
+
+Auto-approve specific tools
+
+By default, the agent may prompt for permission before using certain tools. This example auto-approves read-only filesystem tools (Read, Glob, Grep) by returning `permissionDecision: 'allow'`, letting them run without user confirmation while leaving all other tools subject to normal permission checks:
+
+Python
+
+TypeScript
+
+ async def auto_approve_read_only(input_data, tool_use_id, context):
+ if input_data["hook_event_name"] != "PreToolUse":
+ return {}
+
+ read_only_tools = ["Read", "Glob", "Grep"]
+ if input_data["tool_name"] in read_only_tools:
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": input_data["hook_event_name"],
+ "permissionDecision": "allow",
+ "permissionDecisionReason": "Read-only tool auto-approved",
+ }
+ }
+ return {}
+
+ const autoApproveReadOnly: HookCallback = async (input, toolUseID, { signal }) => {
+ if (input.hook_event_name !== "PreToolUse") return {};
+
+ const preInput = input as PreToolUseHookInput;
+ const readOnlyTools = ["Read", "Glob", "Grep"];
+ if (readOnlyTools.includes(preInput.tool_name)) {
+ return {
+ hookSpecificOutput: {
+ hookEventName: preInput.hook_event_name,
+ permissionDecision: "allow",
+ permissionDecisionReason: "Read-only tool auto-approved"
+ }
+ };
+ }
+ return {};
+ };
+
+###
+
+
+
+Register multiple hooks
+
+When an event fires, all matching hooks run in parallel. For permission decisions, the most restrictive result applies: a single `deny` blocks the tool call regardless of what the other hooks return. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks for every tool call:
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ hooks={
+ "PreToolUse": [
+ HookMatcher(hooks=[authorization_check]),
+ HookMatcher(hooks=[input_validator]),
+ HookMatcher(hooks=[audit_logger]),
]
+ }
+ )
+
+ const options = {
+ hooks: {
+ PreToolUse: [
+ { hooks: [authorizationCheck] },
+ { hooks: [inputValidator] },
+ { hooks: [auditLogger] }
+ ]
+ }
+ };
+
+###
+
+
+
+Filter with multi-tool matchers
+
+Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes:
+
+ * A pipe-separated exact list (`Write|Edit|NotebookEdit`) triggers `file_security_hook` only for file modification tools.
+ * A regex (`^mcp__`) triggers `mcp_audit_hook` for any MCP tool whose name starts with `mcp__`.
+ * An omitted matcher triggers `global_logger` for every tool call regardless of name.
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ hooks={
+ "PreToolUse": [
+ # Match file modification tools
+ HookMatcher(matcher="Write|Edit|NotebookEdit", hooks=[file_security_hook]),
+ # Match all MCP tools
+ HookMatcher(matcher="^mcp__", hooks=[mcp_audit_hook]),
+ # Match everything (no matcher)
+ HookMatcher(hooks=[global_logger]),
+ ]
+ }
+ )
+
+ const options = {
+ hooks: {
+ PreToolUse: [
+ // Match file modification tools
+ { matcher: "Write|Edit|NotebookEdit", hooks: [fileSecurityHook] },
+
+ // Match all MCP tools
+ { matcher: "^mcp__", hooks: [mcpAuditHook] },
+
+ // Match everything (no matcher)
+ { hooks: [globalLogger] }
+ ]
+ }
+ };
+
+###
+
+
+
+Track subagent activity
+
+Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references. This example logs a summary each time a subagent completes:
+
+Python
+
+TypeScript
+
+ async def subagent_tracker(input_data, tool_use_id, context):
+ # Log subagent details when it finishes
+ print(f"[SUBAGENT] Completed: {input_data['agent_id']}")
+ print(f" Transcript: {input_data['agent_transcript_path']}")
+ print(f" Tool use ID: {tool_use_id}")
+ print(f" Stop hook active: {input_data.get('stop_hook_active')}")
+ return {}
+
+ options = ClaudeAgentOptions(
+ hooks={"SubagentStop": [HookMatcher(hooks=[subagent_tracker])]}
+ )
+
+ import { HookCallback, SubagentStopHookInput } from "@anthropic-ai/claude-agent-sdk";
+
+ const subagentTracker: HookCallback = async (input, toolUseID, { signal }) => {
+ // Cast to SubagentStopHookInput to access subagent-specific fields
+ const subInput = input as SubagentStopHookInput;
+
+ // Log subagent details when it finishes
+ console.log(`[SUBAGENT] Completed: ${subInput.agent_id}`);
+ console.log(` Transcript: ${subInput.agent_transcript_path}`);
+ console.log(` Tool use ID: ${toolUseID}`);
+ console.log(` Stop hook active: ${subInput.stop_hook_active}`);
+ return {};
+ };
+
+ const options = {
+ hooks: {
+ SubagentStop: [{ hooks: [subagentTracker] }]
+ }
+ };
+
+###
+
+
+
+Make HTTP requests from hooks
+
+Hooks can perform asynchronous operations like HTTP requests. Catch errors inside your hook instead of letting them propagate, since an unhandled exception can interrupt the agent. This example sends a webhook after each tool completes, logging which tool ran and when. The hook catches errors so a failed webhook doesn’t interrupt the agent:
+
+Python
+
+TypeScript
+
+ import asyncio
+ import json
+ import urllib.request
+ from datetime import datetime
+
+ def _send_webhook(tool_name):
+ """Synchronous helper that POSTs tool usage data to an external webhook."""
+ data = json.dumps(
+ {
+ "tool": tool_name,
+ "timestamp": datetime.now().isoformat(),
+ }
+ ).encode()
+ req = urllib.request.Request(
+ "https://api.example.com/webhook",
+ data=data,
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ urllib.request.urlopen(req)
+
+ async def webhook_notifier(input_data, tool_use_id, context):
+ # Only fire after a tool completes (PostToolUse), not before
+ if input_data["hook_event_name"] != "PostToolUse":
+ return {}
+
+ try:
+ # Run the blocking HTTP call in a thread to avoid blocking the event loop
+ await asyncio.to_thread(_send_webhook, input_data["tool_name"])
+ except Exception as e:
+ # Log the error but don't raise. A failed webhook shouldn't stop the agent
+ print(f"Webhook request failed: {e}")
+
+ return {}
+
+ import { query, HookCallback, PostToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";
+
+ const webhookNotifier: HookCallback = async (input, toolUseID, { signal }) => {
+ // Only fire after a tool completes (PostToolUse), not before
+ if (input.hook_event_name !== "PostToolUse") return {};
+
+ try {
+ await fetch("https://api.example.com/webhook", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ tool: (input as PostToolUseHookInput).tool_name,
+ timestamp: new Date().toISOString()
+ }),
+ // Pass signal so the request cancels if the hook times out
+ signal
+ });
+ } catch (error) {
+ // Handle cancellation separately from other errors
+ if (error instanceof Error && error.name === "AbortError") {
+ console.log("Webhook request cancelled");
+ }
+ // Don't re-throw. A failed webhook shouldn't stop the agent
+ }
+
+ return {};
+ };
+
+ // Register as a PostToolUse hook
+ for await (const message of query({
+ prompt: "Refactor the auth module",
+ options: {
+ hooks: {
+ PostToolUse: [{ hooks: [webhookNotifier] }]
+ }
+ }
+ })) {
+ console.log(message);
+ }
+
+To confirm the hook fires, point the webhook URL at an endpoint you can watch and send a prompt that uses a tool: the hook sends a POST with the tool name and timestamp after each tool completes.
+
+###
+
+
+
+Forward notifications to Slack
+
+Use `Notification` hooks to receive system notifications from the agent and forward them to external services. Notifications fire for event types such as:
+
+ * `permission_prompt` when Claude needs permission
+ * `idle_prompt` when Claude is waiting for input
+ * `auth_success` when authentication completes
+ * `elicitation_dialog`, `elicitation_complete`, and `elicitation_response` for user-prompt elicitation flows
+
+In headless SDK sessions, only the elicitation events `elicitation_complete` and `elicitation_response` fire this hook; the other types are emitted by interactive UI that SDK sessions don’t run. Permission requests, for example, go to the `canUseTool` callback instead. Each notification includes a `message` field with a human-readable description and optionally a `title`. This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](<https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/>), which you create by adding an app to your Slack workspace and enabling incoming webhooks:
+
+Python
+
+TypeScript
+
+ import asyncio
+ import json
+ import urllib.request
+
+ from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, HookMatcher
+
+ def _send_slack_notification(message):
+ """Synchronous helper that sends a message to Slack via incoming webhook."""
+ data = json.dumps({"text": f"Agent status: {message}"}).encode()
+ req = urllib.request.Request(
+ "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
+ data=data,
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ urllib.request.urlopen(req)
+
+ async def notification_handler(input_data, tool_use_id, context):
+ try:
+ # Run the blocking HTTP call in a thread to avoid blocking the event loop
+ await asyncio.to_thread(_send_slack_notification, input_data.get("message", ""))
+ except Exception as e:
+ print(f"Failed to send notification: {e}")
+
+ # Return empty object. Notification hooks don't modify agent behavior
+ return {}
+
+ async def main():
+ options = ClaudeAgentOptions(
+ hooks={
+ # Register the hook for Notification events (no matcher needed)
+ "Notification": [HookMatcher(hooks=[notification_handler])],
+ },
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query("Analyze this codebase")
+ async for message in client.receive_response():
+ print(message)
+
+ asyncio.run(main())
+
+ import { query, HookCallback, NotificationHookInput } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define a hook callback that sends notifications to Slack
+ const notificationHandler: HookCallback = async (input, toolUseID, { signal }) => {
+ // Cast to NotificationHookInput to access the message field
+ const notification = input as NotificationHookInput;
+
+ try {
+ // POST the notification message to a Slack incoming webhook
+ await fetch("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ text: `Agent status: ${notification.message}`
+ }),
+ // Pass signal so the request cancels if the hook times out
+ signal
+ });
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ console.log("Notification cancelled");
+ } else {
+ console.error("Failed to send notification:", error);
+ }
+ }
+
+ // Return empty object. Notification hooks don't modify agent behavior
+ return {};
+ };
+
+ // Register the hook for Notification events (no matcher needed)
+ for await (const message of query({
+ prompt: "Analyze this codebase",
+ options: {
+ hooks: {
+ Notification: [{ hooks: [notificationHandler] }]
+ }
+ }
+ })) {
+ console.log(message);
+ }
+
+When a `Notification` event fires, the hook posts the notification’s `message`, prefixed with `Agent status:`, to the channel your webhook targets.
+
+##
+
+
+
+Fix common issues
+
+###
+
+
+
+Hook not firing
+
+ * Verify the hook event name is correct and case-sensitive (`PreToolUse`, not `preToolUse`)
+ * Check that your matcher pattern matches the tool name exactly
+ * Ensure the hook is under the correct event type in `options.hooks`
+ * For non-tool hooks that support matchers, like `Notification` and `SubagentStop`, matchers match against different fields, and `Stop` ignores matchers entirely (see [matcher patterns](</docs/en/hooks#matcher-patterns>))
+ * Hooks may not fire when the agent hits the [`max_turns`](</docs/en/agent-sdk/python#claudeagentoptions>) limit because the session ends before hooks can execute
+
+###
+
+
+
+Matcher not filtering as expected
+
+Matchers only match tool names, not file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your hook:
+
+ const myHook: HookCallback = async (input, toolUseID, { signal }) => {
+ const preInput = input as PreToolUseHookInput;
+ const toolInput = preInput.tool_input as Record<string, unknown>;
+ const filePath = toolInput?.file_path as string;
+ if (!filePath?.endsWith(".md")) return {}; // Skip non-markdown files
+ // Process markdown files...
+ return {};
+ };
+
+###
+
+
+
+Hook timeout
+
+Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>). When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event:
+
+ * `PreToolUse`: Claude Code doesn’t run the tool call, Claude receives a tool result stating the hook didn’t respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.
+ * `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.
+ * `UserPromptSubmit` and [`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>): Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Because a callback on these events can act as a policy gate, Claude Code never lets a timed-out prompt through unscreened. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out.
+ * `Stop` and `SubagentStop`: Claude Code shows a warning and the agent stops normally.
+ * Other events, such as `Notification` and `PreCompact`: Claude Code logs the failure and continues.
+
+If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.
+
+###
+
+
+
+Tool blocked unexpectedly
+
+ * Check all `PreToolUse` hooks for `permissionDecision: 'deny'` returns
+ * Add logging to your hooks to see what `permissionDecisionReason` they’re returning
+ * Verify matcher patterns aren’t too broad: an empty matcher matches all tools
+
+###
+
+
+
+Modified input not applied
+
+ * Ensure `updatedInput` is inside `hookSpecificOutput`, not at the top level:
+
+ return {
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ permissionDecision: "allow",
+ updatedInput: { command: "new command" }
}
- ]
- }
- }
-
-The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`. Save it to `.claude/hooks/block-rm.sh` in your project and make it executable with `chmod +x .claude/hooks/block-rm.sh` so Claude Code can run it:
-
- #!/bin/bash
- # .claude/hooks/block-rm.sh
- COMMAND=$(jq -r '.tool_input.command')
-
- if echo "$COMMAND" | grep -q 'rm -rf'; then
- jq -n '{
- hookSpecificOutput: {
- hookEventName: "PreToolUse",
- permissionDecision: "deny",
- permissionDecisionReason: "Destructive command blocked by hook"
- }
- }'
- else
- exit 0 # no decision; normal permission flow applies
- fi
-
-This script, like the other Bash examples on this page that parse JSON input, uses `jq`, so install `jq` and make sure it is on your `PATH` before trying them.
-
-The matcher `Bash|PowerShell` covers the PowerShell tool as well as Bash. A single `if` rule matches only one tool’s calls, so each tool gets its own handler: the first narrows to Bash subcommands matching `rm *`, the second to PowerShell commands matching `Remove-Item *`. Both run the same script through `powershell.exe`:
-
- {
- "hooks": {
- "PreToolUse": [
- {
- "matcher": "Bash|PowerShell",
- "hooks": [
- {
- "type": "command",
- "if": "Bash(rm *)",
- "command": "powershell.exe",
- "args": [
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"
- ]
- },
- {
- "type": "command",
- "if": "PowerShell(Remove-Item *)",
- "command": "powershell.exe",
- "args": [
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"
- ]
- }
- ]
- }
- ]
- }
- }
-
-The `-NoProfile` flag skips loading your PowerShell profile so the hook starts fast, and `-ExecutionPolicy Bypass` lets PowerShell run the local script file.The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf` or `Remove-Item` followed by `-Recurse`. Save it to `.claude/hooks/block-rm.ps1` in your project:
-
- # .claude/hooks/block-rm.ps1
- $callInput = [Console]::In.ReadToEnd() | ConvertFrom-Json
- $command = $callInput.tool_input.command
-
- if ($command -match 'rm -rf|Remove-Item.*-Recurse') {
- @{
- hookSpecificOutput = @{
- hookEventName = "PreToolUse"
- permissionDecision = "deny"
- permissionDecisionReason = "Destructive command blocked by hook"
- }
- } | ConvertTo-Json
- } else {
- exit 0 # no decision; normal permission flow applies
- }
-
-Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"` against the macOS/Linux config. Here’s what happens:
-
-1
-
-Event fires
-
-The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
-
- { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
-
-2
-
-Matcher checks
-
-The matcher `"Bash"` matches the tool name, so this hook group activates. If you omit the matcher or use `"*"`, the group activates on every occurrence of the event.
-
-3
-
-If condition checks
-
-The `if` condition `"Bash(rm *)"` matches because `rm -rf /tmp/build` is a subcommand matching `rm *`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs.
-
-4
-
-Hook handler runs
-
-The script inspects the full command and finds `rm -rf`, so it prints a decision to stdout:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PreToolUse",
- "permissionDecision": "deny",
- "permissionDecisionReason": "Destructive command blocked by hook"
- }
- }
-
-If the command had been a safer `rm` variant like `rm file.txt`, the script would hit `exit 0` instead. Exit code 0 with no output means the hook has no decision to report, so the tool call continues through the normal [permission flow](</docs/en/permissions>). The hook can deny the call, but staying silent doesn’t approve it.
-
-5
-
-Claude Code acts on the result
-
-Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.
-
-The Configuration section below documents the full schema, and each hook event section documents what input your command receives and what output it can return.
+ };
+
+ * Don’t pair `updatedInput` with `permissionDecision: 'defer'`, which drops the modified input. Omitting `permissionDecision` is fine: the modified input still applies through the normal permission evaluation. You can also return `'allow'` to auto-approve the modified input or `'ask'` to show it to the user for approval
+ * Include `hookEventName` in `hookSpecificOutput` to identify which hook type the output is for
+
+###
+
+
+
+Session hooks not available in Python
+
+`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren’t available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](</docs/en/hooks#hook-events>) defined in settings files such as `.claude/settings.json`. To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) or [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>):
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ setting_sources=["project"], # Loads .claude/settings.json including hooks
+ )
+
+ const options = {
+ settingSources: ["project"] // Loads .claude/settings.json including hooks
+ };
+
+To run initialization logic as a Python SDK callback instead, use the first message from `client.receive_response()` as your trigger.
+
+###
+
+
+
+Subagent permission prompts multiplying
+
+When spawning multiple subagents, each one may request permissions separately for its own tool calls. To avoid repeated prompts, use `PreToolUse` hooks to auto-approve specific tools, or configure permission rules, which subagents [inherit from the parent conversation](</docs/en/sub-agents#permission-modes>).
+
+###
+
+
+
+Recursive hook loops with subagents
+
+A `UserPromptSubmit` hook that spawns subagents can create infinite loops if those subagents trigger the same hook. To prevent this:
+
+ * Check for a subagent indicator in the hook input before spawning
+ * Use a shared variable or session state to track whether you’re already inside a subagent
+ * Scope hooks to only run for the top-level agent session
+
+###
+
+
+
+systemMessage not appearing in output
+
+The `systemMessage` field shows a message to the user, not the model. By default the SDK surfaces hook output in the message stream only for `SessionStart` and `Setup` hooks, so a message from any other hook event doesn’t appear unless you set `includeHookEvents` (`include_hook_events` in Python). To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel.
##
-Configuration
-
-Hooks are defined in JSON settings files. The configuration has three levels of nesting:
-
- 1. Choose a hook event to respond to, like `PreToolUse` or `Stop`
- 2. Add a matcher group to filter when it fires, like “only for the Bash tool”
- 3. Define one or more hook handlers to run when matched
-
-See How a hook resolves above for a complete walkthrough with an annotated example.
-
-This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, MCP tool, prompt, or agent that runs. “Hook” on its own refers to the general feature.
-
-###
-
-
-
-Hook locations
-
-Where you define a hook determines its scope:
-
-Location| Scope| Shareable
----|---|---
-`~/.claude/settings.json`| All your projects| No, local to your machine
-`.claude/settings.json`| Single project| Yes, can be committed to the repo
-`.claude/settings.local.json`| Single project| No, gitignored when Claude Code saves a setting to it
-Managed policy settings| Organization-wide| Yes, admin-controlled
-[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
-[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
-
-Cloud sessions on [Claude Code on the web](</docs/en/claude-code-on-the-web>) don’t read your local `~/.claude/settings.json`; hooks there come from the repo and from your organization’s server-managed settings. See [what carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) for which files reach a cloud session. For details on settings file resolution, see [settings](</docs/en/settings>). Hooks from settings files, managed policy settings, and plugins also run inside [subagents](</docs/en/sub-agents>). When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type` common input fields that identify the subagent. Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt. See [Hook configuration](</docs/en/settings#hook-configuration>). Hook entries merge across settings levels rather than replacing each other: user, project, and local settings add their own hooks without removing managed ones, and the `disableAllHooks` setting can’t disable managed hooks from outside managed settings. The [HTTP hook allowlists](</docs/en/settings#hook-configuration>) apply to hooks from every source, including managed policy settings:
-
- * `allowedHttpHookUrls`: when defined at any settings level, Claude Code runs an HTTP hook handler only if its URL matches the merged allowlist
- * `httpHookAllowedEnvVars`: when defined, Claude Code interpolates only the environment variables on that list into hook headers
-
-###
-
-
-
-Matcher patterns
-
-The `matcher` field filters when hooks fire. How a matcher is evaluated depends on the characters it contains:
-
-Matcher value| Evaluated as| Example
----|---|---
-`"*"`, `""`, or omitted| Match all| fires on every occurrence of the event
-Only letters, digits, `_`, `-`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly; `code-reviewer` matches only that agent type
-Contains any other character| JavaScript regular expression, unanchored| `^Notebook` matches any tool whose name starts with `Notebook`; `mcp__memory__.*` matches every tool from the `memory` server
-
-A matcher on the regular-expression path is tested with JavaScript’s `RegExp.prototype.test`, which succeeds on a match anywhere in the value. `Edit.*` matches both `Edit` and `NotebookEdit`; wrap the pattern in `^` and `$`, as in `^Edit$`, when you need a whole-string match. Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression, so it also fires for `senior-code-reviewer`; anchor it as `^code-reviewer$` on those versions to match only that name. `FileChanged` and `StopFailure` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives. Every other event with matcher support in the table that follows accepts `|` or `,`. The `FileChanged` event doesn’t follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
-
-Event| What the matcher filters| Example matcher values
----|---|---
-`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
-`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
-`Setup`| which CLI flag triggered setup| `init`, `maintenance`
-`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
-`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, custom agent names, or plugin-scoped names like `^my-plugin:reviewer$`
-`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
-`SubagentStop`| agent type| same values as `SubagentStart`
-`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
-`CwdChanged`| no matcher support| always fires on every directory change
-`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root`
-`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env`
-`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
-`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
-`UserPromptExpansion`| command name| your skill or command names
-`Elicitation`| MCP server name| your configured MCP server names
-`ElicitationResult`| MCP server name| same values as `Elicitation`
-`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `MessageDisplay`| no matcher support| always fires on every occurrence
-
-The matcher runs against a field from the JSON input that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file:
-
- {
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Edit|Write",
- "hooks": [
- {
- "type": "command",
- "command": "/path/to/lint-check.sh"
- }
- ]
- }
- ]
- }
- }
-
-If you add a `matcher` field to an event without matcher support, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
-
-####
-
-
-
-Match MCP tools
-
-[MCP](</docs/en/mcp>) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`), so you can match them the same way you match any other tool name. MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
-
- * `mcp__memory__create_entities`: Memory server’s create entities tool
- * `mcp__filesystem__read_file`: Filesystem server’s read file tool
- * `mcp__github__search_repositories`: GitHub server’s search tool
-
-To match every tool from a server, append `.*` to the server prefix. The `.*` is required: a matcher like `mcp__memory` or `mcp__brave-search` contains only exact-match characters, so it is compared as an exact string and matches no tool.
-
- * `mcp__memory__.*` matches all tools from the `memory` server
- * `mcp__brave-search__.*` matches all tools from a server whose name contains a hyphen
- * `mcp__.*__write.*` matches any tool whose name starts with `write` from any server
-
-Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a bare hyphenated prefix like `mcp__brave-search` is evaluated as an unanchored regular expression and matches every tool from that server. The `mcp__brave-search__.*` form works on every version. Tools from a [plugin-bundled MCP server](</docs/en/mcp#plugin-provided-mcp-servers>) use a scoped server segment that includes the plugin name: `mcp__plugin_<plugin-name>_<server-name>__<tool>`. A matcher written against the bare server key never fires for these tools. For a plugin named `my-plugin` that bundles a server under the key `db`, a `query` tool appears as `mcp__plugin_my-plugin_db__query`, so the matcher for every tool from that server is `mcp__plugin_my-plugin_db__.*`. Use the same scoped tool name in a handler’s `if` field. See [Plugin-provided MCP servers](</docs/en/mcp#plugin-provided-mcp-servers>) for how the scoped name is built. This example logs all memory server operations and validates write operations from any MCP server:
-
- {
- "hooks": {
- "PreToolUse": [
- {
- "matcher": "mcp__memory__.*",
- "hooks": [
- {
- "type": "command",
- "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
- }
- ]
- },
- {
- "matcher": "mcp__.*__write.*",
- "hooks": [
- {
- "type": "command",
- "command": "/home/user/scripts/validate-mcp-write.py"
- }
- ]
- }
- ]
- }
- }
-
-###
-
-
-
-Hook handler fields
-
-Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, MCP tool, LLM prompt, or agent that runs when the matcher matches. There are five types:
-
- * **Command hooks** (`type: "command"`): run a shell command. Your script receives the event’s JSON input on stdin and communicates results back through exit codes and stdout.
- * **HTTP hooks** (`type: "http"`): send the event’s JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same JSON output format as command hooks.
- * **MCP tool hooks** (`type: "mcp_tool"`): call a tool on an already-connected [MCP server](</docs/en/mcp>). The tool’s text output is treated like command-hook stdout.
- * **Prompt hooks** (`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.
- * **Agent hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks.
-
-All matching hooks run in parallel. If you define the same handler in more than one settings file, it runs once. A plugin’s or skill’s copy of the same handler stays separate. 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. As of v2.1.199, [`$CLAUDE_CODE_BRIDGE_SESSION_ID`](</docs/en/env-vars>) is set to the [Remote Control](</docs/en/remote-control>) session ID while the local session has an active Remote Control connection.
-
-####
-
-
-
-Common fields
-
-These fields apply to all hook types:
-
-Field| Required| Description
----|---|---
-`type`| yes| `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"`
-`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the Bash matching table below for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
-`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30, and `MessageDisplay` lowers it to 10. `SessionEnd` hooks share a 1.5-second budget; if your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds
-`statusMessage`| no| Custom spinner message displayed while the hook runs
-`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
-
-The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. In an `if` condition for a file tool, a single-segment directory pattern like `"Edit(src/**)"` matches only the `src` directory in the working directory and the files under it. To match a directory named `src` at any depth, write `"Edit(**/src/**)"`. Before v2.1.214, `"Edit(src/**)"` matched a directory named `src` at any depth under the working directory. For Bash patterns, whether your hook command runs depends on the shape of the pattern and the Bash command Claude is invoking. Leading `VAR=value` assignments are stripped before matching.
-
-`if` pattern| Bash command| Hook runs?| Why
----|---|---|---
-`Bash(git *)`| `FOO=bar git push`| yes| leading assignments are stripped; `git push` matches
-`Bash(git *)`| `npm test && git push`| yes| each subcommand is checked; `git push` matches
-`Bash(rm *)`| `echo $(rm -rf /)`| yes| commands inside `$()` and backticks are checked; `rm -rf /` matches
-`Bash(rm *)`| `echo $(date)`| no| no subcommand matches `rm *`
-`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-
-The filter also fails open, running your hook regardless of pattern, when the Bash command can’t be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny.
-
-####
-
-
-
-Command hook fields
-
-In addition to the common fields, command hooks accept these fields:
-
-Field| Required| Description
----|---|---
-`command`| yes| Shell command to execute. With `args`, the executable to spawn directly. See Exec form and shell form
-`args`| no| Argument list. When present, `command` is resolved as an executable and spawned directly with `args` as the argument vector, with no shell involved. See Exec form and shell form
-`async`| no| If `true`, runs in the background without blocking. See Run hooks in the background
-`asyncRewake`| no| If `true`, runs in the background and wakes Claude on exit code 2. Implies `async`. The hook’s stderr, or stdout if stderr is empty, is shown to Claude as a system reminder so it can react to a long-running background failure
-`shell`| no| Shell to use for this hook. Accepts `"bash"` or `"powershell"`. Defaults to `"bash"`, or to `"powershell"` on Windows when Git Bash isn’t installed. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly. Ignored when `args` is set
-
-##### Exec form and shell form
-
-A command hook runs as exec form when `args` is set, and shell form when `args` is omitted. Set `args` whenever the hook references a path placeholder, since each element is passed as one argument with no quoting. Omit `args` when you need shell features like pipes or `&&`, or when neither concern applies. **Exec form** runs when `args` is present. Claude Code resolves `command` as an executable on `PATH` and spawns it directly with `args` as the argument vector. There is no shell, so each `args` element is one argument exactly as written, and path placeholders like `${CLAUDE_PLUGIN_ROOT}` are substituted into `command` and into each `args` element as plain strings. Special characters such as apostrophes, `$`, and backticks pass through verbatim because there is no shell to interpret them. No shell tokenization happens on any platform. **Shell form** runs when `args` is absent. The `command` string is passed to a shell: `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed. Set the `shell` field to choose explicitly. The shell tokenizes the string, expands variables, and interprets pipes, `&&`, redirects, and globs.
-
-On Windows, exec form requires `command` to resolve to a real executable such as a `.exe`. The `.cmd` and `.bat` shims that npm, npx, eslint, and other tools install in `node_modules/.bin` are not executables and can’t be spawned without a shell. To run them in exec form, invoke the underlying script with `node` directly, for example `"command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/node_modules/eslint/bin/eslint.js"]`. The `node` plus script-path pattern works on every platform because `node.exe` is a real binary. To run a `.cmd` or `.bat` shim by name, use shell form.
-
-This example runs a Node script bundled with a plugin. Exec form passes the resolved script path as one argument with no quoting:
-
- {
- "type": "command",
- "command": "node",
- "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/format.js", "--fix"]
- }
-
-The equivalent shell form needs quoting to handle paths with spaces or special characters:
-
- {
- "type": "command",
- "command": "node \"${CLAUDE_PLUGIN_ROOT}\"/scripts/format.js --fix"
- }
-
-Both forms support the same path placeholders, and both export them as the environment variables `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, and `CLAUDE_PLUGIN_DATA` on the spawned process, so a script can read `process.env.CLAUDE_PLUGIN_ROOT` regardless of how it was launched. Plugin hooks additionally substitute [`${user_config.*}`](</docs/en/plugins-reference#user-configuration>) values, in exec form only: the value is substituted into `command` and into each `args` element as a plain string, so no shell re-parses it. A shell-form plugin hook whose `command` references `${user_config.*}` fails with an [error](</docs/en/errors#plugin-command-references-user-config>) instead of running. To use an option value from a shell-form hook, read the `$CLAUDE_PLUGIN_OPTION_<KEY>` environment variable, such as `$CLAUDE_PLUGIN_OPTION_WEBHOOK_URL` for a `webhook_url` option, or set `args` to switch the hook to exec form. Before v2.1.207, shell-form plugin hook commands also substituted `${user_config.*}`.
-
-In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and don’t trigger the warning.
-
-####
-
-
-
-HTTP hook fields
-
-In addition to the common fields, HTTP hooks accept these fields:
-
-Field| Required| Description
----|---|---
-`url`| yes| URL to send the POST request to
-`headers`| no| Additional HTTP headers as key-value pairs. Values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in `allowedEnvVars` are resolved
-`allowedEnvVars`| no| List of environment variable names that may be interpolated into header values. References to unlisted variables are replaced with empty strings. Required for any env var interpolation to work
-
-Claude Code sends the hook’s JSON input as the POST request body with `Content-Type: application/json`. The response body uses the same JSON output format as command hooks. Error handling differs from command hooks; see HTTP response handling. This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
-
- {
- "hooks": {
- "PreToolUse": [
- {
- "matcher": "Bash",
- "hooks": [
- {
- "type": "http",
- "url": "http://localhost:8080/hooks/pre-tool-use",
- "timeout": 30,
- "headers": {
- "Authorization": "Bearer $MY_TOKEN"
- },
- "allowedEnvVars": ["MY_TOKEN"]
- }
- ]
- }
- ]
- }
- }
-
-####
-
-
-
-MCP tool hook fields
-
-In addition to the common fields, MCP tool hooks accept these fields:
-
-Field| Required| Description
----|---|---
-`server`| yes| Name of a configured MCP server. For a [plugin-bundled server](</docs/en/mcp#plugin-provided-mcp-servers>), this is the scoped name `plugin:<plugin-name>:<server-name>`, such as `plugin:my-plugin:db`, not the bare server key. The server must already be connected; the hook never triggers an OAuth or connection flow
-`tool`| yes| Name of the tool to call on that server
-`input`| no| Arguments passed to the tool. String values support `${path}` substitution from the hook’s JSON input, such as `"${tool_input.file_path}"`
-
-The tool’s text content is treated like command-hook stdout: if it parses as valid JSON output it is processed as a decision, otherwise it is shown as plain text. If the named server is not connected, or the tool returns `isError: true`, the hook produces a non-blocking error and execution continues. MCP tool hooks are available on every hook event once Claude Code has connected to your MCP servers. `SessionStart` and `Setup` typically fire before servers finish connecting, so hooks on those events should expect the “not connected” error on first run. This example calls the `security_scan` tool on the `my_server` MCP server after each `Write` or `Edit`, passing the edited file’s path:
-
- {
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Write|Edit",
- "hooks": [
- {
- "type": "mcp_tool",
- "server": "my_server",
- "tool": "security_scan",
- "input": { "file_path": "${tool_input.file_path}" }
- }
- ]
- }
- ]
- }
- }
-
-####
-
-
-
-Prompt and agent hook fields
-
-In addition to the common fields, prompt and agent hooks accept these fields:
-
-Field| Required| Description
----|---|---
-`prompt`| yes| Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON. Escape with a backslash to include literal text: `\$1.00` renders as `$1.00`
-`model`| no| Model to use for evaluation. Defaults to a fast model
-
-###
-
-
-
-Reference scripts by path
-
-Use these placeholders to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
-
- * `${CLAUDE_PROJECT_DIR}`: the project root. Claude Code also sets this variable in the environment of [stdio MCP servers](</docs/en/mcp#option-3-add-a-local-stdio-server>) and plugin LSP servers.
- * `${CLAUDE_PLUGIN_ROOT}`: the plugin’s installation directory, for scripts bundled with a [plugin](</docs/en/plugins>). Changes on each plugin update.
- * `${CLAUDE_PLUGIN_DATA}`: the plugin’s [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>), for dependencies and state that should survive plugin updates.
-
-Prefer exec form for any hook that references a path placeholder. In shell form, wrap each placeholder in double quotes.
-
- * Project scripts
-
- * Plugin scripts
-
-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:
-
- {
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Write|Edit",
- "hooks": [
- {
- "type": "command",
- "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh",
- "args": []
- }
- ]
- }
- ]
- }
- }
-
-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.This example runs a formatting script bundled with the plugin:
-
- {
- "description": "Automatic code formatting",
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Write|Edit",
- "hooks": [
- {
- "type": "command",
- "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
- "args": [],
- "timeout": 30
- }
- ]
- }
- ]
- }
- }
-
-See the [plugin components reference](</docs/en/plugins-reference#hooks>) for details on creating plugin hooks.
-
-###
-
-
-
-Hooks in skills and agents
-
-In addition to settings files and plugins, hooks can be defined directly in [skills](</docs/en/skills>) and [subagents](</docs/en/sub-agents>) using frontmatter. These hooks are scoped to the component’s lifecycle and only run when that component is active. All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes. Hooks use the same configuration format as settings-based hooks but are scoped to the component’s lifetime and cleaned up when it finishes. This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
-
- ---
- name: secure-operations
- description: Perform operations with security checks
- hooks:
- PreToolUse:
- - matcher: "Bash"
- hooks:
- - type: command
- command: "./scripts/security-check.sh"
- ---
-
-Subagents use the same format in their YAML frontmatter. Frontmatter hooks in a project subagent run only after you accept the [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) for the folder the agent file came from; see [which scopes are exempt](</docs/en/sub-agents#hooks-in-subagent-frontmatter>). Before v2.1.218, these hooks could run from folders you hadn’t trusted.
-
-###
-
-
-
-The `/hooks` menu
-
-Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook’s command, prompt, or URL. The menu displays all five hook types: `command`, `prompt`, `agent`, `http`, and `mcp_tool`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:
-
- * `User Settings`: from `~/.claude/settings.json`
- * `Project Settings`: from `.claude/settings.json`
- * `Local Settings`: from `.claude/settings.local.json`
- * `Plugin Hooks`: from a plugin’s `hooks/hooks.json`
- * `Session Hooks`: registered in memory for the current session
- * `Built-in Hooks`: registered internally by Claude Code
-
-Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.
-
-###
-
-
-
-Disable or remove hooks
-
-To remove a hook, delete its entry from the settings JSON file. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration. The `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 can’t disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks. Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
-
-##
-
-
-
-Hook input and output
-
-Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options. On macOS and Linux, command hooks run in their own session without a controlling terminal as of v2.1.139. The hook process and any child processes can’t open `/dev/tty` or send escape sequences directly to the Claude Code interface. Windows has no `/dev/tty`. To surface a message to the user on any platform, return `systemMessage` in JSON output. To trigger a desktop notification, set a window title, or ring the bell, return `terminalSequence` instead.
-
-###
-
-
-
-Common input fields
-
-Hook events receive these fields as JSON, in addition to event-specific fields documented in each hook event section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.
-
-Field| Description
----|---
-`session_id`| Current session identifier
-`prompt_id`| UUID identifying the user prompt currently being processed. Matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>), so you can correlate hook output with telemetry for a single prompt. Absent until the first user input. Requires Claude Code v2.1.196 or later
-`transcript_path`| Path to conversation JSON. The transcript file is written asynchronously and may lag the in-memory conversation, so it may not yet include the current turn’s most recent messages when a hook fires. Hooks that need the final assistant text of the current turn should use `last_assistant_message` on Stop and SubagentStop instead of reading the transcript
-`cwd`| Current working directory when the hook is invoked
-`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. The mode labeled **Manual** arrives as `"default"`, never as `"manual"`, so scripts that match `"default"` keep working. Not all events receive this field. Check the JSON example in each hook event section
-`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested model effort exceeds what the current model supports, this is the downgraded level the model actually used. Ultracode is not a distinct level and reports as `"xhigh"`. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
-`hook_event_name`| Name of the event that fired
-
-When running with `--agent` or inside a subagent, two additional fields are included:
-
-Field| Description
----|---
-`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
-`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. See SubagentStart for the values custom and plugin subagents report and how to write a matcher against a plugin-scoped name.
-
-Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value doesn’t change when you switch models with `/model` during a session. One set of variables is not inherited: Claude Code [removes `OTEL_*` exporter variables from every subprocess it spawns](</docs/en/monitoring-usage#administrator-configuration>), including hooks. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
-
- {
- "session_id": "abc123",
- "prompt_id": "550e8400-e29b-41d4-a716-446655440000",
- "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
- "cwd": "/home/user/my-project",
- "permission_mode": "default",
- "hook_event_name": "PreToolUse",
- "tool_name": "Bash",
- "tool_input": {
- "command": "npm test",
- "description": "Run test suite",
- "timeout": 120000,
- "run_in_background": false
- },
- "tool_use_id": "toolu_01ABC123..."
- }
-
-The `tool_name`, `tool_input`, and `tool_use_id` fields are event-specific. Each hook event section documents the additional fields for that event.
-
-###
-
-
-
-Exit code output
-
-The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. Stderr from a hook that exits 0 goes to the debug log only, never the transcript, and Claude never sees it. To read it yourself, enable debug logging. To surface a warning to Claude from a `PostToolUse` or `PostToolUseFailure` hook, exit 2 instead so Claude sees the stderr even though the tool already ran. **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 for the full list. A hook that exits 2 while printing JSON that fails JSON output schema validation still blocks: Claude Code uses stderr as the blocking reason and records the validation failure in the debug log. Before v2.1.214, Claude Code treated that combination as a non-blocking error and the action proceeded. **Any other exit code** is a non-blocking error for most hook events. The action proceeds, and the transcript shows a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable debug logging. For example, a hook command script that blocks dangerous Bash commands:
-
- #!/bin/bash
- # Reads JSON input from stdin, checks the command
- input=$(cat)
- command=$(jq -r '.tool_input.command' <<<"$input")
-
- if [[ "$command" == rm* ]]; then
- echo "Blocked: rm commands are not allowed" >&2
- exit 2 # Blocking error: tool call is prevented
- fi
-
- exit 0 # No decision: the normal permission flow applies
-
-For most hook events, only exit code 2 blocks the action. Claude Code treats exit code 1 as a non-blocking error and proceeds with the action, even though 1 is the conventional Unix failure code. If your hook is meant to enforce a policy, use `exit 2`. The exception is `WorktreeCreate`, where any non-zero exit code aborts worktree creation.
-
-####
-
-
-
-Exit code 2 behavior per event
-
-Exit 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.
-
-Hook event| Can block?| What happens on exit 2
----|---|---
-`PreToolUse`| Yes| Blocks the tool call
-`PermissionRequest`| Yes| Denies the permission
-`UserPromptSubmit`| Yes| Blocks prompt processing and erases the prompt
-`UserPromptExpansion`| Yes| Blocks the expansion
-`Stop`| Yes| Prevents Claude from stopping, continues the conversation
-`SubagentStop`| Yes| Prevents the subagent from stopping
-`TeammateIdle`| Yes| Prevents the teammate from going idle, so it continues working
-`TaskCreated`| Yes| Rolls back the task creation
-`TaskCompleted`| Yes| Prevents the task from being marked as completed
-`ConfigChange`| Yes| Blocks the configuration change from taking effect (except `policy_settings`)
-`StopFailure`| No| Output and exit code are ignored
-`PostToolUse`| No| Shows stderr to Claude; the tool already ran
-`PostToolUseFailure`| No| Shows stderr to Claude; the tool already failed
-`PostToolBatch`| Yes| Stops the agentic loop before the next model call
-`PermissionDenied`| No| Exit code and stderr are ignored because the denial already occurred. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry
-`Notification`| No| Shows stderr to user only
-`SubagentStart`| No| Shows stderr to user only
-`SessionStart`| No| Shows stderr to user only
-`Setup`| No| Shows stderr to user only
-`SessionEnd`| No| Shows stderr to user only
-`CwdChanged`| No| Shows stderr to user only
-`DirectoryAdded`| No| Stderr goes to the debug log; the directory is already added
-`FileChanged`| No| Shows stderr to user only
-`PreCompact`| Yes| Blocks compaction
-`PostCompact`| No| Shows stderr to user only
-`Elicitation`| Yes| Denies the elicitation
-`ElicitationResult`| Yes| Blocks the response (action becomes decline)
-`WorktreeCreate`| Yes| Any non-zero exit code causes worktree creation to fail
-`WorktreeRemove`| No| Failures are logged in debug mode only
-`InstructionsLoaded`| No| Exit code is ignored
-`MessageDisplay`| No| The original text is displayed
-
-For `SessionStart`, `Setup`, and `SubagentStart`, the exit code 2 stderr renders in the transcript as a `<hook name> hook error` notice, the same way a non-blocking error does. Claude doesn’t see it, and the session or subagent proceeds. For `SubagentStart`, the notice appears in the subagent’s own transcript, not in the parent conversation.
-
-###
-
-
-
-HTTP response handling
-
-HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:
-
- * **2xx with an empty body** : success, equivalent to exit code 0 with no output
- * **2xx with a plain text body** : success, the text is added as context
- * **2xx with a JSON body** : success, parsed using the same JSON output schema as command hooks
- * **Non-2xx status** : non-blocking error, execution continues
- * **Connection failure or timeout** : non-blocking error, execution continues
-
-Unlike command hooks, HTTP hooks can’t signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.
-
-###
-
-
-
-JSON output
-
-Exit codes only let you block or stay silent, 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 for blocking, allowing, or escalating to the user.
-
-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.
-
-Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. Hook output strings, including `additionalContext`, `systemMessage`, and plain stdout, are capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way a large valid Bash result is handled under [Output limits](</docs/en/tools-reference#output-limits>). The JSON object supports three kinds of fields:
-
- * **Universal fields** like `continue` work across all events. These are listed in the table below.
- * **Top-level`decision` and `reason`** are used by some events to block or provide feedback.
- * **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.
-
-Field| Default| Description
----|---|---
-`continue`| `true`| If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields
-`stopReason`| none| Message shown to the user when `continue` is `false`. Not shown to Claude
-`suppressOutput`| `false`| If `true`, hides the hook’s stdout from the transcript. Stdout still appears in the debug log
-`systemMessage`| none| Warning message shown to the user
-`terminalSequence`| none| A terminal escape sequence for Claude Code to emit on your behalf, such as a desktop notification, window title, or bell. Restricted to OSC `0`/`1`/`2`/`9`/`99`/`777` and BEL. If the value contains anything outside the allowlist, the field is ignored. Use this instead of writing to `/dev/tty`, which is unavailable to hooks
-
-To stop Claude entirely regardless of event type:
-
- { "continue": false, "stopReason": "Build failed, fix errors before continuing" }
-
-For `PreToolUse` and `PostToolUse` hooks, the stop applies even when the tool call fails or completes while Claude is still streaming a response.
-
-####
-
-
-
-Emit terminal notifications
-
-The `terminalSequence` field requires Claude Code v2.1.141 or later. Hooks run without a controlling terminal, so writing escape sequences directly to `/dev/tty` fails. Instead, return the escape sequence in the `terminalSequence` field and Claude Code emits it for you through its own terminal write path. This is race-free, works inside tmux and GNU screen, and works on Windows where there is no `/dev/tty`. The field accepts a string of one or more allowlisted escape sequences:
-
- * OSC `0`, `1`, `2`: window and icon titles
- * OSC `9`: iTerm2, ConEmu, Windows Terminal, and WezTerm notifications, including `9;4` taskbar progress
- * OSC `99`: Kitty notifications
- * OSC `777`: urxvt, Ghostty, and Warp notifications
- * Bare BEL
-
-Sequences may be terminated with BEL or with ST. Anything outside the allowlist, including CSI cursor and color sequences, OSC palette sequences, OSC 8 hyperlinks, OSC 52 clipboard writes, and OSC 1337, is rejected and the field is ignored. The example below fires a desktop notification from a `Notification` hook. The escape sequence is built with `printf` octal escapes so the control bytes never appear on the shell command line, and `jq -n --arg` builds the JSON output so quotes, backslashes, and newlines in the notification message are escaped correctly:
-
- #!/bin/bash
- # Notification hook: ping the desktop when Claude Code needs attention.
- input=$(cat)
- title="Claude Code"
- body=$(jq -r '.message // "Needs your attention"' <<<"$input")
- seq=$(printf '\033]777;notify;%s;%s\007' "$title" "$body")
- jq -nc --arg seq "$seq" '{terminalSequence: $seq}'
-
-The `{ "terminalSequence": "..." }` shape is the same from any shell or language. On Windows, build the escape string in PowerShell or a script and emit the same JSON object.
-
-`terminalSequence` is the supported replacement for hooks that previously wrote escape sequences directly to `/dev/tty`. The allowlist is restricted to sequences that can’t move the cursor or alter colors, so a hook can never corrupt an on-screen prompt.
-
-####
-
-
-
-Add context for Claude
-
-The `additionalContext` field passes a string from your hook into Claude’s context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it doesn’t appear as a chat message in the interface. Return `additionalContext` inside `hookSpecificOutput` alongside the event name:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PostToolUse",
- "additionalContext": "This file is generated. Edit src/schema.ts and run `bun generate` instead."
- }
- }
-
-Where the reminder appears depends on the event:
-
- * SessionStart, Setup, and SubagentStart: at the start of the conversation, before the first prompt
- * UserPromptSubmit and UserPromptExpansion: alongside the submitted prompt
- * PreToolUse, PostToolUse, PostToolUseFailure, and PostToolBatch: next to the tool result
- * Stop and SubagentStop: at the end of the turn. The conversation continues so Claude can act on the feedback. See Stop decision control
-
-When several hooks return `additionalContext` for the same event, Claude receives all of the values. If a value exceeds 10,000 characters, Claude Code writes the full text to a file in the session directory and passes Claude the file path with a short preview instead. Use `additionalContext` for information Claude should know about the current state of your environment or the operation that just ran:
-
- * **Environment state** : the current branch, deployment target, or active feature flags
- * **Conditional project rules** : which test command applies to the file just edited, which directories are read-only in this worktree
- * **External data** : open issues assigned to you, recent CI results, content fetched from an internal service
-
-For instructions that never change, prefer [CLAUDE.md](</docs/en/memory>). It loads without running a script and is the standard place for static project conventions. Write the text as factual statements rather than imperative system instructions. Phrasing such as “The deployment target is production” or “This repo uses `bun test`” reads as project information. Text framed as out-of-band system commands can trigger Claude’s prompt-injection defenses, which causes Claude to surface the text to you instead of treating it as context. Claude Code saves the injected text in the session transcript. For mid-session events like `PostToolUse` or `UserPromptSubmit`, when you resume with `--continue` or `--resume`, Claude Code replays the saved text rather than re-running the hook for past turns, so values like timestamps or commit SHAs become stale. `SessionStart` hooks run again on resume with `source` set to `"resume"`, or `"fork"` if you added `--fork-session`, so they can refresh their context.
-
-####
-
-
-
-Decision control
-
-Not 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:
-
-Events| Decision pattern| Key fields
----|---|---
-UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`. Stop and SubagentStop also accept `hookSpecificOutput.additionalContext` for non-error feedback that continues the conversation
-TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
-PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason`
-PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
-PermissionDenied| `hookSpecificOutput`| `retry: true` tells the model it may retry the denied tool call
-WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation
-Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept)
-ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
-MessageDisplay| `hookSpecificOutput`| `displayContent` replaces the displayed text on screen. Display-only: the transcript and what Claude sees keep the original
-SessionStart, Setup, SubagentStart| Context only| `hookSpecificOutput.additionalContext` adds context for Claude. SessionStart also accepts `initialUserMessage`, `watchPaths`, `sessionTitle`, and `reloadSkills`. No blocking or decision control
-WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, DirectoryAdded, FileChanged| None| No decision control. Used for side effects like logging or cleanup
-
-A few events can also rewrite content rather than only allow or block it:
-
- * `PreToolUse`: `updatedInput` directly under `hookSpecificOutput` replaces a tool’s arguments before it runs. See PreToolUse decision control
- * `PermissionRequest`: `updatedInput` inside the `decision` object. See PermissionRequest decision control
- * `PostToolUse`: `updatedToolOutput` replaces the tool’s result. See PostToolUse decision control
- * `UserPromptSubmit`: can’t replace the prompt; it only injects `additionalContext` alongside it
-
-For redaction or transformation use cases, intercept at `PreToolUse` for outbound tool inputs and `PostToolUse` for inbound tool results. Here are examples of each pattern in action:
-
- * Top-level decision
-
- * PreToolUse
-
- * PermissionRequest
-
-The only value for `decision` is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
-
- {
- "decision": "block",
- "reason": "Test suite must pass before proceeding"
- }
-
-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 for the full set of options.
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PreToolUse",
- "permissionDecision": "deny",
- "permissionDecisionReason": "Database writes are not allowed"
- }
- }
-
-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 for the full set of options.
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PermissionRequest",
- "decision": {
- "behavior": "allow",
- "updatedInput": {
- "command": "npm run lint"
- }
- }
- }
- }
-
-For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](</docs/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>).
-
-##
-
-
-
-Hook events
-
-Each 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.
-
-###
-
-
-
-SessionStart
-
-Runs 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 doesn’t require a script, use [CLAUDE.md](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. The matcher value corresponds to how the session was initiated:
-
-Matcher| When it fires
----|---
-`startup`| New session
-`resume`| `--resume`, `--continue`, or `/resume`
-`clear`| `/clear`
-`compact`| Auto or manual compaction
-`fork`| A new session forked from an existing one: `--fork-session` with `--resume` or `--continue`, the `/fork` background copy, or `/branch`
-
-Before v2.1.214, forked sessions reported source `"resume"`.
-
-####
-
-
-
-SessionStart input
-
-In addition to the common input fields, SessionStart hooks receive `source` and optionally `model`, `agent_type`, and `session_title`:
-
-Field| Description
----|---
-`source`| How the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, `"compact"` after compaction, or `"fork"` for a new session forked from an existing one
-`model`| The active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it
-`agent_type`| The agent name, present when you start Claude Code with `claude --agent <name>`
-`session_title`| The current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "SessionStart",
- "source": "startup",
- "model": "claude-sonnet-5"
- }
-
-####
-
-
-
-SessionStart decision control
-
-Any text your hook script prints to stdout is added as context for Claude. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
-
-Field| Description
----|---
-`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it
-`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) with the `-p` flag, where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
-`sessionTitle`| Sets the session title, with the same effect as `/rename`. Use to name sessions automatically from the launch folder, git branch, or worktree name. Applies when `source` is `"startup"`, `"resume"`, or `"fork"`; ignored on `"clear"` and `"compact"`
-`watchPaths`| Array of absolute paths to watch for FileChanged events during this session
-`reloadSkills`| Boolean. When `true`, Claude Code re-scans the [skill](</docs/en/skills>) and command directories after the SessionStart hooks complete, so skills the hook installed are available in the same session, starting with the first prompt
-
- {
- "hookSpecificOutput": {
- "hookEventName": "SessionStart",
- "additionalContext": "Current branch: feat/auth-refactor\nUncommitted changes: src/auth.ts, src/login.tsx\nActive issue: #4211 Migrate to OAuth2",
- "sessionTitle": "auth-refactor"
- }
- }
-
-Since plain stdout already reaches Claude for this event, a hook that only loads context can print to stdout directly without building JSON. Use the JSON form when you need to combine context with other fields such as `suppressOutput` or `sessionTitle`. Use `reloadSkills` when a SessionStart hook installs or updates skills. Skill discovery normally runs before SessionStart hooks finish, so files the hook writes into `~/.claude/skills/` or `.claude/skills/` would otherwise only appear in the next session. This example syncs a shared skills repository and requests the re-scan:
-
- #!/bin/bash
-
- git -C ~/.claude/skills/team-skills pull --quiet 2>/dev/null || \
- git clone --quiet https://git.example.com/your-org/team-skills.git ~/.claude/skills/team-skills
-
- echo '{"hookSpecificOutput": {"hookEventName": "SessionStart", "reloadSkills": true}}'
-
-The repository URL is a placeholder; replace it with your own skills repository. With the placeholder, the clone fails and prints a `fatal:` message to stderr. Stderr from a SessionStart hook that exits 0 is informational only, so the `reloadSkills` request still applies.
-
-####
-
-
-
-Persist environment variables
-
-SessionStart 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. To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:
-
- #!/bin/bash
-
- if [ -n "$CLAUDE_ENV_FILE" ]; then
- echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
- echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
- echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
- fi
-
- exit 0
-
-To capture all environment changes from setup commands, compare the exported variables before and after:
-
- #!/bin/bash
-
- ENV_BEFORE=$(export -p | sort)
-
- # Run your setup commands that modify the environment
- source ~/.nvm/nvm.sh
- nvm use 20
-
- if [ -n "$CLAUDE_ENV_FILE" ]; then
- ENV_AFTER=$(export -p | sort)
- comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE"
- fi
-
- exit 0
-
-`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types don’t have access to this variable.
-
-###
-
-
-
-Setup
-
-Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It doesn’t fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use SessionStart instead. The matcher value corresponds to the CLI flag that triggered the hook:
-
-Matcher| When it fires
----|---
-`init`| `claude --init-only` or `claude -p --init`
-`maintenance`| `claude -p --maintenance`
-
-When you run `claude --init-only`, Claude Code runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when you combine them with `-p`. In an interactive session, those two flags don’t currently fire Setup hooks. When you start or continue a conversation with `-p`, you also need to supply a prompt, as an argument or piped on stdin. You can skip the prompt when a `SessionStart` hook supplies `initialUserMessage` or when you resume a session with a deferred tool call. On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
-
-####
-
-
-
-Setup input
-
-In addition to the common input fields, Setup hooks receive a `trigger` field set to either `"init"` or `"maintenance"`:
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "Setup",
- "trigger": "init"
- }
-
-####
-
-
-
-Setup decision control
-
-Setup hooks can’t block. Any non-zero exit code, including 2, surfaces stderr to the user as a `<hook name> hook error` notice, and execution continues. In [non-interactive mode](</docs/en/headless>), hook output appears only when you launch with `--verbose`. To pass information into Claude’s context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
-
-Field| Description
----|---
-`additionalContext`| String added to Claude’s context. Multiple hooks’ values are concatenated
-
- {
- "hookSpecificOutput": {
- "hookEventName": "Setup",
- "additionalContext": "Dependencies installed: node_modules, .venv"
- }
- }
-
-Setup hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` and `type: "mcp_tool"` hooks are supported.
-
-###
-
-
-
-InstructionsLoaded
-
-Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook doesn’t support blocking or decision control. It runs asynchronously for observability purposes. The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
-
-####
-
-
-
-InstructionsLoaded input
-
-In addition to the common input fields, InstructionsLoaded hooks receive these fields:
-
-Field| Description
----|---
-`file_path`| Absolute path to the instruction file that was loaded
-`memory_type`| Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"`
-`load_reason`| Why the file was loaded: `"session_start"`, `"nested_traversal"`, `"path_glob_match"`, `"include"`, or `"compact"`. The `"compact"` value fires when instruction files are re-loaded after a compaction event
-`globs`| Path glob patterns from the file’s `paths:` frontmatter, if any. Present only for `path_glob_match` loads
-`trigger_file_path`| Path to the file whose access triggered this load, for lazy loads
-`parent_file_path`| Path to the parent instruction file that included this one, for `include` loads
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
- "cwd": "/Users/my-project",
- "hook_event_name": "InstructionsLoaded",
- "file_path": "/Users/my-project/CLAUDE.md",
- "memory_type": "Project",
- "load_reason": "session_start"
- }
-
-####
-
-
-
-InstructionsLoaded decision control
-
-InstructionsLoaded hooks have no decision control. They can’t block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
-
-###
-
-
-
-UserPromptSubmit
-
-Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. A `UserPromptSubmit` command, HTTP, or MCP tool hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. The transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `UserPromptSubmit` that reaches its timeout blocks the prompt with a message naming the hook and the timeout, because a callback there can be acting as a policy gate that must not fail open. The session continues. Before v2.1.208, a callback timeout on that event ended the turn with an execution error.
-
-####
-
-
-
-UserPromptSubmit input
-
-In addition to the common input fields, UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "UserPromptSubmit",
- "prompt": "Write a function to calculate the factorial of a number"
- }
-
-####
-
-
-
-UserPromptSubmit decision control
-
-`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All JSON output fields are available. There are two ways to add context to the conversation on exit code 0:
-
- * **Plain text stdout** : any non-JSON text written to stdout is added as context
- * **JSON with`additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
-
-Plain stdout is shown as hook output in the transcript. The `additionalContext` value is injected as a system reminder that Claude reads without a visible transcript entry. To block a prompt, return a JSON object with `decision` set to `"block"`:
-
-Field| Description
----|---
-`decision`| `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed
-`reason`| Shown to the user when `decision` is `"block"`. Not added to context
-`additionalContext`| String added to Claude’s context alongside the submitted prompt. See Add context for Claude
-`sessionTitle`| Sets the session title. Use to name sessions automatically based on the prompt content
-`suppressOriginalPrompt`| If `true` when `decision` is `"block"`, omits the original prompt text from the block message shown to the user
-
- {
- "decision": "block",
- "reason": "Explanation for decision",
- "hookSpecificOutput": {
- "hookEventName": "UserPromptSubmit",
- "additionalContext": "My additional context here",
- "sessionTitle": "My session title"
- }
- }
-
-###
-
-
-
-UserPromptExpansion
-
-Runs when a user-typed command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team’s review checklist as `additionalContext`. This event covers the path `PreToolUse` doesn’t: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path. Matches on `command_name`. Leave the matcher empty to fire on every prompt-type command.
-
-####
-
-
-
-UserPromptExpansion input
-
-In addition to the common input fields, UserPromptExpansion hooks receive `expansion_type`, `command_name`, `command_args`, `command_source`, and the original `prompt` string. The `expansion_type` field is `slash_command` for skill and custom commands, or `mcp_prompt` for MCP server prompts.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../00893aaf.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "UserPromptExpansion",
- "expansion_type": "slash_command",
- "command_name": "example-skill",
- "command_args": "arg1 arg2",
- "command_source": "plugin",
- "prompt": "/example-skill arg1 arg2"
- }
-
-####
-
-
-
-UserPromptExpansion decision control
-
-`UserPromptExpansion` hooks can block the expansion or add context. All JSON output fields are available.
-
-Field| Description
----|---
-`decision`| `"block"` prevents the command from expanding. Omit to allow it to proceed
-`reason`| Shown to the user when `decision` is `"block"`
-`additionalContext`| String added to Claude’s context alongside the expanded prompt. See Add context for Claude
-
- {
- "decision": "block",
- "reason": "This slash command is not available",
- "hookSpecificOutput": {
- "hookEventName": "UserPromptExpansion",
- "additionalContext": "Additional context for this expansion"
- }
- }
-
-###
-
-
-
-MessageDisplay
-
-Runs while an assistant message streams to the screen. Claude Code displays the message in increments: each time a batch of newly completed lines is ready to render, the hook runs once with those lines and Claude Code renders the hook’s replacement text in their place. A long message produces several calls; a short message may produce only one. Use MessageDisplay to:
-
- * strip markdown for a minimal display
- * transform the text an Agent SDK application shows its users
- * redact API keys or internal hostnames from Claude’s responses
-
-Claude Code holds each batch until your hook returns, so keep the hook fast. If the hook fails or times out, Claude Code displays the original text. The default timeout for this event is 10 seconds; if your hook needs more time, set the `timeout` field in the hook entry. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. The hook receives assistant message text only, so tool results and the text you type render unchanged. MessageDisplay doesn’t support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, don’t trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
-
-####
-
-
-
-MessageDisplay input
-
-In addition to the common input fields, MessageDisplay hooks receive identifiers for the turn and message, the position of this call within the message, and the new text in `delta`. Batch boundaries depend on how the text streams, so use `index` and `final` to track progress through a message rather than expecting lines to be grouped a particular way.
-
-Field| Description
----|---
-`turn_id`| UUID of the current turn
-`message_id`| UUID of the assistant message being displayed. Stable across every batch of the same message. This is not the API `msg_…` id, so it can’t be correlated with transcript message ids
-`index`| Zero-based index of this batch within the message
-`final`| `true` on the message’s last batch. Each message has exactly one final batch
-`delta`| The newly completed lines since the prior batch, terminating newlines included. Always whole lines, except the final batch which may end mid-line. In interactive runs, the final batch’s delta is empty when the message ends on a newline, so treat `final`, not a non-empty delta, as the end-of-message signal. In Agent SDK and `claude -p` runs, the single call carries the entire message
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
- "cwd": "/Users/my-project",
- "hook_event_name": "MessageDisplay",
- "turn_id": "0c9e6a2f-7d41-4f4e-9a15-3f4f7c2b8d10",
- "message_id": "5b2a9c8e-1f63-4d8a-b7c4-9e0d2a6f1c3b",
- "index": 0,
- "final": false,
- "delta": "Here is the plan:\n"
- }
-
-####
-
-
-
-MessageDisplay output
-
-In addition to the JSON output fields available to all hooks, MessageDisplay hooks can return `displayContent` to replace the delta on screen:
-
-Field| Description
----|---
-`displayContent`| Text displayed in place of the delta. Omit it to display the original
-
-MessageDisplay hooks have no decision control. They can’t block the message or change what is stored in the transcript or sent to Claude. This example strips markdown formatting from Claude’s responses for a plain-text display. The script reads each batch from stdin, removes bold markers and inline code backticks from `delta`, and returns the result as `displayContent`.
-
- * macOS/Linux
-
- * Windows (PowerShell)
-
-Register a command hook for the event in your settings file:
-
- {
- "hooks": {
- "MessageDisplay": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/plain-display.sh",
- "args": []
- }
- ]
- }
- ]
- }
- }
-
-Save this script to `.claude/hooks/plain-display.sh` in your project and make it executable with `chmod +x`:
-
- #!/bin/bash
- jq '{hookSpecificOutput: {hookEventName: "MessageDisplay", displayContent: (.delta | gsub("\\*\\*"; "") | gsub("`"; ""))}}'
-
-Register a command hook that runs the script through PowerShell:
-
- {
- "hooks": {
- "MessageDisplay": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "powershell.exe",
- "args": [
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- "${CLAUDE_PROJECT_DIR}/.claude/hooks/plain-display.ps1"
- ]
- }
- ]
- }
- ]
- }
- }
-
-The `-NoProfile` flag skips loading your PowerShell profile so the hook starts fast, and `-ExecutionPolicy Bypass` lets PowerShell run the local script file.Save this script to `.claude/hooks/plain-display.ps1` in your project:
-
- $batch = [Console]::In.ReadToEnd() | ConvertFrom-Json
- $text = $batch.delta -replace '\*\*', '' -replace '`', ''
- @{
- hookSpecificOutput = @{
- hookEventName = "MessageDisplay"
- displayContent = $text
- }
- } | ConvertTo-Json
-
-Batches with no markdown pass through unchanged. If the script fails, for example because `jq` is missing, Claude Code displays the original text and notes the failure only in debug output, not in the session.
-
-###
-
-
-
-PreToolUse
-
-Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `PowerShell`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names.
-
-PreToolUse runs only when Claude calls a tool. Files you [reference with `@` in your prompt](</docs/en/common-workflows#reference-files-and-directories>) are added without any tool call: Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. To block specific paths from `@` references, use a [`Read` deny rule](</docs/en/permissions#read-and-edit>) instead.PreToolUse also doesn’t fire for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>).
-
-Use PreToolUse decision control to allow, deny, ask, or defer the tool call. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `PreToolUse` that exceeds its timeout blocks the tool call, and Claude receives an error result naming the timeout. An explicit deny returned by another hook still takes precedence.
-
-####
-
-
-
-PreToolUse input
-
-In addition to the common input fields, PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. For the file tools `Write`, `Edit`, and `Read`, `tool_input.file_path` is always absolute:
-
- * Claude Code expands `~` and relative paths before hooks run, so a hook that matches on paths can’t be bypassed via `~` or a relative spelling of the same path
- * On Windows, the path arrives with backslash separators, even when your hook runs under Git Bash where `$PWD` looks like `/c/project`
- * A comparison written with forward slashes, such as a `/src/` check, never matches a backslash path, and the tool call proceeds as if the hook had nothing to block
- * Normalize separators before comparing: `FILE_PATH="${FILE_PATH//\\//}"` in Bash, or `file_path.replace("\\", "/")` in Python, then match a path segment such as `/src/` rather than anchoring with `^`, since the path is absolute
-
-A `Write` call on Windows delivers:
-
- {
- "hook_event_name": "PreToolUse",
- "tool_name": "Write",
- "tool_input": {
- "file_path": "C:\\project\\src\\index.ts",
- "content": "..."
- },
- ...
- }
-
-The `tool_input` fields depend on the tool:
-
-##### Bash
-
-Executes shell commands.
-
-Field| Type| Example| Description
----|---|---|---
-`command`| string| `"npm test"`| The shell command to execute
-`description`| string| `"Run test suite"`| Optional description of what the command does
-`timeout`| number| `120000`| Optional timeout in milliseconds. Values above the [maximum](</docs/en/tools-reference#bash-tool-behavior>) are reduced to the maximum rather than rejected
-`run_in_background`| boolean| `false`| Whether to run the command in background
-
-##### PowerShell
-
-Executes PowerShell commands. See the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) for availability by platform. The fields match the Bash tool, with the command string in `command`:
-
-Field| Type| Example| Description
----|---|---|---
-`command`| string| `"Get-ChildItem -Recurse"`| The PowerShell command to execute
-`description`| string| `"List files recursively"`| Optional description of what the command does
-`timeout`| number| `120000`| Optional timeout in milliseconds
-`run_in_background`| boolean| `false`| Whether to run the command in background
-
-Match `Bash|PowerShell` in hooks that inspect shell commands, so they cover both tools:
-
- * On Windows, wherever the PowerShell tool is enabled, Claude treats PowerShell as the primary shell and routes shell commands through it.
- * On Windows without Git Bash, the tool is enabled automatically and Claude Code doesn’t register the Bash tool at all.
- * A hook that matches only `Bash` never fires there.
-
-##### Write
-
-Creates or overwrites a file.
-
-Field| Type| Example| Description
----|---|---|---
-`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to write
-`content`| string| `"file content"`| Content to write to the file
-
-##### Edit
-
-Replaces a string in an existing file.
-
-Field| Type| Example| Description
----|---|---|---
-`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to edit
-`old_string`| string| `"original text"`| Text to find and replace
-`new_string`| string| `"replacement text"`| Replacement text
-`replace_all`| boolean| `false`| Whether to replace all occurrences
-
-##### Read
-
-Reads file contents.
-
-Field| Type| Example| Description
----|---|---|---
-`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to read
-`offset`| number| `10`| Optional line number to start reading from
-`limit`| number| `50`| Optional number of lines to read
-
-##### Glob
-
-Finds files matching a glob pattern.
-
-Field| Type| Example| Description
----|---|---|---
-`pattern`| string| `"**/*.ts"`| Glob pattern to match files against
-`path`| string| `"/path/to/dir"`| Optional directory to search in. Defaults to current working directory
-
-##### Grep
-
-Searches file contents with regular expressions.
-
-Field| Type| Example| Description
----|---|---|---
-`pattern`| string| `"TODO.*fix"`| Regular expression pattern to search for
-`path`| string| `"/path/to/dir"`| Optional file or directory to search in
-`glob`| string| `"*.ts"`| Optional glob pattern to filter files
-`output_mode`| string| `"content"`| `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"`
-`-i`| boolean| `true`| Case insensitive search
-`multiline`| boolean| `false`| Enable multiline matching
-
-##### WebFetch
-
-Fetches and processes web content.
-
-Field| Type| Example| Description
----|---|---|---
-`url`| string| `"https://example.com/api"`| URL to fetch content from
-`prompt`| string| `"Extract the API endpoints"`| Prompt to run on the fetched content
-
-##### WebSearch
-
-Searches the web.
-
-Field| Type| Example| Description
----|---|---|---
-`query`| string| `"react hooks best practices"`| Search query
-`allowed_domains`| array| `["docs.example.com"]`| Optional: only include results from these domains
-`blocked_domains`| array| `["spam.example.com"]`| Optional: exclude results from these domains
-
-##### Agent
-
-Spawns a [subagent](</docs/en/sub-agents>).
-
-Field| Type| Example| Description
----|---|---|---
-`prompt`| string| `"Find all API endpoints"`| The task for the agent to perform
-`description`| string| `"Find API endpoints"`| Short description of the task
-`subagent_type`| string| `"Explore"`| Type of specialized agent to use
-`model`| string| `"sonnet"`| Optional model alias to override the default
-
-In `PostToolUse`, `tool_response` for a completed Agent call carries the subagent’s final text along with usage telemetry. Read these fields to record per-subagent cost from a hook:
-
-Field| Type| Example| Description
----|---|---|---
-`status`| string| `"completed"`| `"completed"` for foreground subagents, `"async_launched"` for background subagents. As of v2.1.198, subagents run in the background by default, so an omitted `run_in_background` also produces `"async_launched"`
-`agentId`| string| `"a4d2c8f1e0b3a297"`| Identifier for the subagent run
-`content`| array| `[{"type": "text", "text": "Found 12 endpoints..."}]`| The subagent’s final text blocks
-`resolvedModel`| string| `"claude-sonnet-4-5"`| Model the subagent started on, which may differ from the requested model. Requires Claude Code v2.1.174 or later
-`modelsUsed`| array| `["claude-sonnet-4-5", "claude-haiku-4-5"]`| Models used in order, with consecutive repeats collapsed; set only when the model was swapped mid-run. Requires Claude Code v2.1.212 or later
-`totalTokens`| number| `12450`| Total tokens billed across the subagent’s turns
-`totalDurationMs`| number| `48211`| Wall-clock duration of the subagent run
-`totalToolUseCount`| number| `7`| Count of tool calls the subagent made
-`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`
-
-For background subagents, the tool returns when the task moves to the background, so `tool_response` carries no usage fields: a background launch returns immediately, and a foreground task that Claude Code backgrounds mid-run returns at that transition. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. On a `completed` response, `resolvedModel` names the model the subagent started on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later. On an `async_launched` response, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later.
-
-##### AskUserQuestion
-
-Asks the user one to four multiple-choice questions.
-
-Field| Type| Example| Description
----|---|---|---
-`questions`| array| `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]`| Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag
-`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude doesn’t set this field; supply it via `updatedInput` to answer programmatically
-
-##### ExitPlanMode
-
-Presents a plan and asks the user to approve it before Claude leaves [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). Claude writes the plan to a file on disk before calling the tool, so the literal `tool_input` from the model is typically empty. Claude Code injects the plan content and file path before passing the input to hooks.
-
-Field| Type| Example| Description
----|---|---|---
-`plan`| string| `"## Refactor auth\n1. Extract..."`| Plan content in Markdown. Injected from the plan file on disk
-`planFilePath`| string| `"/Users/.../plans/refactor-auth.md"`| Path to the plan file. Injected
-`allowedPrompts`| array| `[{"tool": "Bash", "prompt": "run tests"}]`| Deprecated. Claude Code accepts the field but ignores it. Before v2.1.205, it carried prompt-based permissions Claude requested to implement the plan
-
-In `PostToolUse`, `tool_response` is an object with `plan` and `filePath` fields holding the approved plan, plus internal status flags. Read `tool_response.plan` for the plan content rather than re-reading the file from disk.
-
-####
-
-
-
-PreToolUse decision control
-
-`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: four outcomes (allow, deny, ask, or defer) plus the ability to modify tool input before execution.
-
-Field| Description
----|---
-`permissionDecision`| `"allow"` skips the permission prompt, except for tools that require user interaction and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>). `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
-`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored
-`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
-`additionalContext`| String added to Claude’s context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See Add context for Claude
-
-When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`. When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation. A hook’s `"ask"` also forces a permission prompt in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): the classifier can still deny the tool call, but it can’t approve the call silently. Before v2.1.211, the classifier could approve a Bash command running outside the [sandbox](</docs/en/sandboxing>) without showing the prompt the hook requested; the classifier still applied its own safety rules to that command, and a hook `"deny"` was always honored.
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PreToolUse",
- "permissionDecision": "allow",
- "permissionDecisionReason": "My reason here",
- "updatedInput": {
- "field_to_modify": "new value"
- },
- "additionalContext": "Current environment: production. Proceed with caution."
- }
- }
-
-`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs.
-
-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.
-
-####
-
-
-
-Defer a tool call for later
-
-`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](</docs/en/headless>) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result. The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:
-
- 1. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires.
- 2. The hook returns `permissionDecision: "defer"`. The tool doesn’t execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
- 3. The calling process reads `deferred_tool_use` from the SDK result, surfaces the question in its own UI, and waits for an answer.
- 4. The calling process runs `claude -p --resume <session-id>`. The same tool call fires `PreToolUse` again.
- 5. The hook returns `permissionDecision: "allow"` with the answer in `updatedInput`. The tool executes and Claude continues.
-
-The `deferred_tool_use` field carries the tool’s `id`, `name`, and `input`. The `input` is the parameters Claude generated for the tool call, captured before execution:
-
- {
- "type": "result",
- "subtype": "success",
- "stop_reason": "tool_deferred",
- "session_id": "abc123",
- "deferred_tool_use": {
- "id": "toolu_01abc",
- "name": "AskUserQuestion",
- "input": { "questions": [{ "question": "Which framework?", "header": "Framework", "options": [{"label": "React"}, {"label": "Vue"}], "multiSelect": false }] }
- }
- }
-
-There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
-
-`--resume` restores the permission mode that was active when the tool was deferred, so you don’t need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over, and `auto`, which is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Passing `--permission-mode` explicitly on resume overrides the restored value.
-
-###
-
-
-
-PermissionRequest
-
-Runs when Claude Code is about to ask you for permission. In sessions that can’t show a prompt, such as background subagents in [non-interactive mode](</docs/en/headless>), Claude Code still runs these hooks, and if no hook returns a decision, it denies the tool call. Use PermissionRequest decision control to allow or deny on behalf of the user. Matches on tool name, same values as PreToolUse.
-
-####
-
-
-
-PermissionRequest input
-
-PermissionRequest 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. PreToolUse hooks run before every tool call, whether or not it needs permission. PermissionRequest hooks run only when Claude Code is about to ask you for permission, or when it would otherwise auto-deny a call that can’t prompt. Neither event fires for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>).
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "PermissionRequest",
- "tool_name": "Bash",
- "tool_input": {
- "command": "rm -rf node_modules",
- "description": "Remove node_modules directory"
- },
- "permission_suggestions": [
- {
- "type": "addRules",
- "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],
- "behavior": "allow",
- "destination": "localSettings"
- }
- ]
- }
-
-####
-
-
-
-PermissionRequest decision control
-
-`PermissionRequest` hooks can allow or deny permission requests. In addition to the JSON output fields available to all hooks, your hook script can return a `decision` object with these event-specific fields:
-
-Field| Description
----|---
-`behavior`| `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated, so a hook returning `"allow"` doesn’t override a matching deny rule
-`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. The modified input is re-evaluated against deny and ask rules
-`updatedPermissions`| For `"allow"` only: array of permission update entries to apply, such as adding an allow rule or changing the session permission mode
-`message`| For `"deny"` only: tells Claude why the permission was denied
-`interrupt`| For `"deny"` only: if `true`, stops Claude
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PermissionRequest",
- "decision": {
- "behavior": "allow",
- "updatedInput": {
- "command": "npm run lint"
- }
- }
- }
- }
-
-####
-
-
-
-Permission update entries
-
-The `updatedPermissions` output field and the `permission_suggestions` input field both use the same array of entry objects. Each entry has a `type` that determines its other fields, and a `destination` that controls where the change is written.
-
-`type`| Fields| Effect
----|---|---
-`addRules`| `rules`, `behavior`, `destination`| Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"`
-`replaceRules`| `rules`, `behavior`, `destination`| Replaces all rules of the given `behavior` at the `destination` with the provided `rules`
-`removeRules`| `rules`, `behavior`, `destination`| Removes matching rules of the given `behavior`
-`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `auto`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `plan`, and `manual` as an alias for `default`. The `manual` alias requires Claude Code v2.1.200 or later
-`addDirectories`| `directories`, `destination`| Adds working directories. `directories` is an array of path strings
-`removeDirectories`| `directories`, `destination`| Removes working directories
-
-`setMode` with `bypassPermissions` only takes effect if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and the mode is not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). Otherwise the update is a no-op. `bypassPermissions` is never persisted as `defaultMode` regardless of `destination`.
-
-The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.
-
-`destination`| Writes to
----|---
-`session`| in-memory only, discarded when the session ends
-`localSettings`| `.claude/settings.local.json`
-`projectSettings`| `.claude/settings.json`
-`userSettings`| `~/.claude/settings.json`
-
-A hook can echo one of the `permission_suggestions` it received as its own `updatedPermissions` output, which is equivalent to the user selecting that “always allow” option in the dialog.
-
-###
-
-
-
-PostToolUse
-
-Runs immediately after a tool completes successfully. Matches on tool name, same values as PreToolUse.
-
-####
-
-
-
-PostToolUse input
-
-`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. File-tool `tool_input` paths arrive in the same format as for PreToolUse: always absolute, with the platform’s native separators, so backslashes on Windows.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "PostToolUse",
- "tool_name": "Write",
- "tool_input": {
- "file_path": "/path/to/file.txt",
- "content": "file content"
- },
- "tool_response": {
- "filePath": "/path/to/file.txt",
- "success": true
- },
- "tool_use_id": "toolu_01ABC123...",
- "duration_ms": 12
- }
-
-Field| Description
----|---
-`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks
-
-####
-
-
-
-PostToolUse decision control
-
-`PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
-
-Field| Description
----|---
-`decision`| `"block"` adds the `reason` next to the tool result. Claude still sees the original output; to replace it, use `updatedToolOutput`
-`reason`| Explanation shown to Claude when `decision` is `"block"`
-`additionalContext`| String added to Claude’s context alongside the tool result. See Add context for Claude
-`updatedToolOutput`| Replaces the tool’s output with the provided value before it is sent to Claude. The value must match the tool’s output shape
-`updatedMCPToolOutput`| Replaces the output for MCP tools only. Prefer `updatedToolOutput`, which works for all tools
-
-The example below replaces the output of a `Bash` call. The replacement value matches the `Bash` tool’s output shape:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PostToolUse",
- "additionalContext": "Additional information for Claude",
- "updatedToolOutput": {
- "stdout": "[redacted]",
- "stderr": "",
- "interrupted": false,
- "isImage": false
- }
- }
- }
-
-`updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a PreToolUse hook instead.The replacement value must match the tool’s output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that doesn’t match the tool’s output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption.
-
-###
-
-
-
-PostToolUseFailure
-
-Runs when a tool that started executing fails: the tool threw an error, or an MCP tool returned an error result. Use this to log failures, send alerts, or provide corrective feedback to Claude. Matches on tool name, same values as PreToolUse.
-
-This event doesn’t fire for tool calls rejected before execution: an unknown tool name, input that fails schema or tool-specific validation, or a permission denial. Validation rejections are returned as `tool_use_error` results and happen before hooks run, so they fire neither `PreToolUse` nor `PostToolUseFailure`. Permission denials fire `PreToolUse` but not this event; see PermissionDenied.
-
-####
-
-
-
-PostToolUseFailure input
-
-PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields. For example, a failed `npm test` command might deliver:
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "PostToolUseFailure",
- "tool_name": "Bash",
- "tool_input": {
- "command": "npm test",
- "description": "Run test suite"
- },
- "tool_use_id": "toolu_01ABC123...",
- "error": "Exit code 1\nError: Cannot find module 'express'",
- "is_interrupt": false,
- "duration_ms": 4187
- }
-
-Field| Description
----|---
-`error`| String describing what went wrong. The format depends on the tool that failed
-`is_interrupt`| Optional boolean. True when the failure reached Claude Code as an abort rather than as an error the tool reported. Cancelling a running tool does not fire this hook; the tool result carries the interruption message instead
-`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks
-
-The `error` string is generally the same text Claude receives as the failed tool’s result. Its format varies by tool and failure. Key your hook on `tool_name`, `is_interrupt`, and the `Exit code N` first line; treat the rest of the string as display text, not a stable format.
-
- * For Bash and PowerShell, a command that ran and exited produces a first line `Exit code N`, then any output the command produced as one block with stdout and stderr interleaved
- * A payload may also carry a bare failure message with no exit-code line, when Claude Code could not start the shell process itself
- * Claude Code middle-truncates strings longer than 10,000 characters around a `... [N characters truncated] ...` marker, and can insert lines of its own, such as `Command timed out after 2m 0s`
-
-####
-
-
-
-PostToolUseFailure decision control
-
-`PostToolUseFailure` hooks can provide context to Claude after a tool failure. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
-
-Field| Description
----|---
-`additionalContext`| String added to Claude’s context alongside the error. See Add context for Claude
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PostToolUseFailure",
- "additionalContext": "Additional information about the failure for Claude"
- }
- }
-
-###
-
-
-
-PostToolBatch
-
-Runs once after every tool call in a batch has resolved, before Claude Code sends the next request to the model. `PostToolUse` fires once per tool, which means it fires concurrently when Claude makes parallel tool calls. `PostToolBatch` fires exactly once with the full batch, so it is the right place to inject context that depends on the set of tools that ran rather than on any single tool. There is no matcher for this event.
-
-####
-
-
-
-PostToolBatch input
-
-In addition to the common input fields, PostToolBatch hooks receive `tool_calls`, an array describing every tool call in the batch:
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "PostToolBatch",
- "tool_calls": [
- {
- "tool_name": "Read",
- "tool_input": {"file_path": "/.../ledger/accounts.py"},
- "tool_use_id": "toolu_01...",
- "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."
- },
- {
- "tool_name": "Read",
- "tool_input": {"file_path": "/.../ledger/transactions.py"},
- "tool_use_id": "toolu_02...",
- "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."
- }
- ]
- }
-
-`tool_response` contains the same content the model receives in the corresponding `tool_result` block. The value is a serialized string or content-block array, exactly as the tool emitted it. For `Read`, that means line-number-prefixed text rather than raw file contents. Responses can be large, so parse only the fields you need.
-
-The `tool_response` shape differs from `PostToolUse`’s. `PostToolUse` passes the tool’s structured `Output` object, such as `{filePath: "...", success: true}` for `Write`; `PostToolBatch` passes the serialized `tool_result` content the model sees.
-
-####
-
-
-
-PostToolBatch decision control
-
-`PostToolBatch` hooks can inject context for Claude. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
-
-Field| Description
----|---
-`additionalContext`| Context string injected once before the next model call. See Add context for Claude for delivery details, what to put in it, and how resumed sessions handle past values
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PostToolBatch",
- "additionalContext": "These files are part of the ledger module. Run pytest before marking the task complete."
- }
- }
-
-Returning `decision: "block"` or `continue: false` stops the agentic loop before the next model call.
-
-###
-
-
-
-PermissionDenied
-
-Runs when the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier denies a tool call. This hook only fires in auto mode: it doesn’t run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call. Matches on tool name, same values as PreToolUse.
-
-####
-
-
-
-PermissionDenied input
-
-In addition to the common input fields, PermissionDenied hooks receive `tool_name`, `tool_input`, `tool_use_id`, and `reason`.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "auto",
- "hook_event_name": "PermissionDenied",
- "tool_name": "Bash",
- "tool_input": {
- "command": "rm -rf /tmp/build",
- "description": "Clean build directory"
- },
- "tool_use_id": "toolu_01ABC123...",
- "reason": "Blocked by classifier"
- }
-
-Field| Description
----|---
-`reason`| The denial reason: the fixed text `Blocked by classifier` in most sessions, or the classifier’s written explanation when the session’s classifier model provides one. See [Review denials](</docs/en/auto-mode-config#review-denials>)
-
-####
-
-
-
-PermissionDenied decision control
-
-PermissionDenied hooks can tell the model it may retry the denied tool call. Return a JSON object with `hookSpecificOutput.retry` set to `true`:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PermissionDenied",
- "retry": true
- }
- }
-
-When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook doesn’t return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.
-
-###
-
-
-
-Notification
-
-Runs when Claude Code sends notifications. Matches on notification type. Omit the matcher to run hooks for all notification types.
-
-Matcher| When it fires
----|---
-`permission_prompt`| Claude needs you to approve a tool use
-`idle_prompt`| Claude is done and waiting for your next prompt
-`auth_success`| Authentication completes
-`elicitation_dialog`| An MCP server opens an elicitation form
-`elicitation_complete`| An MCP elicitation form is submitted or dismissed
-`elicitation_response`| An MCP elicitation response is sent back to the server
-`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal
-`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal
-
-The `agent_needs_input` and `agent_completed` types require Claude Code v2.1.198 or later. Use 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:
-
- {
- "hooks": {
- "Notification": [
- {
- "matcher": "permission_prompt",
- "hooks": [
- {
- "type": "command",
- "command": "/path/to/permission-alert.sh"
- }
- ]
- },
- {
- "matcher": "idle_prompt",
- "hooks": [
- {
- "type": "command",
- "command": "/path/to/idle-notification.sh"
- }
- ]
- }
- ]
- }
- }
-
-####
-
-
-
-Notification input
-
-In addition to the common input fields, Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "Notification",
- "message": "Claude needs your permission",
- "title": "Permission needed",
- "notification_type": "permission_prompt"
- }
-
-Notification hooks can’t block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The common JSON output fields such as `systemMessage` apply.
-
-###
-
-
-
-SubagentStart
-
-Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name. For built-in agents, this is the agent name like `general-purpose`, `Explore`, or `Plan`. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), the agent type is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. The colon places a plugin-scoped name on the regular-expression path, so anchor the matcher with `^` and `$` for an exact match: `^my-plugin:reviewer$`.
-
-####
-
-
-
-SubagentStart input
-
-In addition to the common input fields, SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name that the matcher filters on.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "SubagentStart",
- "agent_id": "agent-abc123",
- "agent_type": "Explore"
- }
-
-SubagentStart hooks can’t block subagent creation, but they can inject context into the subagent. In addition to the JSON output fields available to all hooks, you can return:
-
-Field| Description
----|---
-`additionalContext`| String added to the subagent’s context at the start of its conversation, before its first prompt. See Add context for Claude
-
- {
- "hookSpecificOutput": {
- "hookEventName": "SubagentStart",
- "additionalContext": "Follow security guidelines for this task"
- }
- }
-
-###
-
-
-
-SubagentStop
-
-Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.
-
-####
-
-
-
-SubagentStop input
-
-In addition to the 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. SubagentStop hooks also receive the `background_tasks` and `session_crons` arrays described under Stop input, available in Claude Code v2.1.145 or later. Both arrays are scoped to the parent session, not the subagent.
-
- {
- "session_id": "abc123",
- "transcript_path": "~/.claude/projects/.../abc123.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "SubagentStop",
- "stop_hook_active": false,
- "agent_id": "def456",
- "agent_type": "Explore",
- "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
- "last_assistant_message": "Analysis complete. Found 3 potential issues...",
- "background_tasks": [],
- "session_crons": []
- }
-
-SubagentStop hooks use the same decision control format as Stop hooks, including `hookSpecificOutput.additionalContext` with `hookEventName` set to `"SubagentStop"`, for non-error feedback that keeps the subagent running. Returning `decision: "block"` with a `reason` keeps the subagent running and delivers `reason` to the subagent as its next instruction. To inject context into the parent session after a subagent returns, use a `PostToolUse` hook on the `Agent` tool instead.
-
-###
-
-
-
-TaskCreated
-
-Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. TaskCreated hooks don’t support matchers and fire on every occurrence.
-
-####
-
-
-
-TaskCreated input
-
-In addition to the common input fields, TaskCreated hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "TaskCreated",
- "task_id": "task-001",
- "task_subject": "Implement user authentication",
- "task_description": "Add login and signup endpoints",
- "teammate_name": "implementer",
- "team_name": "session-a1b2c3d4"
- }
-
-Field| Description
----|---
-`task_id`| Identifier of the task being created
-`task_subject`| Title of the task
-`task_description`| Detailed description of the task. May be absent
-`teammate_name`| Name of the teammate creating the task. May be absent
-`team_name`| Deprecated. Session-derived team name; will be removed in a future release
-
-####
-
-
-
-TaskCreated decision control
-
-TaskCreated hooks support two ways to control task creation:
-
- * **Exit code 2** : the task is not created and the stderr message is fed back to the model as feedback.
- * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
-
-This example blocks tasks whose subjects don’t follow the required format:
-
- #!/bin/bash
- INPUT=$(cat)
- TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
-
- if [[ ! "$TASK_SUBJECT" =~ ^\[TICKET-[0-9]+\] ]]; then
- echo "Task subject must start with a ticket number, e.g. '[TICKET-123] Add feature'" >&2
- exit 2
- fi
-
- exit 0
-
-###
-
-
-
-TaskCompleted
-
-Runs 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](</docs/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. TaskCompleted hooks don’t support matchers and fire on every occurrence.
-
-####
-
-
-
-TaskCompleted input
-
-In addition to the common input fields, TaskCompleted hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "TaskCompleted",
- "task_id": "task-001",
- "task_subject": "Implement user authentication",
- "task_description": "Add login and signup endpoints",
- "teammate_name": "implementer",
- "team_name": "session-a1b2c3d4"
- }
-
-Field| Description
----|---
-`task_id`| Identifier of the task being completed
-`task_subject`| Title of the task
-`task_description`| Detailed description of the task. May be absent
-`teammate_name`| Name of the teammate completing the task. May be absent
-`team_name`| Deprecated. Session-derived team name; will be removed in a future release
-
-####
-
-
-
-TaskCompleted decision control
-
-TaskCompleted hooks support two ways to control task completion:
-
- * **Exit code 2** : the task is not marked as completed and the stderr message is fed back to the model as feedback.
- * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
-
-This example runs tests and blocks task completion if they fail:
-
- #!/bin/bash
- INPUT=$(cat)
- TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
-
- # Run the test suite
- if ! npm test 2>&1; then
- echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
- exit 2
- fi
-
- exit 0
-
-###
-
-
-
-Stop
-
-Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt. API errors fire StopFailure instead.
-
-The [`/goal`](</docs/en/goal>) command is a built-in shortcut for a session-scoped prompt-based Stop hook. Use it when you want Claude to keep working until a condition holds without writing hook configuration.
-
-####
-
-
-
-Stop input
-
-In addition to the common input fields, Stop hooks receive `stop_hook_active`, `last_assistant_message`, `background_tasks`, and `session_crons`. 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 avoid blocking on a condition that will never resolve. Claude Code overrides the hook and ends the turn after 8 consecutive blocks. The `last_assistant_message` field contains the text content of Claude’s final response, so hooks can access it without parsing the transcript file. For hooks that act on the just-completed turn, such as read-aloud or notification hooks, use this field rather than reading `transcript_path`: the transcript file isn’t guaranteed to include the final message at Stop time on all versions. The `background_tasks` and `session_crons` arrays, available in Claude Code v2.1.145 or later, let hooks distinguish “session is done” from “session is paused waiting for background work to wake it back up”. Both arrays are present when the task registry is reachable and are empty when nothing is in flight or scheduled. Each entry in `background_tasks` describes one in-flight task and uses these fields:
-
-Field| Description
----|---
-`id`| Task identifier
-`type`| Friendly task-type label such as `shell`, `subagent`, `monitor`, `workflow`, `teammate`, `cloud session`, or `MCP task`. Each label identifies which Claude Code feature created the task. Falls back to the raw discriminant for unrecognized types
-`status`| Current task status
-`description`| Free-text description, capped at 1000 characters with an in-string `… [+N chars]` marker when clipped
-`command`| Shell command line, capped at 1000 characters. Present only for `shell` tasks
-`agent_type`| Subagent type name. Present only for `subagent` tasks
-`server`| MCP server name. Present only for `monitor` and `MCP task` tasks
-`tool`| MCP tool name. Present only for `monitor` and `MCP task` tasks
-`name`| Workflow name. Present only for `workflow` tasks
-
-Each entry in `session_crons` describes one session-scoped scheduled wakeup, sourced from `CronCreate`, `ScheduleWakeup`, and `/loop`:
-
-Field| Description
----|---
-`id`| Cron task identifier
-`schedule`| Cron expression, for example `0 9 * * 1-5`
-`recurring`| `false` for one-shot wakeups whose schedule encodes a single fire time, `true` for tasks that re-fire on every match
-`prompt`| Prompt submitted when the cron fires, capped at 1000 characters with the same `… [+N chars]` marker
-
-This example shows a Stop input with one in-flight shell task and one recurring cron:
-
- {
- "session_id": "abc123",
- "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "Stop",
- "stop_hook_active": true,
- "last_assistant_message": "I've completed the refactoring. Here's a summary...",
- "background_tasks": [
- {
- "id": "task-001",
- "type": "shell",
- "status": "running",
- "description": "tail logs",
- "command": "tail -f /var/log/syslog"
- }
- ],
- "session_crons": [
- {
- "id": "cron-001",
- "schedule": "0 9 * * 1-5",
- "recurring": true,
- "prompt": "check the build"
- }
- ]
- }
-
-####
-
-
-
-Stop decision control
-
-`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
-
-Field| Description
----|---
-`decision`| `"block"` prevents Claude from stopping. Omit to allow Claude to stop
-`reason`| Required when `decision` is `"block"`. Tells Claude why it should continue
-`hookSpecificOutput.additionalContext`| Non-error feedback for Claude. The conversation continues so Claude can act on it, but unlike `decision: "block"` it is shown in the transcript as hook feedback rather than a hook error
-
- {
- "decision": "block",
- "reason": "Must be provided when Claude is blocked from stopping"
- }
-
-Use `additionalContext` when the hook is working as designed and giving Claude guidance, such as “run the test suite before finishing”. It keeps the conversation going through the same loop protections as `decision: "block"`, namely the `stop_hook_active` input and the 8-consecutive-continuation cap, but the transcript labels it `Stop hook feedback` and no hook error notification is shown:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "Stop",
- "additionalContext": "Please run the test suite before finishing"
- }
- }
-
-###
-
-
-
-StopFailure
-
-Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude can’t complete a response due to rate limits, authentication problems, or other API errors.
-
-####
-
-
-
-StopFailure input
-
-In addition to the common input fields, StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering.
-
-Field| Description
----|---
-`error`| Error type: `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown`
-`error_details`| Additional details about the error, when available
-`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"`
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "StopFailure",
- "error": "rate_limit",
- "error_details": "429 Too Many Requests",
- "last_assistant_message": "API Error: Rate limit reached"
- }
-
-StopFailure hooks have no decision control. They run for notification and logging purposes only.
-
-###
-
-
-
-TeammateIdle
-
-Runs when an [agent team](</docs/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. TeammateIdle hooks don’t support matchers and fire on every occurrence.
-
-####
-
-
-
-TeammateIdle input
-
-In addition to the common input fields, TeammateIdle hooks receive `teammate_name` and `team_name`.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "TeammateIdle",
- "teammate_name": "researcher",
- "team_name": "session-a1b2c3d4"
- }
-
-Field| Description
----|---
-`teammate_name`| Name of the teammate that is about to go idle
-`team_name`| Deprecated. Session-derived team name; will be removed in a future release
-
-####
-
-
-
-TeammateIdle decision control
-
-TeammateIdle hooks support two ways to control teammate behavior:
-
- * **Exit code 2** : the teammate receives the stderr message as feedback and continues working instead of going idle.
- * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
-
-This example checks that a build artifact exists before allowing a teammate to go idle:
-
- #!/bin/bash
-
- if [ ! -f "./dist/output.js" ]; then
- echo "Build artifact missing. Run the build before stopping." >&2
- exit 2
- fi
-
- exit 0
-
-###
-
-
-
-ConfigChange
-
-Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files. ConfigChange 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. The matcher filters on the configuration source:
-
-Matcher| When it fires
----|---
-`user_settings`| `~/.claude/settings.json` changes
-`project_settings`| `.claude/settings.json` changes
-`local_settings`| `.claude/settings.local.json` changes
-`policy_settings`| Managed policy settings change
-`skills`| A skill file in `.claude/skills/` changes
-
-This example logs all configuration changes for security auditing:
-
- {
- "hooks": {
- "ConfigChange": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/audit-config-change.sh",
- "args": []
- }
- ]
- }
- ]
- }
- }
-
-####
-
-
-
-ConfigChange input
-
-In addition to the 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.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "ConfigChange",
- "source": "project_settings",
- "file_path": "/Users/.../my-project/.claude/settings.json"
- }
-
-####
-
-
-
-ConfigChange decision control
-
-ConfigChange 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.
-
-Field| Description
----|---
-`decision`| `"block"` prevents the configuration change from being applied. Omit to allow the change
-`reason`| Explanation shown to the user when `decision` is `"block"`
-
- {
- "decision": "block",
- "reason": "Configuration changes to project settings require admin approval"
- }
-
-`policy_settings` changes can’t 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.
-
-###
-
-
-
-CwdChanged
-
-Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. CwdChanged doesn’t support matchers and fires on every directory change.
-
-####
-
-
-
-CwdChanged input
-
-In addition to the common input fields, CwdChanged hooks receive `old_cwd` and `new_cwd`.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
- "cwd": "/Users/my-project/src",
- "hook_event_name": "CwdChanged",
- "old_cwd": "/Users/my-project",
- "new_cwd": "/Users/my-project/src"
- }
-
-####
-
-
-
-CwdChanged output
-
-In addition to the JSON output fields available to all hooks, CwdChanged hooks can return `watchPaths` to dynamically set which file paths FileChanged watches:
-
-Field| Description
----|---
-`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Returning an empty array clears the dynamic list, which is typical when entering a new directory
-
-CwdChanged hooks have no decision control. They can’t block the directory change.
-
-###
-
-
-
-DirectoryAdded
-
-Runs after you add a working directory mid-session with the `/add-dir` command, or after an SDK client adds one with the `register_repo_root` control request. Use this to prepare a newly added repository, for example by installing its dependencies. Claude Code doesn’t fire this event when:
-
- * You pass a directory with the `--add-dir` startup flag; SessionStart covers those directories
- * You add a directory on the `/permissions` Workspace tab
- * You add a directory that is already a working directory; the add fails with an error
-
-Claude Code fires DirectoryAdded after refreshing sandbox and permission state, so sandboxed tools already see the new directory when your hook runs. Hook commands themselves run unsandboxed. Claude Code doesn’t wait for the hook: the add completes immediately, and the hook runs in the background with the 600-second default timeout. The matcher filters on how the directory was added:
-
-Matcher| When it fires
----|---
-`slash_command`| You add a directory with `/add-dir`
-`register_repo_root`| An SDK client adds a directory with the `register_repo_root` control request
-
-####
-
-
-
-DirectoryAdded input
-
-In addition to the common input fields, DirectoryAdded hooks receive `directory` and `source`.
-
-Field| Description
----|---
-`directory`| Absolute path of the directory that was added
-`source`| How the directory was added, `"slash_command"` for `/add-dir` or `"register_repo_root"` for the SDK control request
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
- "cwd": "/Users/my-project",
- "hook_event_name": "DirectoryAdded",
- "directory": "/Users/my-other-repo",
- "source": "slash_command"
- }
-
-DirectoryAdded hooks have no decision control. They can’t block the add, which has already completed when the hook runs. Claude Code surfaces hook output differently per source:
-
- * `slash_command`: unlike on every other event, where you see the `systemMessage` and Claude doesn’t, Claude Code delivers the hook’s `systemMessage` to Claude as context on the next conversation turn. A count of failed hooks appears in the transcript; full failure output goes to the debug log
- * `register_repo_root`: Claude Code writes `systemMessage` output and failure output to the debug log only
-
-###
-
-
-
-FileChanged
-
-Runs when a watched file changes on disk. Useful for reloading environment variables when project configuration files are modified. The `matcher` for this event serves two roles:
-
- * **Build the watch list** : the value is split on `|` and each segment is registered as a literal filename in the working directory, so `".envrc|.env"` watches exactly those two files. Regex patterns are not useful here: a value like `^\.env` would watch a file literally named `^\.env`.
- * **Filter which hooks run** : when a watched file changes, the same value filters which hook groups run using the standard matcher rules against the changed file’s basename.
-
-FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks.
-
-####
-
-
-
-FileChanged input
-
-In addition to the common input fields, FileChanged hooks receive `file_path` and `event`.
-
-Field| Description
----|---
-`file_path`| Absolute path to the file that changed
-`event`| What happened: `"change"` for a modified file, `"add"` for a created file, or `"unlink"` for a deleted file
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
- "cwd": "/Users/my-project",
- "hook_event_name": "FileChanged",
- "file_path": "/Users/my-project/.envrc",
- "event": "change"
- }
-
-####
-
-
-
-FileChanged output
-
-In addition to the JSON output fields available to all hooks, FileChanged hooks can return `watchPaths` to dynamically update which file paths are watched:
-
-Field| Description
----|---
-`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Use this when your hook script discovers additional files to watch based on the changed file
-
-FileChanged hooks have no decision control. They can’t block the file change from occurring.
-
-###
-
-
-
-WorktreeCreate
-
-Runs when a worktree is being created, whether from `claude --worktree`, from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>), or for a [background session](</docs/en/agent-view#how-file-edits-are-isolated>) that Claude Code isolates in its own worktree. By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. See WorktreeCreate output for how each hook type returns the path. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
-
- {
- "hooks": {
- "WorktreeCreate": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
- }
- ]
- }
- ]
- }
- }
-
-The 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.
-
-####
-
-
-
-WorktreeCreate input
-
-In addition to the 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`.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "WorktreeCreate",
- "name": "feature-auth"
- }
-
-####
-
-
-
-WorktreeCreate output
-
-WorktreeCreate hooks don’t use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the path to the created worktree directory:
-
- * **Command hooks** (`type: "command"`): print the path as the last non-empty line of stdout. Claude Code strips ANSI escape codes before reading that line, so shell startup banners printed before your `echo` are ignored. Redirect any other hook output to stderr.
- * **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
-
-If the hook fails or produces no path, worktree creation fails with an error. Claude Code resolves a relative path against the directory the hook ran in, collapsing any `.` or `..` segments in it. If the resulting path isn’t a directory Claude Code can enter, the session prints an error naming the path and exits with code 1. Before v2.1.205, a relative path or a path that didn’t exist on disk crashed the session at startup, and with `-p` it stalled for about 30 seconds before exiting with code 0. Claude Code refuses an absolute path that contains `.` or `..` segments, and any path that passes through a symlink below the repository root, because a symlink committed to the repository could redirect the worktree outside it. The error names the rejected component. Return a normalized path that doesn’t pass through a symlink inside the repository. Before v2.1.216, worktree creation followed the hook’s path without this screening.
-
-###
-
-
-
-WorktreeRemove
-
-Runs when a worktree is being removed. This is the cleanup counterpart to WorktreeCreate. The event fires when:
-
- * you exit a `--worktree` session and choose to remove it
- * a subagent with `isolation: "worktree"` finishes
- * you delete a [background session](</docs/en/agent-view#what-deleting-a-session-removes>) whose worktree the hook created
-
-For git-based worktrees, Claude Code 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. For a background-session delete, Claude Code verifies the stored worktree path before running the hook and refuses a path that is a symlink or passes through one below the repository root. The hook runs for a worktree that still contains files only when you confirm the delete in [agent view](</docs/en/agent-view#what-deleting-a-session-removes>); for such a worktree, [`claude rm`](</docs/en/agent-view#manage-sessions-from-the-shell>) keeps the session and worktree instead. Before v2.1.216, the hook ran on the stored path without these checks. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
-
- {
- "hooks": {
- "WorktreeRemove": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
- }
- ]
- }
- ]
- }
- }
-
-####
-
-
-
-WorktreeRemove input
-
-In addition to the common input fields, WorktreeRemove hooks receive the `worktree_path` field, which is the absolute path to the worktree being removed.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "WorktreeRemove",
- "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
- }
-
-WorktreeRemove hooks have no decision control. They can’t block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only.
-
-###
-
-
-
-PreCompact
-
-Runs before Claude Code is about to run a compact operation. The matcher value indicates whether compaction was triggered manually or automatically:
-
-Matcher| When it fires
----|---
-`manual`| `/compact`
-`auto`| Auto-compact when the context window is full
-
-Exit with code 2 to block compaction. For a manual `/compact`, the stderr message is shown to the user. You can also block by returning JSON with `"decision": "block"`. Blocking automatic compaction has different effects depending on when it fires. If compaction was triggered proactively before the context limit, Claude Code skips it and the conversation continues uncompacted. If compaction was triggered to recover from a context-limit error already returned by the API, the underlying error surfaces and the current request fails.
-
-####
-
-
-
-PreCompact input
-
-In addition to the 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.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "PreCompact",
- "trigger": "manual",
- "custom_instructions": ""
- }
-
-###
-
-
-
-PostCompact
-
-Runs after Claude Code completes a compact operation. Use this event to react to the new compacted state, for example to log the generated summary or update external state. The same matcher values apply as for `PreCompact`:
-
-Matcher| When it fires
----|---
-`manual`| After `/compact`
-`auto`| After auto-compact when the context window is full
-
-####
-
-
-
-PostCompact input
-
-In addition to the common input fields, PostCompact hooks receive `trigger` and `compact_summary`. The `compact_summary` field contains the conversation summary generated by the compact operation.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "PostCompact",
- "trigger": "manual",
- "compact_summary": "Summary of the compacted conversation..."
- }
-
-PostCompact hooks have no decision control. They can’t affect the compaction result but can perform follow-up tasks.
-
-###
-
-
-
-SessionEnd
-
-Runs when a Claude Code session ends. Useful for cleanup tasks, logging session statistics, or saving session state. Supports matchers to filter by exit reason. The `reason` field in the hook input indicates why the session ended:
-
-Reason| Description
----|---
-`clear`| Session cleared with `/clear` command
-`resume`| Session switched via interactive `/resume`
-`logout`| User logged out
-`prompt_input_exit`| User exited while prompt input was visible
-`bypass_permissions_disabled`| Bypass permissions mode was disabled
-`other`| Other exit reasons
-
-####
-
-
-
-SessionEnd input
-
-In addition to the common input fields, SessionEnd hooks receive a `reason` field indicating why the session ended. See the reason table above for all values.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "SessionEnd",
- "reason": "other"
- }
-
-SessionEnd hooks have no decision control. They can’t block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If a hook needs more time, set a per-hook `timeout` in the hook configuration. The overall budget is automatically raised to the highest per-hook timeout configured in settings files, up to 60 seconds. Timeouts set on plugin-provided hooks don’t raise the budget. To override the budget explicitly, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable in milliseconds.
-
- CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
-
-###
-
-
-
-Elicitation
-
-Runs when an MCP server requests user input mid-task. By default, Claude Code shows an interactive dialog for the user to respond. Hooks can intercept this request and respond programmatically, skipping the dialog entirely. The matcher field matches against the MCP server name.
-
-####
-
-
-
-Elicitation input
-
-In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation, the most common case:
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "Elicitation",
- "mcp_server_name": "my-mcp-server",
- "message": "Please provide your credentials",
- "mode": "form",
- "requested_schema": {
- "type": "object",
- "properties": {
- "username": { "type": "string", "title": "Username" }
- }
- }
- }
-
-For URL-mode elicitation, used for browser-based authentication:
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "Elicitation",
- "mcp_server_name": "my-mcp-server",
- "message": "Please authenticate",
- "mode": "url",
- "url": "https://auth.example.com/login"
- }
-
-####
-
-
-
-Elicitation output
-
-To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "Elicitation",
- "action": "accept",
- "content": {
- "username": "alice"
- }
- }
- }
-
-Field| Values| Description
----|---|---
-`action`| `accept`, `decline`, `cancel`| Whether to accept, decline, or cancel the request
-`content`| object| Form field values to submit. Only used when `action` is `accept`
-
-Exit code 2 denies the elicitation and shows stderr to the user.
-
-###
-
-
-
-ElicitationResult
-
-Runs after a user responds to an MCP elicitation. Hooks can observe, modify, or block the response before it is sent back to the MCP server. The matcher field matches against the MCP server name.
-
-####
-
-
-
-ElicitationResult input
-
-In addition to the common input fields, ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "ElicitationResult",
- "mcp_server_name": "my-mcp-server",
- "action": "accept",
- "content": { "username": "alice" },
- "mode": "form",
- "elicitation_id": "elicit-123"
- }
-
-####
-
-
-
-ElicitationResult output
-
-To override the user’s response, return a JSON object with `hookSpecificOutput`:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "ElicitationResult",
- "action": "decline",
- "content": {}
- }
- }
-
-Field| Values| Description
----|---|---
-`action`| `accept`, `decline`, `cancel`| Overrides the user’s action
-`content`| object| Overrides form field values. Only meaningful when `action` is `accept`
-
-Exit code 2 blocks the response, changing the effective action to `decline`.
-
-##
-
-
-
-Prompt-based hooks
-
-In addition to command, HTTP, and MCP tool hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type. Events that support all five hook types (`command`, `http`, `mcp_tool`, `prompt`, and `agent`):
-
- * `PermissionDenied`
- * `PermissionRequest`
- * `PostToolBatch`
- * `PostToolUse`
- * `PostToolUseFailure`
- * `PreToolUse`
- * `Stop`
- * `SubagentStop`
- * `TaskCompleted`
- * `TaskCreated`
- * `TeammateIdle`
- * `UserPromptExpansion`
- * `UserPromptSubmit`
-
-Events that support `command`, `http`, and `mcp_tool` hooks but not `prompt` or `agent`:
-
- * `ConfigChange`
- * `CwdChanged`
- * `DirectoryAdded`
- * `Elicitation`
- * `ElicitationResult`
- * `FileChanged`
- * `InstructionsLoaded`
- * `Notification`
- * `PostCompact`
- * `PreCompact`
- * `SessionEnd`
- * `StopFailure`
- * `SubagentStart`
- * `WorktreeCreate`
- * `WorktreeRemove`
-
-`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They don’t support `http`, `prompt`, or `agent` hooks.
-
-###
-
-
-
-How prompt-based hooks work
-
-Instead of executing a Bash command, prompt-based hooks:
-
- 1. Send the hook input and your prompt to a Claude model, Haiku by default
- 2. The LLM responds with structured JSON containing a decision
- 3. Claude Code processes the decision automatically
-
-###
-
-
-
-Prompt hook configuration
-
-Set `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. This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
-
- {
- "hooks": {
- "Stop": [
- {
- "hooks": [
- {
- "type": "prompt",
- "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."
- }
- ]
- }
- ]
- }
- }
-
-Field| Required| Description
----|---|---
-`type`| yes| Must be `"prompt"`
-`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
-`model`| no| Model to use for evaluation. Defaults to a fast model
-`timeout`| no| Timeout in seconds. Default: 30
-`continueOnBlock`| no| When the prompt returns `ok: false`, feed the reason back to Claude and continue the turn instead of stopping. Default: `false`. Implemented as `continue: true` on the resulting `decision: "block"`. See Response schema for per-event behavior
-
-###
-
-
-
-Response schema
-
-The LLM must respond with JSON containing:
-
- {
- "ok": true | false,
- "reason": "Explanation for the decision"
- }
-
-Field| Description
----|---
-`ok`| `true` to allow. `false` produces a `decision: "block"`. See the per-event behavior below
-`reason`| Required when `ok` is `false`. Used as the block reason
-
-What happens on `ok: false` depends on the event:
-
- * `Stop` and `SubagentStop`: the reason is fed back to Claude as its next instruction and the turn continues
- * `PreToolUse`: the tool call is denied; by default the turn ends and the deny reason appears in the chat as a warning line. Set `continueOnBlock: true` to instead return the reason to Claude as the tool error so it can adjust and continue, equivalent to a command hook’s `permissionDecision: "deny"`. Before v2.1.210, the deny reason was returned to Claude as the tool error and the turn continued
- * `PostToolUse`: by default the turn ends and the reason appears in the chat as a warning line. Set `continueOnBlock: true` to feed the reason back to Claude and continue the turn instead
- * `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears as a warning line. These events end the turn on `decision: "block"` regardless of `continue`
- * `PostToolUseFailure` and `TaskCreated`: the reason is returned to Claude as a tool error and the turn continues, regardless of `continueOnBlock`
- * `TaskCompleted`: when it fires because a task is marked completed during a turn, the reason is returned to Claude as a tool error and the turn continues, regardless of `continueOnBlock`. When it fires because a teammate stops, it behaves like `TeammateIdle` and halts the teammate by default
- * `TeammateIdle`: by default the teammate stops and the reason appears as a warning line. Set `continueOnBlock: true` to feed the reason back to the teammate and keep it working instead
- * `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
- * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks can’t set. They run on this event, but their output is discarded. Use a command hook to return `retry`
-
-If you need finer control on any event, use a command hook with the per-event fields described in Decision control.
-
-###
-
-
-
-Check multiple conditions before stopping
-
-This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. `SubagentStop` hooks use the same format to evaluate whether a [subagent](</docs/en/sub-agents>) should stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction:
-
- {
- "hooks": {
- "Stop": [
- {
- "hooks": [
- {
- "type": "prompt",
- "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.",
- "timeout": 30
- }
- ]
- }
- ]
- }
- }
-
-##
-
-
-
-Agent-based hooks
-
-Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer command hooks.
-
-Agent-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.
-
-###
-
-
-
-How agent hooks work
-
-When an agent hook fires:
-
- 1. Claude Code spawns a subagent with your prompt and the hook’s JSON input
- 2. The subagent can use tools like Read, Grep, and Glob to investigate
- 3. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision
- 4. Claude Code processes the decision the same way as a prompt hook
-
-Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.
-
-###
-
-
-
-Agent hook configuration
-
-Set `type` to `"agent"` and provide a `prompt` string. The configuration fields are the same as prompt hooks, with a longer default timeout:
-
-Field| Required| Description
----|---|---
-`type`| yes| Must be `"agent"`
-`prompt`| yes| Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON
-`model`| no| Model to use. Defaults to a fast model
-`timeout`| no| Timeout in seconds. Default: 60
-
-The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block. This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
-
- {
- "hooks": {
- "Stop": [
- {
- "hooks": [
- {
- "type": "agent",
- "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",
- "timeout": 120
- }
- ]
- }
- ]
- }
- }
-
-##
-
-
-
-Run hooks in the background
-
-By 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 can’t 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.
-
-###
-
-
-
-Configure an async hook
-
-Add `"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. This 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:
-
- {
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Write",
- "hooks": [
- {
- "type": "command",
- "command": "/path/to/run-tests.sh",
- "async": true,
- "timeout": 120
- }
- ]
- }
- ]
- }
- }
-
-The `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. You receive an async hook’s results only while the session runs:
-
- * In [non-interactive mode](</docs/en/headless>) with the `-p` flag, Claude Code kills any async hook still running at teardown and finalizes it with outcome `cancelled`
- * If your hook’s work must outlive a `claude -p` session, start a fully detached process from it
-
-###
-
-
-
-How async hooks execute
-
-When 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. After the background process exits, if the hook produced a JSON response with an `additionalContext` field, that content is delivered to Claude as context on the next conversation turn. A `systemMessage` field is shown to you, not to Claude. Claude Code validates that JSON response against the same output schema as synchronous hooks, and drops any field whose value has the wrong type, such as a `systemMessage` that isn’t a string, instead of delivering it. Run with `--debug` to see a warning naming each dropped field. Before v2.1.202, malformed JSON output from an async hook could crash the session, and the crash recurred each time the session was resumed. Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
-
-###
-
-
-
-Run tests after file changes
-
-This 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`:
-
- #!/bin/bash
- # run-tests-async.sh
-
- # Read hook input from stdin
- INPUT=$(cat)
- FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
-
- # Only run tests for source files
- if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
- exit 0
- fi
-
- # Run tests and report results to Claude via additionalContext
- RESULT=$(npm test 2>&1)
- EXIT_CODE=$?
-
- if [ $EXIT_CODE -eq 0 ]; then
- MSG="Tests passed after editing $FILE_PATH"
- else
- MSG="Tests failed after editing $FILE_PATH: $RESULT"
- fi
- jq -nc --arg msg "$MSG" '{hookSpecificOutput: {hookEventName: "PostToolUse", additionalContext: $msg}}'
-
-Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:
-
- {
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Write|Edit",
- "hooks": [
- {
- "type": "command",
- "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/run-tests-async.sh",
- "args": [],
- "async": true,
- "timeout": 300
- }
- ]
- }
- ]
- }
- }
-
-###
-
-
-
-Limitations
-
-Async hooks have additional constraints compared to synchronous hooks:
-
- * Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction. Exception: an `asyncRewake` hook that exits with code 2 wakes Claude immediately even when the session is idle.
- * Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
-
-##
-
-
-
-Security considerations
-
-###
-
-
-
-Disclaimer
-
-Command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration.
-
-###
-
-
-
-Security best practices
-
-Keep these practices in mind when writing hooks:
-
- * **Validate and sanitize inputs** : never trust input data blindly
- * **Always quote shell variables** : use `"$VAR"` not `$VAR`
- * **Block path traversal** : check for `..` in file paths
- * **Use absolute paths** : specify full paths for scripts. In exec form, use `${CLAUDE_PROJECT_DIR}` and the path needs no quoting. In shell form, wrap it in double quotes
- * **Skip sensitive files** : avoid `.env`, `.git/`, keys, etc.
-
-##
-
-
-
-Windows PowerShell tool
-
-On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Claude Code auto-detects `pwsh.exe`, the PowerShell 7 and later executable, and falls back to `powershell.exe` for Windows PowerShell 5.1.
-
- {
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Write",
- "hooks": [
- {
- "type": "command",
- "shell": "powershell",
- "command": "Write-Host 'File written'"
- }
- ]
- }
- ]
- }
- }
-
-To reference the project root from a PowerShell shell-form command, write `${CLAUDE_PROJECT_DIR}` or `$env:CLAUDE_PROJECT_DIR`. As of v2.1.198, Claude Code rewrites the `${CLAUDE_PROJECT_DIR}`, `${CLAUDE_PLUGIN_ROOT}`, and `${CLAUDE_PLUGIN_DATA}` placeholders in a PowerShell shell-form command to PowerShell’s `${env:NAME}` form, whether the hook is defined in `settings.json`, a plugin, or a skill. PowerShell then resolves the value from the exported environment after parsing, so the placeholder works inside double-quoted strings but not inside single-quoted strings, where PowerShell never expands variables. Before v2.1.198, this rewrite applied only to plugin hooks. On earlier versions, a `settings.json` hook needs the `$env:` form or exec form, where `${CLAUDE_PROJECT_DIR}` is substituted in each `args` element regardless of where the hook is defined. Don’t write the bare `$CLAUDE_PROJECT_DIR` spelling in a PowerShell hook. PowerShell parses it as an undefined local variable and resolves it to `$null`, which leaves the script path without its project-root prefix. Claude Code doesn’t rewrite that form; it logs a warning in the debug log instead. The example below shows a `settings.json` hook that runs a project script with the `$env:` form, which works on every version:
-
- {
- "type": "command",
- "shell": "powershell",
- "command": "& \"$env:CLAUDE_PROJECT_DIR\\.claude\\hooks\\check.ps1\""
- }
-
-##
-
-
-
-Debug hooks
-
-Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag doesn’t print to the terminal. For example, a `PostToolUse` hook on `Write` whose command prints `hook-ran` produces entries like:
-
- 2026-07-19T02:03:24.382Z [DEBUG] Hook output does not start with {, treating as plain text
- 2026-07-19T02:03:24.382Z [DEBUG] Hook PostToolUse:Write (PostToolUse) success:
- hook-ran
-
-For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, Stop hooks that keep blocking, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide. For a broader diagnostic walkthrough covering `/context`, `/doctor`, and settings precedence, see [Debug your config](</docs/en/debug-your-config>).
+Related resources
+
+ * [Claude Code hooks reference](</docs/en/hooks>): full JSON input/output schemas, event documentation, and matcher patterns
+ * [Claude Code hooks guide](</docs/en/hooks-guide>): shell command hook examples and walkthroughs
+ * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>): hook types, input/output definitions, and configuration options
+ * [Python SDK reference](</docs/en/agent-sdk/python>): hook types, input/output definitions, and configuration options
+ * [Permissions](</docs/en/agent-sdk/permissions>): control what your agent can do
+ * [Custom tools](</docs/en/agent-sdk/custom-tools>): build tools to extend agent capabilities
--- a/hooks.md
+++ b/hooks.md
@@ -2516,7 +2516,13 @@
DirectoryAdded
-Runs after a working directory is added mid-session, with the `/add-dir` command or the SDK `register_repo_root` control request. Use this to prepare a newly added repository, for example by installing its dependencies. Claude Code doesn’t fire this event for directories you pass with the `--add-dir` startup flag; SessionStart covers those. DirectoryAdded fires after Claude Code has refreshed sandbox and permission state, so sandboxed tools already see the new directory when your hook runs. Hook commands themselves run unsandboxed. The matcher filters on how the directory was added:
+Runs after you add a working directory mid-session with the `/add-dir` command, or after an SDK client adds one with the `register_repo_root` control request. Use this to prepare a newly added repository, for example by installing its dependencies. Claude Code doesn’t fire this event when:
+
+ * You pass a directory with the `--add-dir` startup flag; SessionStart covers those directories
+ * You add a directory on the `/permissions` Workspace tab
+ * You add a directory that is already a working directory; the add fails with an error
+
+Claude Code fires DirectoryAdded after refreshing sandbox and permission state, so sandboxed tools already see the new directory when your hook runs. Hook commands themselves run unsandboxed. Claude Code doesn’t wait for the hook: the add completes immediately, and the hook runs in the background with the 600-second default timeout. The matcher filters on how the directory was added:
Matcher| When it fires
---|---
Show diff (191 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -1,6 +1,6 @@
For a quickstart guide with examples, see [Automate actions with hooks](</docs/en/hooks-guide>).
-Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Hooks run wherever Claude Code runs: sessions in the terminal, IDE extensions, the [Desktop app](</docs/en/desktop-quickstart>), and [Claude Code on the web](</docs/en/claude-code-on-the-web>) all fire the same hook events. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you’re setting up hooks for the first time, start with the [guide](</docs/en/hooks-guide>) instead.
+Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Hooks run wherever Claude Code runs: sessions in the terminal, IDE extensions, the [Desktop app](</docs/en/desktop-quickstart>), and [Claude Code on the web](</docs/en/claude-code-on-the-web>) all fire the same hook events. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks.
##
@@ -237,7 +237,7 @@
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
-Cloud sessions on [Claude Code on the web](</docs/en/claude-code-on-the-web>) don’t read your local `~/.claude/settings.json`; hooks there come from the repo and from your organization’s server-managed settings. See [what carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) for which files reach a cloud session. For details on settings file resolution, see [settings](</docs/en/settings>). Hooks from settings files, managed policy settings, and plugins also run inside [subagents](</docs/en/sub-agents>). When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type` common input fields that identify the subagent. Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt, so administrators can distribute vetted hooks through an organization marketplace. See [Hook configuration](</docs/en/settings#hook-configuration>). Hook entries merge across settings levels rather than replacing each other: user, project, and local settings add their own hooks without removing managed ones, and the `disableAllHooks` setting can’t disable managed hooks from outside managed settings. The [HTTP hook allowlists](</docs/en/settings#hook-configuration>) apply to hooks from every source, including managed policy settings:
+Cloud sessions on [Claude Code on the web](</docs/en/claude-code-on-the-web>) don’t read your local `~/.claude/settings.json`; hooks there come from the repo and from your organization’s server-managed settings. See [what carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) for which files reach a cloud session. For details on settings file resolution, see [settings](</docs/en/settings>). Hooks from settings files, managed policy settings, and plugins also run inside [subagents](</docs/en/sub-agents>). When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type` common input fields that identify the subagent. Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt. See [Hook configuration](</docs/en/settings#hook-configuration>). Hook entries merge across settings levels rather than replacing each other: user, project, and local settings add their own hooks without removing managed ones, and the `disableAllHooks` setting can’t disable managed hooks from outside managed settings. The [HTTP hook allowlists](</docs/en/settings#hook-configuration>) apply to hooks from every source, including managed policy settings:
* `allowedHttpHookUrls`: when defined at any settings level, Claude Code runs an HTTP hook handler only if its URL matches the merged allowlist
* `httpHookAllowedEnvVars`: when defined, Claude Code interpolates only the environment variables on that list into hook headers
@@ -297,7 +297,7 @@
}
}
-`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `MessageDisplay`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
+If you add a `matcher` field to an event without matcher support, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
####
@@ -443,7 +443,7 @@
`headers`| no| Additional HTTP headers as key-value pairs. Values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in `allowedEnvVars` are resolved
`allowedEnvVars`| no| List of environment variable names that may be interpolated into header values. References to unlisted variables are replaced with empty strings. Required for any env var interpolation to work
-Claude Code sends the hook’s JSON input as the POST request body with `Content-Type: application/json`. The response body uses the same JSON output format as command hooks. Error handling differs from command hooks: non-2xx responses, connection failures, and timeouts all produce non-blocking errors that allow execution to continue. To block a tool call or deny a permission, return a 2xx response with a JSON body containing `decision: "block"` or a `hookSpecificOutput` with `permissionDecision: "deny"`. This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
+Claude Code sends the hook’s JSON input as the POST request body with `Content-Type: application/json`. The response body uses the same JSON output format as command hooks. Error handling differs from command hooks; see HTTP response handling. This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
{
"hooks": {
@@ -525,7 +525,7 @@
* `${CLAUDE_PLUGIN_ROOT}`: the plugin’s installation directory, for scripts bundled with a [plugin](</docs/en/plugins>). Changes on each plugin update.
* `${CLAUDE_PLUGIN_DATA}`: the plugin’s [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>), for dependencies and state that should survive plugin updates.
-Prefer exec form for any hook that references a path placeholder. Exec form passes each `args` element as one argument with no shell tokenization, so paths with spaces or special characters need no quoting. In shell form, wrap each placeholder in double quotes.
+Prefer exec form for any hook that references a path placeholder. In shell form, wrap each placeholder in double quotes.
* Project scripts
@@ -650,7 +650,7 @@
Field| Description
---|---
`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
-`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), this is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. See SubagentStart for how to write a matcher against a plugin-scoped name.
+`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. See SubagentStart for the values custom and plugin subagents report and how to write a matcher against a plugin-scoped name.
Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value doesn’t change when you switch models with `/model` during a session. One set of variables is not inherited: Claude Code [removes `OTEL_*` exporter variables from every subprocess it spawns](</docs/en/monitoring-usage#administrator-configuration>), including hooks. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
@@ -737,7 +737,7 @@
`InstructionsLoaded`| No| Exit code is ignored
`MessageDisplay`| No| The original text is displayed
-For `SessionStart`, `Setup`, and `SubagentStart`, the exit code 2 stderr renders in the transcript as a `<hook name> hook error` notice, the same way a non-blocking error does. Claude doesn’t see it, and the session or subagent proceeds. For `SubagentStart`, the notice appears in the subagent’s own transcript, not in the parent conversation. As of Claude Code v2.1.199, `SessionStart`, `Setup`, and `SubagentStart` show exit code 2 stderr in the transcript. Earlier versions wrote it to the debug log only.
+For `SessionStart`, `Setup`, and `SubagentStart`, the exit code 2 stderr renders in the transcript as a `<hook name> hook error` notice, the same way a non-blocking error does. Claude doesn’t see it, and the session or subagent proceeds. For `SubagentStart`, the notice appears in the subagent’s own transcript, not in the parent conversation.
###
@@ -880,7 +880,7 @@
* PermissionRequest
-Used by `UserPromptSubmit`, `UserPromptExpansion`, `PostToolUse`, `PostToolUseFailure`, `PostToolBatch`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
+The only value for `decision` is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
{
"decision": "block",
@@ -1033,8 +1033,6 @@
exit 0
-Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
-
`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types don’t have access to this variable.
###
@@ -1138,7 +1136,7 @@
UserPromptSubmit
-Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. A `UserPromptSubmit` command, HTTP, or MCP tool hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. As of v2.1.196, the transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. Earlier versions cancel the hook with no notice. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `UserPromptSubmit` that reaches its timeout blocks the prompt with a message naming the hook and the timeout, because a callback there can be acting as a policy gate that must not fail open. The session continues. Before v2.1.208, a callback timeout on that event ended the turn with an execution error.
+Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. A `UserPromptSubmit` command, HTTP, or MCP tool hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. The transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `UserPromptSubmit` that reaches its timeout blocks the prompt with a message naming the hook and the timeout, because a callback there can be acting as a policy gate that must not fail open. The session continues. Before v2.1.208, a callback timeout on that event ended the turn with an execution error.
####
@@ -1322,8 +1320,6 @@
#!/bin/bash
jq '{hookSpecificOutput: {hookEventName: "MessageDisplay", displayContent: (.delta | gsub("\\*\\*"; "") | gsub("`"; ""))}}'
-
-The script needs `jq` on your `PATH`.
Register a command hook that runs the script through PowerShell:
@@ -1577,7 +1573,7 @@
}
}
-`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) prompt even when a hook returns `"allow"`. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs.
+`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs.
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.
@@ -1818,13 +1814,12 @@
Field| Description
---|---
`error`| String describing what went wrong. The format depends on the tool that failed
-`is_interrupt`| Optional boolean. True when the failure reached Claude Code as an abort rather than as an error the tool reported; the shell tools convert mid-run cancellations into ordinary exit-code errors, so an exit-code payload carries `is_interrupt: false` even when the command was cancelled
+`is_interrupt`| Optional boolean. True when the failure reached Claude Code as an abort rather than as an error the tool reported. Cancelling a running tool does not fire this hook; the tool result carries the interruption message instead
`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks
The `error` string is generally the same text Claude receives as the failed tool’s result. Its format varies by tool and failure. Key your hook on `tool_name`, `is_interrupt`, and the `Exit code N` first line; treat the rest of the string as display text, not a stable format.
* For Bash and PowerShell, a command that ran and exited produces a first line `Exit code N`, then any output the command produced as one block with stdout and stderr interleaved
- * The line `[Request interrupted by user for tool use]` appears when the command was cancelled while running
* A payload may also carry a bare failure message with no exit-code line, when Claude Code could not start the shell process itself
* Claude Code middle-truncates strings longer than 10,000 characters around a `... [N characters truncated] ...` marker, and can insert lines of its own, such as `Command timed out after 2m 0s`
@@ -2105,7 +2100,7 @@
TaskCreated
-Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks don’t support matchers and fire on every occurrence.
+Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. TaskCreated hooks don’t support matchers and fire on every occurrence.
####
@@ -2166,7 +2161,7 @@
TaskCompleted
-Runs 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](</docs/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. When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks don’t support matchers and fire on every occurrence.
+Runs 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](</docs/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. TaskCompleted hooks don’t support matchers and fire on every occurrence.
####
@@ -2358,7 +2353,7 @@
TeammateIdle
-Runs when an [agent team](</docs/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. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks don’t support matchers and fire on every occurrence.
+Runs when an [agent team](</docs/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. TeammateIdle hooks don’t support matchers and fire on every occurrence.
####
@@ -2990,7 +2985,7 @@
Prompt hook configuration
-Set `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. This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
+Set `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. This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
{
"hooks": {
@@ -3234,10 +3229,8 @@
Limitations
-Async hooks have several constraints compared to synchronous hooks:
-
- * Only `type: "command"` hooks support `async`. Prompt-based hooks can’t run asynchronously.
- * Async hooks can’t block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
+Async hooks have additional constraints compared to synchronous hooks:
+
* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction. Exception: an `asyncRewake` hook that exits with code 2 wakes Claude immediately even when the session is idle.
* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
@@ -3252,8 +3245,6 @@
Disclaimer
-
-Command hooks run with your system user’s full permissions.
Command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration.
@@ -3277,7 +3268,7 @@
Windows PowerShell tool
-On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe`, the PowerShell 7 and later executable, and falls back to `powershell.exe` for Windows PowerShell 5.1.
+On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Claude Code auto-detects `pwsh.exe`, the PowerShell 7 and later executable, and falls back to `powershell.exe` for Windows PowerShell 5.1.
{
"hooks": {
--- a/hooks.md
+++ b/hooks.md
@@ -679,7 +679,7 @@
Exit code output
-The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. A hook that exits 2 while printing JSON that fails JSON output schema validation still blocks: Claude Code uses stderr as the blocking reason and records the validation failure in the debug log. Before v2.1.214, Claude Code treated that combination as a non-blocking error and the action proceeded. **Any other exit code** is a non-blocking error for most hook events. The action proceeds, and the transcript shows a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable debug logging. For example, a hook command script that blocks dangerous Bash commands:
+The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. Stderr from a hook that exits 0 goes to the debug log only, never the transcript, and Claude never sees it. To read it yourself, enable debug logging. To surface a warning to Claude from a `PostToolUse` or `PostToolUseFailure` hook, exit 2 instead so Claude sees the stderr even though the tool already ran. **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 for the full list. A hook that exits 2 while printing JSON that fails JSON output schema validation still blocks: Claude Code uses stderr as the blocking reason and records the validation failure in the debug log. Before v2.1.214, Claude Code treated that combination as a non-blocking error and the action proceeded. **Any other exit code** is a non-blocking error for most hook events. The action proceeds, and the transcript shows a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable debug logging. For example, a hook command script that blocks dangerous Bash commands:
#!/bin/bash
# Reads JSON input from stdin, checks the command
@@ -1380,7 +1380,26 @@
PreToolUse input
-In addition to the common input fields, PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool:
+In addition to the common input fields, PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. For the file tools `Write`, `Edit`, and `Read`, `tool_input.file_path` is always absolute:
+
+ * Claude Code expands `~` and relative paths before hooks run, so a hook that matches on paths can’t be bypassed via `~` or a relative spelling of the same path
+ * On Windows, the path arrives with backslash separators, even when your hook runs under Git Bash where `$PWD` looks like `/c/project`
+ * A comparison written with forward slashes, such as a `/src/` check, never matches a backslash path, and the tool call proceeds as if the hook had nothing to block
+ * Normalize separators before comparing: `FILE_PATH="${FILE_PATH//\\//}"` in Bash, or `file_path.replace("\\", "/")` in Python, then match a path segment such as `/src/` rather than anchoring with `^`, since the path is absolute
+
+A `Write` call on Windows delivers:
+
+ {
+ "hook_event_name": "PreToolUse",
+ "tool_name": "Write",
+ "tool_input": {
+ "file_path": "C:\\project\\src\\index.ts",
+ "content": "..."
+ },
+ ...
+ }
+
+The `tool_input` fields depend on the tool:
##### Bash
@@ -1703,7 +1722,7 @@
PostToolUse input
-`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.
+`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. File-tool `tool_input` paths arrive in the same format as for PreToolUse: always absolute, with the platform’s native separators, so backslashes on Windows.
{
"session_id": "abc123",
@@ -2649,9 +2668,9 @@
* you exit a `--worktree` session and choose to remove it
* a subagent with `isolation: "worktree"` finishes
- * you delete a [background session](</docs/en/agent-view#organize-the-list>) whose worktree the hook created
-
-For git-based worktrees, Claude Code 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. For a background-session delete, Claude Code verifies the stored worktree path before running the hook and refuses a path that is a symlink or passes through one below the repository root. The hook runs for a worktree that still contains files only when you confirm the delete in [agent view](</docs/en/agent-view#organize-the-list>); for such a worktree, [`claude rm`](</docs/en/agent-view#manage-sessions-from-the-shell>) keeps the session and worktree instead. Before v2.1.216, the hook ran on the stored path without these checks. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
+ * you delete a [background session](</docs/en/agent-view#what-deleting-a-session-removes>) whose worktree the hook created
+
+For git-based worktrees, Claude Code 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. For a background-session delete, Claude Code verifies the stored worktree path before running the hook and refuses a path that is a symlink or passes through one below the repository root. The hook runs for a worktree that still contains files only when you confirm the delete in [agent view](</docs/en/agent-view#what-deleting-a-session-removes>); for such a worktree, [`claude rm`](</docs/en/agent-view#manage-sessions-from-the-shell>) keeps the session and worktree instead. Before v2.1.216, the hook ran on the stored path without these checks. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
{
"hooks": {
Show diff (209 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -1,6 +1,6 @@
For a quickstart guide with examples, see [Automate actions with hooks](</docs/en/hooks-guide>).
-Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you’re setting up hooks for the first time, start with the [guide](</docs/en/hooks-guide>) instead.
+Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Hooks run wherever Claude Code runs: sessions in the terminal, IDE extensions, the [Desktop app](</docs/en/desktop-quickstart>), and [Claude Code on the web](</docs/en/claude-code-on-the-web>) all fire the same hook events. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you’re setting up hooks for the first time, start with the [guide](</docs/en/hooks-guide>) instead.
##
@@ -56,7 +56,13 @@
How a hook resolves
-To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The `matcher` narrows to Bash tool calls and the `if` condition narrows further to Bash subcommands matching `rm *`, so `block-rm.sh` only spawns when both filters match:
+To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands.
+
+ * macOS/Linux
+
+ * Windows (PowerShell)
+
+The `matcher` narrows to Bash tool calls and the `if` condition narrows further to Bash subcommands matching `rm *`, so `block-rm.sh` only spawns when both filters match:
{
"hooks": {
@@ -76,7 +82,7 @@
}
}
-The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`. Save it to `.claude/hooks/block-rm.sh` in your project:
+The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`. Save it to `.claude/hooks/block-rm.sh` in your project and make it executable with `chmod +x .claude/hooks/block-rm.sh` so Claude Code can run it:
#!/bin/bash
# .claude/hooks/block-rm.sh
@@ -94,7 +100,65 @@
exit 0 # no decision; normal permission flow applies
fi
-On macOS and Linux, make the script executable with `chmod +x .claude/hooks/block-rm.sh` so Claude Code can run it. On Windows, write the hook in PowerShell instead and register it with `"command": "powershell.exe"`, as shown in the MessageDisplay example. This script and the Bash examples on this page that parse JSON input use `jq`, so install `jq` and make sure it is on your `PATH` before trying them. Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here’s what happens:
+This script, like the other Bash examples on this page that parse JSON input, uses `jq`, so install `jq` and make sure it is on your `PATH` before trying them.
+
+The matcher `Bash|PowerShell` covers the PowerShell tool as well as Bash. A single `if` rule matches only one tool’s calls, so each tool gets its own handler: the first narrows to Bash subcommands matching `rm *`, the second to PowerShell commands matching `Remove-Item *`. Both run the same script through `powershell.exe`:
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Bash|PowerShell",
+ "hooks": [
+ {
+ "type": "command",
+ "if": "Bash(rm *)",
+ "command": "powershell.exe",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"
+ ]
+ },
+ {
+ "type": "command",
+ "if": "PowerShell(Remove-Item *)",
+ "command": "powershell.exe",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The `-NoProfile` flag skips loading your PowerShell profile so the hook starts fast, and `-ExecutionPolicy Bypass` lets PowerShell run the local script file.The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf` or `Remove-Item` followed by `-Recurse`. Save it to `.claude/hooks/block-rm.ps1` in your project:
+
+ # .claude/hooks/block-rm.ps1
+ $callInput = [Console]::In.ReadToEnd() | ConvertFrom-Json
+ $command = $callInput.tool_input.command
+
+ if ($command -match 'rm -rf|Remove-Item.*-Recurse') {
+ @{
+ hookSpecificOutput = @{
+ hookEventName = "PreToolUse"
+ permissionDecision = "deny"
+ permissionDecisionReason = "Destructive command blocked by hook"
+ }
+ } | ConvertTo-Json
+ } else {
+ exit 0 # no decision; normal permission flow applies
+ }
+
+Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"` against the macOS/Linux config. Here’s what happens:
1
@@ -173,7 +237,7 @@
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
-For details on settings file resolution, see [settings](</docs/en/settings>). Hooks from settings files, managed policy settings, and plugins also run inside [subagents](</docs/en/sub-agents>). When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type` common input fields that identify the subagent. Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt, so administrators can distribute vetted hooks through an organization marketplace. See [Hook configuration](</docs/en/settings#hook-configuration>). Hook entries merge across settings levels rather than replacing each other: user, project, and local settings add their own hooks without removing managed ones, and the `disableAllHooks` setting can’t disable managed hooks from outside managed settings. The [HTTP hook allowlists](</docs/en/settings#hook-configuration>) apply to hooks from every source, including managed policy settings:
+Cloud sessions on [Claude Code on the web](</docs/en/claude-code-on-the-web>) don’t read your local `~/.claude/settings.json`; hooks there come from the repo and from your organization’s server-managed settings. See [what carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) for which files reach a cloud session. For details on settings file resolution, see [settings](</docs/en/settings>). Hooks from settings files, managed policy settings, and plugins also run inside [subagents](</docs/en/sub-agents>). When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type` common input fields that identify the subagent. Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt, so administrators can distribute vetted hooks through an organization marketplace. See [Hook configuration](</docs/en/settings#hook-configuration>). Hook entries merge across settings levels rather than replacing each other: user, project, and local settings add their own hooks without removing managed ones, and the `disableAllHooks` setting can’t disable managed hooks from outside managed settings. The [HTTP hook allowlists](</docs/en/settings#hook-configuration>) apply to hooks from every source, including managed policy settings:
* `allowedHttpHookUrls`: when defined at any settings level, Claude Code runs an HTTP hook handler only if its URL matches the merged allowlist
* `httpHookAllowedEnvVars`: when defined, Claude Code interpolates only the environment variables on that list into hook headers
@@ -294,7 +358,7 @@
* **Prompt hooks** (`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.
* **Agent hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks.
-All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI. As of v2.1.199, [`$CLAUDE_CODE_BRIDGE_SESSION_ID`](</docs/en/env-vars>) is set to the [Remote Control](</docs/en/remote-control>) session ID while the local session has an active Remote Control connection.
+All matching hooks run in parallel. If you define the same handler in more than one settings file, it runs once. A plugin’s or skill’s copy of the same handler stays separate. 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. As of v2.1.199, [`$CLAUDE_CODE_BRIDGE_SESSION_ID`](</docs/en/env-vars>) is set to the [Remote Control](</docs/en/remote-control>) session ID while the local session has an active Remote Control connection.
####
@@ -701,7 +765,7 @@
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.
-Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. Hook output strings, including `additionalContext`, `systemMessage`, and plain stdout, are capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way large tool results are handled. The JSON object supports three kinds of fields:
+Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. Hook output strings, including `additionalContext`, `systemMessage`, and plain stdout, are capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way a large valid Bash result is handled under [Output limits](</docs/en/tools-reference#output-limits>). The JSON object supports three kinds of fields:
* **Universal fields** like `continue` work across all events. These are listed in the table below.
* **Top-level`decision` and `reason`** are used by some events to block or provide feedback.
@@ -1304,7 +1368,7 @@
PreToolUse
-Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names.
+Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `PowerShell`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names.
PreToolUse runs only when Claude calls a tool. Files you [reference with `@` in your prompt](</docs/en/common-workflows#reference-files-and-directories>) are added without any tool call: Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. To block specific paths from `@` references, use a [`Read` deny rule](</docs/en/permissions#read-and-edit>) instead.PreToolUse also doesn’t fire for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>).
@@ -1328,6 +1392,23 @@
`description`| string| `"Run test suite"`| Optional description of what the command does
`timeout`| number| `120000`| Optional timeout in milliseconds. Values above the [maximum](</docs/en/tools-reference#bash-tool-behavior>) are reduced to the maximum rather than rejected
`run_in_background`| boolean| `false`| Whether to run the command in background
+
+##### PowerShell
+
+Executes PowerShell commands. See the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) for availability by platform. The fields match the Bash tool, with the command string in `command`:
+
+Field| Type| Example| Description
+---|---|---|---
+`command`| string| `"Get-ChildItem -Recurse"`| The PowerShell command to execute
+`description`| string| `"List files recursively"`| Optional description of what the command does
+`timeout`| number| `120000`| Optional timeout in milliseconds
+`run_in_background`| boolean| `false`| Whether to run the command in background
+
+Match `Bash|PowerShell` in hooks that inspect shell commands, so they cover both tools:
+
+ * On Windows, wherever the PowerShell tool is enabled, Claude treats PowerShell as the primary shell and routes shell commands through it.
+ * On Windows without Git Bash, the tool is enabled automatically and Claude Code doesn’t register the Bash tool at all.
+ * A hook that matches only `Bash` never fires there.
##### Write
@@ -1696,7 +1777,7 @@
PostToolUseFailure input
-PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:
+PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields. For example, a failed `npm test` command might deliver:
{
"session_id": "abc123",
@@ -1710,16 +1791,23 @@
"description": "Run test suite"
},
"tool_use_id": "toolu_01ABC123...",
- "error": "Command exited with non-zero status code 1",
+ "error": "Exit code 1\nError: Cannot find module 'express'",
"is_interrupt": false,
"duration_ms": 4187
}
Field| Description
---|---
-`error`| String describing what went wrong
-`is_interrupt`| Optional boolean indicating whether the failure was caused by user interruption
+`error`| String describing what went wrong. The format depends on the tool that failed
+`is_interrupt`| Optional boolean. True when the failure reached Claude Code as an abort rather than as an error the tool reported; the shell tools convert mid-run cancellations into ordinary exit-code errors, so an exit-code payload carries `is_interrupt: false` even when the command was cancelled
`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks
+
+The `error` string is generally the same text Claude receives as the failed tool’s result. Its format varies by tool and failure. Key your hook on `tool_name`, `is_interrupt`, and the `Exit code N` first line; treat the rest of the string as display text, not a stable format.
+
+ * For Bash and PowerShell, a command that ran and exited produces a first line `Exit code N`, then any output the command produced as one block with stdout and stderr interleaved
+ * The line `[Request interrupted by user for tool use]` appears when the command was cancelled while running
+ * A payload may also carry a bare failure message with no exit-code line, when Claude Code could not start the shell process itself
+ * Claude Code middle-truncates strings longer than 10,000 characters around a `... [N characters truncated] ...` marker, and can insert lines of its own, such as `Command timed out after 2m 0s`
####
@@ -3056,7 +3144,10 @@
}
}
-The `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.
+The `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. You receive an async hook’s results only while the session runs:
+
+ * In [non-interactive mode](</docs/en/headless>) with the `-p` flag, Claude Code kills any async hook still running at teardown and finalizes it with outcome `cancelled`
+ * If your hook’s work must outlive a `claude -p` session, start a fully detached process from it
###
--- a/hooks.md
+++ b/hooks.md
@@ -615,7 +615,7 @@
Exit code output
-The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. A hook that exits 2 while printing JSON that fails JSON output schema validation still blocks: Claude Code uses stderr as the blocking reason and records the validation failure in the debug log. Before v2.1.214, Claude Code treated that combination as a non-blocking error and the action proceeded. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr, so you can identify the cause without `--debug`. Execution continues and the full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
+The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. A hook that exits 2 while printing JSON that fails JSON output schema validation still blocks: Claude Code uses stderr as the blocking reason and records the validation failure in the debug log. Before v2.1.214, Claude Code treated that combination as a non-blocking error and the action proceeded. **Any other exit code** is a non-blocking error for most hook events. The action proceeds, and the transcript shows a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable debug logging. For example, a hook command script that blocks dangerous Bash commands:
#!/bin/bash
# Reads JSON input from stdin, checks the command
--- a/hooks.md
+++ b/hooks.md
@@ -40,6 +40,7 @@
`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
`ConfigChange`| When a configuration file changes during a session
`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
+`DirectoryAdded`| When a working directory is added mid-session via `/add-dir` or the SDK `register_repo_root` control request
`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
`WorktreeCreate`| When a worktree is being created via `--worktree`, `isolation: "worktree"`, or for a background session. Replaces default git behavior
`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session
@@ -205,6 +206,7 @@
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`CwdChanged`| no matcher support| always fires on every directory change
+`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root`
`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env`
`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
@@ -660,6 +662,7 @@
`Setup`| No| Shows stderr to user only
`SessionEnd`| No| Shows stderr to user only
`CwdChanged`| No| Shows stderr to user only
+`DirectoryAdded`| No| Stderr goes to the debug log; the directory is already added
`FileChanged`| No| Shows stderr to user only
`PreCompact`| Yes| Blocks compaction
`PostCompact`| No| Shows stderr to user only
@@ -796,7 +799,7 @@
ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
MessageDisplay| `hookSpecificOutput`| `displayContent` replaces the displayed text on screen. Display-only: the transcript and what Claude sees keep the original
SessionStart, Setup, SubagentStart| Context only| `hookSpecificOutput.additionalContext` adds context for Claude. SessionStart also accepts `initialUserMessage`, `watchPaths`, `sessionTitle`, and `reloadSkills`. No blocking or decision control
-WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged| None| No decision control. Used for side effects like logging or cleanup
+WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, DirectoryAdded, FileChanged| None| No decision control. Used for side effects like logging or cleanup
A few events can also rewrite content rather than only allow or block it:
@@ -2409,6 +2412,46 @@
+DirectoryAdded
+
+Runs after a working directory is added mid-session, with the `/add-dir` command or the SDK `register_repo_root` control request. Use this to prepare a newly added repository, for example by installing its dependencies. Claude Code doesn’t fire this event for directories you pass with the `--add-dir` startup flag; SessionStart covers those. DirectoryAdded fires after Claude Code has refreshed sandbox and permission state, so sandboxed tools already see the new directory when your hook runs. Hook commands themselves run unsandboxed. The matcher filters on how the directory was added:
+
+Matcher| When it fires
+---|---
+`slash_command`| You add a directory with `/add-dir`
+`register_repo_root`| An SDK client adds a directory with the `register_repo_root` control request
+
+####
+
+
+
+DirectoryAdded input
+
+In addition to the common input fields, DirectoryAdded hooks receive `directory` and `source`.
+
+Field| Description
+---|---
+`directory`| Absolute path of the directory that was added
+`source`| How the directory was added, `"slash_command"` for `/add-dir` or `"register_repo_root"` for the SDK control request
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
+ "cwd": "/Users/my-project",
+ "hook_event_name": "DirectoryAdded",
+ "directory": "/Users/my-other-repo",
+ "source": "slash_command"
+ }
+
+DirectoryAdded hooks have no decision control. They can’t block the add, which has already completed when the hook runs. Claude Code surfaces hook output differently per source:
+
+ * `slash_command`: unlike on every other event, where you see the `systemMessage` and Claude doesn’t, Claude Code delivers the hook’s `systemMessage` to Claude as context on the next conversation turn. A count of failed hooks appears in the transcript; full failure output goes to the debug log
+ * `register_repo_root`: Claude Code writes `systemMessage` output and failure output to the debug log only
+
+###
+
+
+
FileChanged
Runs when a watched file changes on disk. Useful for reloading environment variables when project configuration files are modified. The `matcher` for this event serves two roles:
@@ -2806,6 +2849,7 @@
* `ConfigChange`
* `CwdChanged`
+ * `DirectoryAdded`
* `Elicitation`
* `ElicitationResult`
* `FileChanged`
--- a/hooks.md
+++ b/hooks.md
@@ -8,7 +8,7 @@
Hook lifecycle
-Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences:
+Claude Code runs hooks at specific points during a session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences:
* once per session: `SessionStart` and `SessionEnd`
* once per turn: `UserPromptSubmit`, `Stop`, and `StopFailure`
Show diff (103 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -23,7 +23,7 @@
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
-`PermissionRequest`| When a permission dialog appears
+`PermissionRequest`| When a tool call needs a permission decision
`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
`PostToolUse`| After a tool call succeeds
`PostToolUseFailure`| After a tool call fails
@@ -75,7 +75,7 @@
}
}
-The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:
+The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`. Save it to `.claude/hooks/block-rm.sh` in your project:
#!/bin/bash
# .claude/hooks/block-rm.sh
@@ -93,7 +93,7 @@
exit 0 # no decision; normal permission flow applies
fi
-This script and the Bash examples on this page that parse JSON input use `jq`, so install `jq` and make sure it is on your `PATH` before trying them. Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here’s what happens:
+On macOS and Linux, make the script executable with `chmod +x .claude/hooks/block-rm.sh` so Claude Code can run it. On Windows, write the hook in PowerShell instead and register it with `"command": "powershell.exe"`, as shown in the MessageDisplay example. This script and the Bash examples on this page that parse JSON input use `jq`, so install `jq` and make sure it is on your `PATH` before trying them. Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here’s what happens:
1
@@ -167,7 +167,7 @@
---|---|---
`~/.claude/settings.json`| All your projects| No, local to your machine
`.claude/settings.json`| Single project| Yes, can be committed to the repo
-`.claude/settings.local.json`| Single project| No, gitignored when Claude Code creates it
+`.claude/settings.local.json`| Single project| No, gitignored when Claude Code saves a setting to it
Managed policy settings| Organization-wide| Yes, admin-controlled
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
@@ -306,7 +306,7 @@
---|---|---
`type`| yes| `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"`
`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the Bash matching table below for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
-`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30, and `MessageDisplay` lowers it to 10
+`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30, and `MessageDisplay` lowers it to 10. `SessionEnd` hooks share a 1.5-second budget; if your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
@@ -536,12 +536,12 @@
Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook’s command, prompt, or URL. The menu displays all five hook types: `command`, `prompt`, `agent`, `http`, and `mcp_tool`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:
- * `User`: from `~/.claude/settings.json`
- * `Project`: from `.claude/settings.json`
- * `Local`: from `.claude/settings.local.json`
- * `Plugin`: from a plugin’s `hooks/hooks.json`
- * `Session`: registered in memory for the current session
- * `Built-in`: registered internally by Claude Code
+ * `User Settings`: from `~/.claude/settings.json`
+ * `Project Settings`: from `.claude/settings.json`
+ * `Local Settings`: from `.claude/settings.local.json`
+ * `Plugin Hooks`: from a plugin’s `hooks/hooks.json`
+ * `Session Hooks`: registered in memory for the current session
+ * `Built-in Hooks`: registered internally by Claude Code
Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.
@@ -617,7 +617,8 @@
#!/bin/bash
# Reads JSON input from stdin, checks the command
- command=$(jq -r '.tool_input.command' < /dev/stdin)
+ input=$(cat)
+ command=$(jq -r '.tool_input.command' <<<"$input")
if [[ "$command" == rm* ]]; then
echo "Blocked: rm commands are not allowed" >&2
@@ -982,7 +983,7 @@
`init`| `claude --init-only` or `claude -p --init`
`maintenance`| `claude -p --maintenance`
-`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p`; in an interactive session those two flags don’t currently fire Setup hooks. On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
+When you run `claude --init-only`, Claude Code runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when you combine them with `-p`. In an interactive session, those two flags don’t currently fire Setup hooks. When you start or continue a conversation with `-p`, you also need to supply a prompt, as an argument or piped on stdin. You can skip the prompt when a `SessionStart` hook supplies `initialUserMessage` or when you resume a session with a deferred tool call. On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
####
@@ -1515,7 +1516,7 @@
PermissionRequest
-Runs when the user is shown a permission dialog. Use PermissionRequest decision control to allow or deny on behalf of the user. Matches on tool name, same values as PreToolUse.
+Runs when Claude Code is about to ask you for permission. In sessions that can’t show a prompt, such as background subagents in [non-interactive mode](</docs/en/headless>), Claude Code still runs these hooks, and if no hook returns a decision, it denies the tool call. Use PermissionRequest decision control to allow or deny on behalf of the user. Matches on tool name, same values as PreToolUse.
####
@@ -1523,7 +1524,7 @@
PermissionRequest input
-PermissionRequest 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 from PreToolUse 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. Neither event fires for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>).
+PermissionRequest 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. PreToolUse hooks run before every tool call, whether or not it needs permission. PermissionRequest hooks run only when Claude Code is about to ask you for permission, or when it would otherwise auto-deny a call that can’t prompt. Neither event fires for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>).
{
"session_id": "abc123",
--- a/hooks.md
+++ b/hooks.md
@@ -172,7 +172,10 @@
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
-For details on settings file resolution, see [settings](</docs/en/settings>). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt, so administrators can distribute vetted hooks through an organization marketplace. See [Hook configuration](</docs/en/settings#hook-configuration>).
+For details on settings file resolution, see [settings](</docs/en/settings>). Hooks from settings files, managed policy settings, and plugins also run inside [subagents](</docs/en/sub-agents>). When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type` common input fields that identify the subagent. Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt, so administrators can distribute vetted hooks through an organization marketplace. See [Hook configuration](</docs/en/settings#hook-configuration>). Hook entries merge across settings levels rather than replacing each other: user, project, and local settings add their own hooks without removing managed ones, and the `disableAllHooks` setting can’t disable managed hooks from outside managed settings. The [HTTP hook allowlists](</docs/en/settings#hook-configuration>) apply to hooks from every source, including managed policy settings:
+
+ * `allowedHttpHookUrls`: when defined at any settings level, Claude Code runs an HTTP hook handler only if its URL matches the merged allowlist
+ * `httpHookAllowedEnvVars`: when defined, Claude Code interpolates only the environment variables on that list into hook headers
###
--- a/hooks.md
+++ b/hooks.md
@@ -594,11 +594,15 @@
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
- "command": "npm test"
- }
- }
-
-The `tool_name` and `tool_input` fields are event-specific. Each hook event section documents the additional fields for that event.
+ "command": "npm test",
+ "description": "Run test suite",
+ "timeout": 120000,
+ "run_in_background": false
+ },
+ "tool_use_id": "toolu_01ABC123..."
+ }
+
+The `tool_name`, `tool_input`, and `tool_use_id` fields are event-specific. Each hook event section documents the additional fields for that event.
###
@@ -1820,12 +1824,12 @@
"description": "Clean build directory"
},
"tool_use_id": "toolu_01ABC123...",
- "reason": "Auto mode denied: command targets a path outside the project"
+ "reason": "Blocked by classifier"
}
Field| Description
---|---
-`reason`| The classifier’s explanation for why the tool call was denied
+`reason`| The denial reason: the fixed text `Blocked by classifier` in most sessions, or the classifier’s written explanation when the session’s classifier model provides one. See [Review denials](</docs/en/auto-mode-config#review-denials>)
####
--- a/hooks.md
+++ b/hooks.md
@@ -523,7 +523,7 @@
command: "./scripts/security-check.sh"
---
-Agents use the same format in their YAML frontmatter.
+Subagents use the same format in their YAML frontmatter. Frontmatter hooks in a project subagent run only after you accept the [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) for the folder the agent file came from; see [which scopes are exempt](</docs/en/sub-agents#hooks-in-subagent-frontmatter>). Before v2.1.218, these hooks could run from folders you hadn’t trusted.
###
--- a/hooks.md
+++ b/hooks.md
@@ -2877,10 +2877,11 @@
What happens on `ok: false` depends on the event:
* `Stop` and `SubagentStop`: the reason is fed back to Claude as its next instruction and the turn continues
- * `PreToolUse`: the tool call is denied and the reason is returned to Claude as the tool error, equivalent to a command hook’s `permissionDecision: "deny"`
+ * `PreToolUse`: the tool call is denied; by default the turn ends and the deny reason appears in the chat as a warning line. Set `continueOnBlock: true` to instead return the reason to Claude as the tool error so it can adjust and continue, equivalent to a command hook’s `permissionDecision: "deny"`. Before v2.1.210, the deny reason was returned to Claude as the tool error and the turn continued
* `PostToolUse`: by default the turn ends and the reason appears in the chat as a warning line. Set `continueOnBlock: true` to feed the reason back to Claude and continue the turn instead
* `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears as a warning line. These events end the turn on `decision: "block"` regardless of `continue`
- * `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`
+ * `PostToolUseFailure` and `TaskCreated`: the reason is returned to Claude as a tool error and the turn continues, regardless of `continueOnBlock`
+ * `TaskCompleted`: when it fires because a task is marked completed during a turn, the reason is returned to Claude as a tool error and the turn continues, regardless of `continueOnBlock`. When it fires because a teammate stops, it behaves like `TeammateIdle` and halts the teammate by default
* `TeammateIdle`: by default the teammate stops and the reason appears as a warning line. Set `continueOnBlock: true` to feed the reason back to the teammate and keep it working instead
* `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
* `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks can’t set. They run on this event, but their output is discarded. Use a command hook to return `retry`
Show diff (171 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -12,7 +12,7 @@
* once per session: `SessionStart` and `SessionEnd`
* once per turn: `UserPromptSubmit`, `Stop`, and `StopFailure`
- * on every tool call inside the agentic loop: `PreToolUse` and `PostToolUse`
+ * on every tool call inside the agentic loop: `PreToolUse` and `PostToolUse`, except [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) calls, which skip both
The table below summarizes when each event fires. The Hook events section documents the full input schema and decision control options for each one.
@@ -41,8 +41,8 @@
`ConfigChange`| When a configuration file changes during a session
`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
-`WorktreeCreate`| When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior
-`WorktreeRemove`| When a worktree is being removed, either at session exit or when a subagent finishes
+`WorktreeCreate`| When a worktree is being created via `--worktree`, `isolation: "worktree"`, or for a background session. Replaces default git behavior
+`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session
`PreCompact`| Before context compaction
`PostCompact`| After context compaction completes
`Elicitation`| When an MCP server requests user input during a tool call
@@ -193,7 +193,7 @@
Event| What the matcher filters| Example matcher values
---|---|---
`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
-`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
+`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
@@ -307,7 +307,7 @@
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
-The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. For Bash patterns, whether your hook command runs depends on the shape of the pattern and the Bash command Claude is invoking. Leading `VAR=value` assignments are stripped before matching.
+The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. In an `if` condition for a file tool, a single-segment directory pattern like `"Edit(src/**)"` matches only the `src` directory in the working directory and the files under it. To match a directory named `src` at any depth, write `"Edit(**/src/**)"`. Before v2.1.214, `"Edit(src/**)"` matched a directory named `src` at any depth under the working directory. For Bash patterns, whether your hook command runs depends on the shape of the pattern and the Bash command Claude is invoking. Leading `VAR=value` assignments are stripped before matching.
`if` pattern| Bash command| Hook runs?| Why
---|---|---|---
@@ -606,7 +606,7 @@
Exit code output
-The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr, so you can identify the cause without `--debug`. Execution continues and the full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
+The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. A hook that exits 2 while printing JSON that fails JSON output schema validation still blocks: Claude Code uses stderr as the blocking reason and records the validation failure in the debug log. Before v2.1.214, Claude Code treated that combination as a non-blocking error and the action proceeded. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr, so you can identify the cause without `--debug`. Execution continues and the full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
#!/bin/bash
# Reads JSON input from stdin, checks the command
@@ -766,7 +766,7 @@
* **Conditional project rules** : which test command applies to the file just edited, which directories are read-only in this worktree
* **External data** : open issues assigned to you, recent CI results, content fetched from an internal service
-For instructions that never change, prefer [CLAUDE.md](</docs/en/memory>). It loads without running a script and is the standard place for static project conventions. Write the text as factual statements rather than imperative system instructions. Phrasing such as “The deployment target is production” or “This repo uses `bun test`” reads as project information. Text framed as out-of-band system commands can trigger Claude’s prompt-injection defenses, which causes Claude to surface the text to you instead of treating it as context. Once injected, the text is saved in the session transcript. For mid-session events like `PostToolUse` or `UserPromptSubmit`, resuming with `--continue` or `--resume` replays the saved text rather than re-running the hook for past turns, so values like timestamps or commit SHAs become stale on resume. `SessionStart` hooks run again on resume with `source` set to `"resume"`, so they can refresh their context.
+For instructions that never change, prefer [CLAUDE.md](</docs/en/memory>). It loads without running a script and is the standard place for static project conventions. Write the text as factual statements rather than imperative system instructions. Phrasing such as “The deployment target is production” or “This repo uses `bun test`” reads as project information. Text framed as out-of-band system commands can trigger Claude’s prompt-injection defenses, which causes Claude to surface the text to you instead of treating it as context. Claude Code saves the injected text in the session transcript. For mid-session events like `PostToolUse` or `UserPromptSubmit`, when you resume with `--continue` or `--resume`, Claude Code replays the saved text rather than re-running the hook for past turns, so values like timestamps or commit SHAs become stale. `SessionStart` hooks run again on resume with `source` set to `"resume"`, or `"fork"` if you added `--fork-session`, so they can refresh their context.
####
@@ -860,6 +860,9 @@
`resume`| `--resume`, `--continue`, or `/resume`
`clear`| `/clear`
`compact`| Auto or manual compaction
+`fork`| A new session forked from an existing one: `--fork-session` with `--resume` or `--continue`, the `/fork` background copy, or `/branch`
+
+Before v2.1.214, forked sessions reported source `"resume"`.
####
@@ -871,7 +874,7 @@
Field| Description
---|---
-`source`| How the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction
+`source`| How the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, `"compact"` after compaction, or `"fork"` for a new session forked from an existing one
`model`| The active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it
`agent_type`| The agent name, present when you start Claude Code with `claude --agent <name>`
`session_title`| The current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly
@@ -897,7 +900,7 @@
---|---
`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it
`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) with the `-p` flag, where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
-`sessionTitle`| Sets the session title, with the same effect as `/rename`. Use to name sessions automatically from the launch folder, git branch, or worktree name. Applies only when `source` is `"startup"` or `"resume"`; ignored on `"clear"` and `"compact"`
+`sessionTitle`| Sets the session title, with the same effect as `/rename`. Use to name sessions automatically from the launch folder, git branch, or worktree name. Applies when `source` is `"startup"`, `"resume"`, or `"fork"`; ignored on `"clear"` and `"compact"`
`watchPaths`| Array of absolute paths to watch for FileChanged events during this session
`reloadSkills`| Boolean. When `true`, Claude Code re-scans the [skill](</docs/en/skills>) and command directories after the SessionStart hooks complete, so skills the hook installed are available in the same session, starting with the first prompt
@@ -1292,7 +1295,7 @@
Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names.
-PreToolUse runs only when Claude calls a tool. Files you [reference with `@` in your prompt](</docs/en/common-workflows#reference-files-and-directories>) are added without any tool call: Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. To block specific paths from `@` references, use a [`Read` deny rule](</docs/en/permissions#read-and-edit>) instead.
+PreToolUse runs only when Claude calls a tool. Files you [reference with `@` in your prompt](</docs/en/common-workflows#reference-files-and-directories>) are added without any tool call: Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. To block specific paths from `@` references, use a [`Read` deny rule](</docs/en/permissions#read-and-edit>) instead.PreToolUse also doesn’t fire for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>).
Use PreToolUse decision control to allow, deny, ask, or defer the tool call. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `PreToolUse` that exceeds its timeout blocks the tool call, and Claude receives an error result naming the timeout. An explicit deny returned by another hook still takes precedence.
@@ -1404,13 +1407,14 @@
`status`| string| `"completed"`| `"completed"` for foreground subagents, `"async_launched"` for background subagents. As of v2.1.198, subagents run in the background by default, so an omitted `run_in_background` also produces `"async_launched"`
`agentId`| string| `"a4d2c8f1e0b3a297"`| Identifier for the subagent run
`content`| array| `[{"type": "text", "text": "Found 12 endpoints..."}]`| The subagent’s final text blocks
-`resolvedModel`| string| `"claude-sonnet-4-5"`| Model the subagent ran on, which may differ from the requested model. Requires Claude Code v2.1.174 or later
+`resolvedModel`| string| `"claude-sonnet-4-5"`| Model the subagent started on, which may differ from the requested model. Requires Claude Code v2.1.174 or later
+`modelsUsed`| array| `["claude-sonnet-4-5", "claude-haiku-4-5"]`| Models used in order, with consecutive repeats collapsed; set only when the model was swapped mid-run. Requires Claude Code v2.1.212 or later
`totalTokens`| number| `12450`| Total tokens billed across the subagent’s turns
`totalDurationMs`| number| `48211`| Wall-clock duration of the subagent run
`totalToolUseCount`| number| `7`| Count of tool calls the subagent made
`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`
-For background subagents, the tool returns immediately after launching, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later.
+For background subagents, the tool returns when the task moves to the background, so `tool_response` carries no usage fields: a background launch returns immediately, and a foreground task that Claude Code backgrounds mid-run returns at that transition. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. On a `completed` response, `resolvedModel` names the model the subagent started on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later. On an `async_launched` response, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later.
##### AskUserQuestion
@@ -1512,7 +1516,7 @@
PermissionRequest input
-PermissionRequest 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.
+PermissionRequest 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 from PreToolUse 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. Neither event fires for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>).
{
"session_id": "abc123",
@@ -2448,7 +2452,7 @@
WorktreeCreate
-Runs when a worktree is being created, either from `claude --worktree` or from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>). By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. See WorktreeCreate output for how each hook type returns the path. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+Runs when a worktree is being created, whether from `claude --worktree`, from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>), or for a [background session](</docs/en/agent-view#how-file-edits-are-isolated>) that Claude Code isolates in its own worktree. By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. See WorktreeCreate output for how each hook type returns the path. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
{
"hooks": {
@@ -2494,7 +2498,7 @@
* **Command hooks** (`type: "command"`): print the path as the last non-empty line of stdout. Claude Code strips ANSI escape codes before reading that line, so shell startup banners printed before your `echo` are ignored. Redirect any other hook output to stderr.
* **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
-If the hook fails or produces no path, worktree creation fails with an error. Claude Code resolves a relative path against the directory the hook ran in. If the resulting path isn’t a directory Claude Code can enter, the session prints an error naming the path and exits with code 1. Before v2.1.205, a relative path or a path that didn’t exist on disk crashed the session at startup, and with `-p` it stalled for about 30 seconds before exiting with code 0.
+If the hook fails or produces no path, worktree creation fails with an error. Claude Code resolves a relative path against the directory the hook ran in, collapsing any `.` or `..` segments in it. If the resulting path isn’t a directory Claude Code can enter, the session prints an error naming the path and exits with code 1. Before v2.1.205, a relative path or a path that didn’t exist on disk crashed the session at startup, and with `-p` it stalled for about 30 seconds before exiting with code 0. Claude Code refuses an absolute path that contains `.` or `..` segments, and any path that passes through a symlink below the repository root, because a symlink committed to the repository could redirect the worktree outside it. The error names the rejected component. Return a normalized path that doesn’t pass through a symlink inside the repository. Before v2.1.216, worktree creation followed the hook’s path without this screening.
###
@@ -2502,7 +2506,13 @@
WorktreeRemove
-Runs 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. This is the cleanup counterpart to WorktreeCreate. For git-based worktrees, Claude Code 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. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
+Runs when a worktree is being removed. This is the cleanup counterpart to WorktreeCreate. The event fires when:
+
+ * you exit a `--worktree` session and choose to remove it
+ * a subagent with `isolation: "worktree"` finishes
+ * you delete a [background session](</docs/en/agent-view#organize-the-list>) whose worktree the hook created
+
+For git-based worktrees, Claude Code 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. For a background-session delete, Claude Code verifies the stored worktree path before running the hook and refuses a path that is a symlink or passes through one below the repository root. The hook runs for a worktree that still contains files only when you confirm the delete in [agent view](</docs/en/agent-view#organize-the-list>); for such a worktree, [`claude rm`](</docs/en/agent-view#manage-sessions-from-the-shell>) keeps the session and worktree instead. Before v2.1.216, the hook ran on the stored path without these checks. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
{
"hooks": {
@@ -3137,11 +3147,10 @@
Debug hooks
-Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag doesn’t print to the terminal.
-
- [DEBUG] Executing hooks for PostToolUse:Write
- [DEBUG] Found 1 hook commands to execute
- [DEBUG] Executing hook command: <Your command> with timeout 600000ms
- [DEBUG] Hook command completed with status 0: <Your stdout>
+Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag doesn’t print to the terminal. For example, a `PostToolUse` hook on `Write` whose command prints `hook-ran` produces entries like:
+
+ 2026-07-19T02:03:24.382Z [DEBUG] Hook output does not start with {, treating as plain text
+ 2026-07-19T02:03:24.382Z [DEBUG] Hook PostToolUse:Write (PostToolUse) success:
+ hook-ran
For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, Stop hooks that keep blocking, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide. For a broader diagnostic walkthrough covering `/context`, `/doctor`, and settings precedence, see [Debug your config](</docs/en/debug-your-config>).
--- a/hooks.md
+++ b/hooks.md
@@ -708,6 +708,8 @@
{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
+For `PreToolUse` and `PostToolUse` hooks, the stop applies even when the tool call fails or completes while Claude is still streaming a response.
+
####
--- a/hooks.md
+++ b/hooks.md
@@ -93,7 +93,7 @@
exit 0 # no decision; normal permission flow applies
fi
-Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here’s what happens:
+This script and the Bash examples on this page that parse JSON input use `jq`, so install `jq` and make sure it is on your `PATH` before trying them. Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here’s what happens:
1
@@ -916,6 +916,8 @@
echo '{"hookSpecificOutput": {"hookEventName": "SessionStart", "reloadSkills": true}}'
+The repository URL is a placeholder; replace it with your own skills repository. With the placeholder, the clone fails and prints a `fatal:` message to stderr. Stderr from a SessionStart hook that exits 0 is informational only, so the `reloadSkills` request still applies.
+
####
@@ -968,7 +970,7 @@
`init`| `claude --init-only` or `claude -p --init`
`maintenance`| `claude -p --maintenance`
-`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p`; in an interactive session those two flags don’t currently fire Setup hooks. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
+`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p`; in an interactive session those two flags don’t currently fire Setup hooks. On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
####
@@ -1290,7 +1292,7 @@
PreToolUse runs only when Claude calls a tool. Files you [reference with `@` in your prompt](</docs/en/common-workflows#reference-files-and-directories>) are added without any tool call: Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. To block specific paths from `@` references, use a [`Read` deny rule](</docs/en/permissions#read-and-edit>) instead.
-Use PreToolUse decision control to allow, deny, ask, or defer the tool call.
+Use PreToolUse decision control to allow, deny, ask, or defer the tool call. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `PreToolUse` that exceeds its timeout blocks the tool call, and Claude receives an error result naming the timeout. An explicit deny returned by another hook still takes precedence.
####
@@ -1444,7 +1446,7 @@
`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
`additionalContext`| String added to Claude’s context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See Add context for Claude
-When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`. When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
+When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`. When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation. A hook’s `"ask"` also forces a permission prompt in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): the classifier can still deny the tool call, but it can’t approve the call silently. Before v2.1.211, the classifier could approve a Bash command running outside the [sandbox](</docs/en/sandboxing>) without showing the prompt the hook requested; the classifier still applied its own safety rules to that command, and a hook `"deny"` was always honored.
{
"hookSpecificOutput": {
@@ -1492,7 +1494,7 @@
There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
-`--resume` restores the permission mode that was active when the tool was deferred, so you don’t need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.
+`--resume` restores the permission mode that was active when the tool was deferred, so you don’t need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over, and `auto`, which is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Passing `--permission-mode` explicitly on resume overrides the restored value.
###
--- a/hooks.md
+++ b/hooks.md
@@ -583,7 +583,7 @@
`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), this is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. See SubagentStart for how to write a matcher against a plugin-scoped name.
-Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value doesn’t change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
+Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value doesn’t change when you switch models with `/model` during a session. One set of variables is not inherited: Claude Code [removes `OTEL_*` exporter variables from every subprocess it spawns](</docs/en/monitoring-usage#administrator-configuration>), including hooks. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
{
"session_id": "abc123",
@@ -1308,7 +1308,7 @@
---|---|---|---
`command`| string| `"npm test"`| The shell command to execute
`description`| string| `"Run test suite"`| Optional description of what the command does
-`timeout`| number| `120000`| Optional timeout in milliseconds
+`timeout`| number| `120000`| Optional timeout in milliseconds. Values above the [maximum](</docs/en/tools-reference#bash-tool-behavior>) are reduced to the maximum rather than rejected
`run_in_background`| boolean| `false`| Whether to run the command in background
##### Write
@@ -1439,7 +1439,7 @@
Field| Description
---|---
-`permissionDecision`| `"allow"` skips the permission prompt, except for tools that require user interaction. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
+`permissionDecision`| `"allow"` skips the permission prompt, except for tools that require user interaction and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>). `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored
`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
`additionalContext`| String added to Claude’s context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See Add context for Claude
@@ -1458,7 +1458,7 @@
}
}
-`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs.
+`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) prompt even when a hook returns `"allow"`. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs.
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.
--- a/hooks.md
+++ b/hooks.md
@@ -1056,7 +1056,7 @@
UserPromptSubmit
-Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. A `UserPromptSubmit` hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. As of v2.1.196, the transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. Earlier versions cancel the hook with no notice.
+Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. A `UserPromptSubmit` command, HTTP, or MCP tool hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. As of v2.1.196, the transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. Earlier versions cancel the hook with no notice. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `UserPromptSubmit` that reaches its timeout blocks the prompt with a message naming the hook and the timeout, because a callback there can be acting as a policy gate that must not fail open. The session continues. Before v2.1.208, a callback timeout on that event ended the turn with an execution error.
####
--- a/hooks.md
+++ b/hooks.md
@@ -356,7 +356,7 @@
"command": "node \"${CLAUDE_PLUGIN_ROOT}\"/scripts/format.js --fix"
}
-Both forms support the same path placeholders, and both export them as the environment variables `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, and `CLAUDE_PLUGIN_DATA` on the spawned process, so a script can read `process.env.CLAUDE_PLUGIN_ROOT` regardless of how it was launched. Plugin hooks additionally substitute `${user_config.*}` values; see [User configuration](</docs/en/plugins-reference#user-configuration>).
+Both forms support the same path placeholders, and both export them as the environment variables `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, and `CLAUDE_PLUGIN_DATA` on the spawned process, so a script can read `process.env.CLAUDE_PLUGIN_ROOT` regardless of how it was launched. Plugin hooks additionally substitute [`${user_config.*}`](</docs/en/plugins-reference#user-configuration>) values, in exec form only: the value is substituted into `command` and into each `args` element as a plain string, so no shell re-parses it. A shell-form plugin hook whose `command` references `${user_config.*}` fails with an [error](</docs/en/errors#plugin-command-references-user-config>) instead of running. To use an option value from a shell-form hook, read the `$CLAUDE_PLUGIN_OPTION_<KEY>` environment variable, such as `$CLAUDE_PLUGIN_OPTION_WEBHOOK_URL` for a `webhook_url` option, or set `args` to switch the hook to exec form. Before v2.1.207, shell-form plugin hook commands also substituted `${user_config.*}`.
In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and don’t trigger the warning.
@@ -1468,11 +1468,7 @@
Defer a tool call for later
-`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](</docs/en/headless>) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result.
-
-The `defer` value requires Claude Code v2.1.89 or later. Earlier versions don’t recognize it and the tool proceeds through the normal permission flow.
-
-The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:
+`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](</docs/en/headless>) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result. The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:
1. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires.
2. The hook returns `permissionDecision: "defer"`. The tool doesn’t execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
@@ -1671,7 +1667,9 @@
PostToolUseFailure
-Runs 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. Matches on tool name, same values as PreToolUse.
+Runs when a tool that started executing fails: the tool threw an error, or an MCP tool returned an error result. Use this to log failures, send alerts, or provide corrective feedback to Claude. Matches on tool name, same values as PreToolUse.
+
+This event doesn’t fire for tool calls rejected before execution: an unknown tool name, input that fails schema or tool-specific validation, or a permission denial. Validation rejections are returned as `tool_use_error` results and happen before hooks run, so they fire neither `PreToolUse` nor `PostToolUseFailure`. Permission denials fire `PreToolUse` but not this event; see PermissionDenied.
####
--- a/hooks.md
+++ b/hooks.md
@@ -1419,13 +1419,13 @@
##### ExitPlanMode
-Presents a plan and asks the user to approve it before Claude leaves [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). Claude writes the plan to a file on disk before calling the tool, so the literal `tool_input` from the model only carries `allowedPrompts`. Claude Code injects the plan content and file path before passing the input to hooks.
+Presents a plan and asks the user to approve it before Claude leaves [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). Claude writes the plan to a file on disk before calling the tool, so the literal `tool_input` from the model is typically empty. Claude Code injects the plan content and file path before passing the input to hooks.
Field| Type| Example| Description
---|---|---|---
`plan`| string| `"## Refactor auth\n1. Extract..."`| Plan content in Markdown. Injected from the plan file on disk
`planFilePath`| string| `"/Users/.../plans/refactor-auth.md"`| Path to the plan file. Injected
-`allowedPrompts`| array| `[{"tool": "Bash", "prompt": "run tests"}]`| Optional. Prompt-based permissions Claude is requesting to implement the plan, each with a `tool` name and a `prompt` describing the category of action
+`allowedPrompts`| array| `[{"tool": "Bash", "prompt": "run tests"}]`| Deprecated. Claude Code accepts the field but ignores it. Before v2.1.205, it carried prompt-based permissions Claude requested to implement the plan
In `PostToolUse`, `tool_response` is an object with `plan` and `filePath` fields holding the approved plan, plus internal status flags. Read `tool_response.plan` for the plan content rather than re-reading the file from disk.
@@ -2446,7 +2446,7 @@
WorktreeCreate
-Runs when a worktree is being created, either from `claude --worktree` or from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>). By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+Runs when a worktree is being created, either from `claude --worktree` or from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>). By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. See WorktreeCreate output for how each hook type returns the path. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
{
"hooks": {
@@ -2487,12 +2487,12 @@
WorktreeCreate output
-WorktreeCreate hooks don’t use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
-
- * **Command hooks** (`type: "command"`): print the path on stdout.
+WorktreeCreate hooks don’t use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the path to the created worktree directory:
+
+ * **Command hooks** (`type: "command"`): print the path as the last non-empty line of stdout. Claude Code strips ANSI escape codes before reading that line, so shell startup banners printed before your `echo` are ignored. Redirect any other hook output to stderr.
* **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
-If the hook fails or produces no path, worktree creation fails with an error.
+If the hook fails or produces no path, worktree creation fails with an error. Claude Code resolves a relative path against the directory the hook ran in. If the resulting path isn’t a directory Claude Code can enter, the session prints an error naming the path and exits with code 1. Before v2.1.205, a relative path or a path that didn’t exist on disk crashed the session at startup, and with `-p` it stalled for about 30 seconds before exiting with code 0.
###
--- a/hooks.md
+++ b/hooks.md
@@ -248,7 +248,7 @@
* `mcp__brave-search__.*` matches all tools from a server whose name contains a hyphen
* `mcp__.*__write.*` matches any tool whose name starts with `write` from any server
-Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a bare hyphenated prefix like `mcp__brave-search` is evaluated as an unanchored regular expression and matches every tool from that server. The `mcp__brave-search__.*` form works on every version. This example logs all memory server operations and validates write operations from any MCP server:
+Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a bare hyphenated prefix like `mcp__brave-search` is evaluated as an unanchored regular expression and matches every tool from that server. The `mcp__brave-search__.*` form works on every version. Tools from a [plugin-bundled MCP server](</docs/en/mcp#plugin-provided-mcp-servers>) use a scoped server segment that includes the plugin name: `mcp__plugin_<plugin-name>_<server-name>__<tool>`. A matcher written against the bare server key never fires for these tools. For a plugin named `my-plugin` that bundles a server under the key `db`, a `query` tool appears as `mcp__plugin_my-plugin_db__query`, so the matcher for every tool from that server is `mcp__plugin_my-plugin_db__.*`. Use the same scoped tool name in a handler’s `if` field. See [Plugin-provided MCP servers](</docs/en/mcp#plugin-provided-mcp-servers>) for how the scoped name is built. This example logs all memory server operations and validates write operations from any MCP server:
{
"hooks": {
@@ -407,7 +407,7 @@
Field| Required| Description
---|---|---
-`server`| yes| Name of a configured MCP server. The server must already be connected; the hook never triggers an OAuth or connection flow
+`server`| yes| Name of a configured MCP server. For a [plugin-bundled server](</docs/en/mcp#plugin-provided-mcp-servers>), this is the scoped name `plugin:<plugin-name>:<server-name>`, such as `plugin:my-plugin:db`, not the bare server key. The server must already be connected; the hook never triggers an OAuth or connection flow
`tool`| yes| Name of the tool to call on that server
`input`| no| Arguments passed to the tool. String values support `${path}` substitution from the hook’s JSON input, such as `"${tool_input.file_path}"`
@@ -570,7 +570,7 @@
---|---
`session_id`| Current session identifier
`prompt_id`| UUID identifying the user prompt currently being processed. Matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>), so you can correlate hook output with telemetry for a single prompt. Absent until the first user input. Requires Claude Code v2.1.196 or later
-`transcript_path`| Path to conversation JSON
+`transcript_path`| Path to conversation JSON. The transcript file is written asynchronously and may lag the in-memory conversation, so it may not yet include the current turn’s most recent messages when a hook fires. Hooks that need the final assistant text of the current turn should use `last_assistant_message` on Stop and SubagentStop instead of reading the transcript
`cwd`| Current working directory when the hook is invoked
`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. The mode labeled **Manual** arrives as `"default"`, never as `"manual"`, so scripts that match `"default"` keep working. Not all events receive this field. Check the JSON example in each hook event section
`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested model effort exceeds what the current model supports, this is the downgraded level the model actually used. Ultracode is not a distinct level and reports as `"xhigh"`. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
@@ -2114,7 +2114,7 @@
Stop input
-In addition to the common input fields, Stop hooks receive `stop_hook_active`, `last_assistant_message`, `background_tasks`, and `session_crons`. 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 avoid blocking on a condition that will never resolve. Claude Code overrides the hook and ends the turn after 8 consecutive blocks. The `last_assistant_message` field contains the text content of Claude’s final response, so hooks can access it without parsing the transcript file. The `background_tasks` and `session_crons` arrays, available in Claude Code v2.1.145 or later, let hooks distinguish “session is done” from “session is paused waiting for background work to wake it back up”. Both arrays are present when the task registry is reachable and are empty when nothing is in flight or scheduled. Each entry in `background_tasks` describes one in-flight task and uses these fields:
+In addition to the common input fields, Stop hooks receive `stop_hook_active`, `last_assistant_message`, `background_tasks`, and `session_crons`. 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 avoid blocking on a condition that will never resolve. Claude Code overrides the hook and ends the turn after 8 consecutive blocks. The `last_assistant_message` field contains the text content of Claude’s final response, so hooks can access it without parsing the transcript file. For hooks that act on the just-completed turn, such as read-aloud or notification hooks, use this field rather than reading `transcript_path`: the transcript file isn’t guaranteed to include the final message at Stop time on all versions. The `background_tasks` and `session_crons` arrays, available in Claude Code v2.1.145 or later, let hooks distinguish “session is done” from “session is paused waiting for background work to wake it back up”. Both arrays are present when the task registry is reachable and are empty when nothing is in flight or scheduled. Each entry in `background_tasks` describes one in-flight task and uses these fields:
Field| Description
---|---
--- a/hooks.md
+++ b/hooks.md
@@ -2999,7 +2999,7 @@
How async hooks execute
-When 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. After the background process exits, if the hook produced a JSON response with an `additionalContext` field, that content is delivered to Claude as context on the next conversation turn. A `systemMessage` field is shown to you, not to Claude. Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
+When 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. After the background process exits, if the hook produced a JSON response with an `additionalContext` field, that content is delivered to Claude as context on the next conversation turn. A `systemMessage` field is shown to you, not to Claude. Claude Code validates that JSON response against the same output schema as synchronous hooks, and drops any field whose value has the wrong type, such as a `systemMessage` that isn’t a string, instead of delivering it. Run with `--debug` to see a warning naming each dropped field. Before v2.1.202, malformed JSON output from an async hook could crash the session, and the crash recurred each time the session was resumed. Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
###
--- a/hooks.md
+++ b/hooks.md
@@ -572,7 +572,7 @@
`prompt_id`| UUID identifying the user prompt currently being processed. Matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>), so you can correlate hook output with telemetry for a single prompt. Absent until the first user input. Requires Claude Code v2.1.196 or later
`transcript_path`| Path to conversation JSON
`cwd`| Current working directory when the hook is invoked
-`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
+`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. The mode labeled **Manual** arrives as `"default"`, never as `"manual"`, so scripts that match `"default"` keep working. Not all events receive this field. Check the JSON example in each hook event section
`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested model effort exceeds what the current model supports, this is the downgraded level the model actually used. Ultracode is not a distinct level and reports as `"xhigh"`. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
`hook_event_name`| Name of the event that fired
@@ -1576,7 +1576,7 @@
`addRules`| `rules`, `behavior`, `destination`| Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"`
`replaceRules`| `rules`, `behavior`, `destination`| Replaces all rules of the given `behavior` at the `destination` with the provided `rules`
`removeRules`| `rules`, `behavior`, `destination`| Removes matching rules of the given `behavior`
-`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `auto`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan`
+`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `auto`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `plan`, and `manual` as an alias for `default`. The `manual` alias requires Claude Code v2.1.200 or later
`addDirectories`| `directories`, `destination`| Adds working directories. `directories` is an array of path strings
`removeDirectories`| `directories`, `destination`| Removes working directories
Show diff (721 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -8,7 +8,11 @@
Hook lifecycle
-Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences: once per session (`SessionStart`, `SessionEnd`), once per turn (`UserPromptSubmit`, `Stop`, `StopFailure`), and on every tool call inside the agentic loop (`PreToolUse`, `PostToolUse`):
+Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences:
+
+ * once per session: `SessionStart` and `SessionEnd`
+ * once per turn: `UserPromptSubmit`, `Stop`, and `StopFailure`
+ * on every tool call inside the agentic loop: `PreToolUse` and `PostToolUse`
The table below summarizes when each event fires. The Hook events section documents the full input schema and decision control options for each one.
@@ -184,7 +188,7 @@
Only letters, digits, `_`, `-`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly; `code-reviewer` matches only that agent type
Contains any other character| JavaScript regular expression, unanchored| `^Notebook` matches any tool whose name starts with `Notebook`; `mcp__memory__.*` matches every tool from the `memory` server
-A matcher on the regular-expression path is tested with JavaScript’s `RegExp.prototype.test`, which succeeds on a match anywhere in the value. `Edit.*` matches both `Edit` and `NotebookEdit`; wrap the pattern in `^` and `$`, as in `^Edit$`, when you need a whole-string match. Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression, so it also fires for `senior-code-reviewer`; anchor it as `^code-reviewer$` on those versions to match only that name. `FileChanged` and `StopFailure` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives. Every other event with matcher support in the table that follows accepts `|` or `,`. The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
+A matcher on the regular-expression path is tested with JavaScript’s `RegExp.prototype.test`, which succeeds on a match anywhere in the value. `Edit.*` matches both `Edit` and `NotebookEdit`; wrap the pattern in `^` and `$`, as in `^Edit$`, when you need a whole-string match. Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression, so it also fires for `senior-code-reviewer`; anchor it as `^code-reviewer$` on those versions to match only that name. `FileChanged` and `StopFailure` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives. Every other event with matcher support in the table that follows accepts `|` or `,`. The `FileChanged` event doesn’t follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
Event| What the matcher filters| Example matcher values
---|---|---
@@ -192,7 +196,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, custom agent names, or plugin-scoped names like `^my-plugin:reviewer$`
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
@@ -285,7 +289,7 @@
* **Prompt hooks** (`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.
* **Agent hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks.
-All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
+All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI. As of v2.1.199, [`$CLAUDE_CODE_BRIDGE_SESSION_ID`](</docs/en/env-vars>) is set to the [Remote Control](</docs/en/remote-control>) session ID while the local session has an active Remote Control connection.
####
@@ -313,7 +317,7 @@
`Bash(rm *)`| `echo $(date)`| no| no subcommand matches `rm *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny.
+The filter also fails open, running your hook regardless of pattern, when the Bash command can’t be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny.
####
@@ -335,7 +339,7 @@
A command hook runs as exec form when `args` is set, and shell form when `args` is omitted. Set `args` whenever the hook references a path placeholder, since each element is passed as one argument with no quoting. Omit `args` when you need shell features like pipes or `&&`, or when neither concern applies. **Exec form** runs when `args` is present. Claude Code resolves `command` as an executable on `PATH` and spawns it directly with `args` as the argument vector. There is no shell, so each `args` element is one argument exactly as written, and path placeholders like `${CLAUDE_PLUGIN_ROOT}` are substituted into `command` and into each `args` element as plain strings. Special characters such as apostrophes, `$`, and backticks pass through verbatim because there is no shell to interpret them. No shell tokenization happens on any platform. **Shell form** runs when `args` is absent. The `command` string is passed to a shell: `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed. Set the `shell` field to choose explicitly. The shell tokenizes the string, expands variables, and interprets pipes, `&&`, redirects, and globs.
-On Windows, exec form requires `command` to resolve to a real executable such as a `.exe`. The `.cmd` and `.bat` shims that npm, npx, eslint, and other tools install in `node_modules/.bin` are not executables and cannot be spawned without a shell. To run them in exec form, invoke the underlying script with `node` directly, for example `"command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/node_modules/eslint/bin/eslint.js"]`. The `node` plus script-path pattern works on every platform because `node.exe` is a real binary. To run a `.cmd` or `.bat` shim by name, use shell form.
+On Windows, exec form requires `command` to resolve to a real executable such as a `.exe`. The `.cmd` and `.bat` shims that npm, npx, eslint, and other tools install in `node_modules/.bin` are not executables and can’t be spawned without a shell. To run them in exec form, invoke the underlying script with `node` directly, for example `"command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/node_modules/eslint/bin/eslint.js"]`. The `node` plus script-path pattern works on every platform because `node.exe` is a real binary. To run a `.cmd` or `.bat` shim by name, use shell form.
This example runs a Node script bundled with a plugin. Exec form passes the resolved script path as one argument with no quoting:
@@ -354,7 +358,7 @@
Both forms support the same path placeholders, and both export them as the environment variables `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, and `CLAUDE_PLUGIN_DATA` on the spawned process, so a script can read `process.env.CLAUDE_PLUGIN_ROOT` regardless of how it was launched. Plugin hooks additionally substitute `${user_config.*}` values; see [User configuration](</docs/en/plugins-reference#user-configuration>).
-In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and do not trigger the warning.
+In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and don’t trigger the warning.
####
@@ -544,7 +548,7 @@
Disable or remove hooks
-To remove a hook, delete its entry from the settings JSON file. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration. The `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. Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
+To remove a hook, delete its entry from the settings JSON file. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration. The `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 can’t disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks. Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
##
@@ -552,7 +556,7 @@
Hook input and output
-Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options. On macOS and Linux, command hooks run in their own session without a controlling terminal as of v2.1.139. The hook process and any child processes cannot open `/dev/tty` or send escape sequences directly to the Claude Code interface. Windows has no `/dev/tty`. To surface a message to the user on any platform, return `systemMessage` in JSON output. To trigger a desktop notification, set a window title, or ring the bell, return `terminalSequence` instead.
+Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options. On macOS and Linux, command hooks run in their own session without a controlling terminal as of v2.1.139. The hook process and any child processes can’t open `/dev/tty` or send escape sequences directly to the Claude Code interface. Windows has no `/dev/tty`. To surface a message to the user on any platform, return `systemMessage` in JSON output. To trigger a desktop notification, set a window title, or ring the bell, return `terminalSequence` instead.
###
@@ -579,7 +583,7 @@
`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), this is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. See SubagentStart for how to write a matcher against a plugin-scoped name.
-Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value does not change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
+Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value doesn’t change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
{
"session_id": "abc123",
@@ -633,15 +637,15 @@
`UserPromptExpansion`| Yes| Blocks the expansion
`Stop`| Yes| Prevents Claude from stopping, continues the conversation
`SubagentStop`| Yes| Prevents the subagent from stopping
-`TeammateIdle`| Yes| Prevents the teammate from going idle (teammate continues working)
+`TeammateIdle`| Yes| Prevents the teammate from going idle, so it continues working
`TaskCreated`| Yes| Rolls back the task creation
`TaskCompleted`| Yes| Prevents the task from being marked as completed
`ConfigChange`| Yes| Blocks the configuration change from taking effect (except `policy_settings`)
`StopFailure`| No| Output and exit code are ignored
-`PostToolUse`| No| Shows stderr to Claude (tool already ran)
-`PostToolUseFailure`| No| Shows stderr to Claude (tool already failed)
+`PostToolUse`| No| Shows stderr to Claude; the tool already ran
+`PostToolUseFailure`| No| Shows stderr to Claude; the tool already failed
`PostToolBatch`| Yes| Stops the agentic loop before the next model call
-`PermissionDenied`| No| Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry
+`PermissionDenied`| No| Exit code and stderr are ignored because the denial already occurred. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry
`Notification`| No| Shows stderr to user only
`SubagentStart`| No| Shows stderr to user only
`SessionStart`| No| Shows stderr to user only
@@ -658,6 +662,8 @@
`InstructionsLoaded`| No| Exit code is ignored
`MessageDisplay`| No| The original text is displayed
+For `SessionStart`, `Setup`, and `SubagentStart`, the exit code 2 stderr renders in the transcript as a `<hook name> hook error` notice, the same way a non-blocking error does. Claude doesn’t see it, and the session or subagent proceeds. For `SubagentStart`, the notice appears in the subagent’s own transcript, not in the parent conversation. As of Claude Code v2.1.199, `SessionStart`, `Setup`, and `SubagentStart` show exit code 2 stderr in the transcript. Earlier versions wrote it to the debug log only.
+
###
@@ -672,7 +678,7 @@
* **Non-2xx status** : non-blocking error, execution continues
* **Connection failure or timeout** : non-blocking error, execution continues
-Unlike command hooks, HTTP hooks cannot signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.
+Unlike command hooks, HTTP hooks can’t signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.
###
@@ -728,7 +734,7 @@
The `{ "terminalSequence": "..." }` shape is the same from any shell or language. On Windows, build the escape string in PowerShell or a script and emit the same JSON object.
-`terminalSequence` is the supported replacement for hooks that previously wrote escape sequences directly to `/dev/tty`. The allowlist is restricted to sequences that cannot move the cursor or alter colors, so a hook can never corrupt an on-screen prompt.
+`terminalSequence` is the supported replacement for hooks that previously wrote escape sequences directly to `/dev/tty`. The allowlist is restricted to sequences that can’t move the cursor or alter colors, so a hook can never corrupt an on-screen prompt.
####
@@ -736,7 +742,7 @@
Add context for Claude
-The `additionalContext` field passes a string from your hook into Claude’s context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it does not appear as a chat message in the interface. Return `additionalContext` inside `hookSpecificOutput` alongside the event name:
+The `additionalContext` field passes a string from your hook into Claude’s context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it doesn’t appear as a chat message in the interface. Return `additionalContext` inside `hookSpecificOutput` alongside the event name:
{
"hookSpecificOutput": {
@@ -787,7 +793,7 @@
* `PreToolUse`: `updatedInput` directly under `hookSpecificOutput` replaces a tool’s arguments before it runs. See PreToolUse decision control
* `PermissionRequest`: `updatedInput` inside the `decision` object. See PermissionRequest decision control
* `PostToolUse`: `updatedToolOutput` replaces the tool’s result. See PostToolUse decision control
- * `UserPromptSubmit`: cannot replace the prompt; it only injects `additionalContext` alongside it
+ * `UserPromptSubmit`: can’t replace the prompt; it only injects `additionalContext` alongside it
For redaction or transformation use cases, intercept at `PreToolUse` for outbound tool inputs and `PostToolUse` for inbound tool results. Here are examples of each pattern in action:
@@ -844,7 +850,7 @@
SessionStart
-Runs 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](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. The matcher value corresponds to how the session was initiated:
+Runs 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 doesn’t require a script, use [CLAUDE.md](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. The matcher value corresponds to how the session was initiated:
Matcher| When it fires
---|---
@@ -859,7 +865,14 @@
SessionStart input
-In addition to the common input fields, SessionStart hooks receive `source` and optionally `model`, `agent_type`, and `session_title`. 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 active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it. If you start Claude Code with `claude --agent <name>`, an `agent_type` field contains the agent name. The `session_title` field carries the current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly.
+In addition to the common input fields, SessionStart hooks receive `source` and optionally `model`, `agent_type`, and `session_title`:
+
+Field| Description
+---|---
+`source`| How the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction
+`model`| The active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it
+`agent_type`| The agent name, present when you start Claude Code with `claude --agent <name>`
+`session_title`| The current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly
{
"session_id": "abc123",
@@ -881,7 +894,7 @@
Field| Description
---|---
`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it
-`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) (`-p`), where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
+`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) with the `-p` flag, where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
`sessionTitle`| Sets the session title, with the same effect as `/rename`. Use to name sessions automatically from the launch folder, git branch, or worktree name. Applies only when `source` is `"startup"` or `"resume"`; ignored on `"clear"` and `"compact"`
`watchPaths`| Array of absolute paths to watch for FileChanged events during this session
`reloadSkills`| Boolean. When `true`, Claude Code re-scans the [skill](</docs/en/skills>) and command directories after the SessionStart hooks complete, so skills the hook installed are available in the same session, starting with the first prompt
@@ -940,7 +953,7 @@
Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
-`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types do not have access to this variable.
+`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types don’t have access to this variable.
###
@@ -948,14 +961,14 @@
Setup
-Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in print mode (`-p`). It does not fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use SessionStart instead. The matcher value corresponds to the CLI flag that triggered the hook:
+Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It doesn’t fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use SessionStart instead. The matcher value corresponds to the CLI flag that triggered the hook:
Matcher| When it fires
---|---
`init`| `claude --init-only` or `claude -p --init`
`maintenance`| `claude -p --maintenance`
-`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p` (print mode); in an interactive session those two flags do not currently fire Setup hooks. Because Setup does not fire on every launch, a plugin that needs a dependency installed cannot rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
+`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p`; in an interactive session those two flags don’t currently fire Setup hooks. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
####
@@ -979,7 +992,7 @@
Setup decision control
-Setup hooks cannot block. On exit code 2, stderr is shown to the user; on any other non-zero exit code, stderr appears only when you launch with `--verbose`. In both cases execution continues. To pass information into Claude’s context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
+Setup hooks can’t block. Any non-zero exit code, including 2, surfaces stderr to the user as a `<hook name> hook error` notice, and execution continues. In [non-interactive mode](</docs/en/headless>), hook output appears only when you launch with `--verbose`. To pass information into Claude’s context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
Field| Description
---|---
@@ -1000,7 +1013,7 @@
InstructionsLoaded
-Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes. The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
+Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook doesn’t support blocking or decision control. It runs asynchronously for observability purposes. The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
####
@@ -1035,7 +1048,7 @@
InstructionsLoaded decision control
-InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
+InstructionsLoaded hooks have no decision control. They can’t block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
###
@@ -1073,7 +1086,7 @@
* **Plain text stdout** : any non-JSON text written to stdout is added as context
* **JSON with`additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
-Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely. To block a prompt, return a JSON object with `decision` set to `"block"`:
+Plain stdout is shown as hook output in the transcript. The `additionalContext` value is injected as a system reminder that Claude reads without a visible transcript entry. To block a prompt, return a JSON object with `decision` set to `"block"`:
Field| Description
---|---
@@ -1093,15 +1106,13 @@
}
}
-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 block prompts or want more structured control.
-
###
UserPromptExpansion
-Runs when a user-typed slash command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team’s review checklist as `additionalContext`. This event covers the path `PreToolUse` does not: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path. Matches on `command_name`. Leave the matcher empty to fire on every prompt-type slash command.
+Runs when a user-typed command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team’s review checklist as `additionalContext`. This event covers the path `PreToolUse` doesn’t: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path. Matches on `command_name`. Leave the matcher empty to fire on every prompt-type command.
####
@@ -1134,7 +1145,7 @@
Field| Description
---|---
-`decision`| `"block"` prevents the slash command from expanding. Omit to allow it to proceed
+`decision`| `"block"` prevents the command from expanding. Omit to allow it to proceed
`reason`| Shown to the user when `decision` is `"block"`
`additionalContext`| String added to Claude’s context alongside the expanded prompt. See Add context for Claude
@@ -1159,7 +1170,7 @@
* transform the text an Agent SDK application shows its users
* redact API keys or internal hostnames from Claude’s responses
-Claude Code holds each batch until your hook returns, so keep the hook fast. If the hook fails or times out, Claude Code displays the original text. The default timeout for this event is 10 seconds; if your hook needs more time, set the `timeout` field in the hook entry. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. The hook receives assistant message text only, so tool results and the text you type render unchanged. MessageDisplay does not support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, do not trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
+Claude Code holds each batch until your hook returns, so keep the hook fast. If the hook fails or times out, Claude Code displays the original text. The default timeout for this event is 10 seconds; if your hook needs more time, set the `timeout` field in the hook entry. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. The hook receives assistant message text only, so tool results and the text you type render unchanged. MessageDisplay doesn’t support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, don’t trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
####
@@ -1172,7 +1183,7 @@
Field| Description
---|---
`turn_id`| UUID of the current turn
-`message_id`| UUID of the assistant message being displayed. Stable across every batch of the same message. This is not the API `msg_…` id, so it cannot be correlated with transcript message ids
+`message_id`| UUID of the assistant message being displayed. Stable across every batch of the same message. This is not the API `msg_…` id, so it can’t be correlated with transcript message ids
`index`| Zero-based index of this batch within the message
`final`| `true` on the message’s last batch. Each message has exactly one final batch
`delta`| The newly completed lines since the prior batch, terminating newlines included. Always whole lines, except the final batch which may end mid-line. In interactive runs, the final batch’s delta is empty when the message ends on a newline, so treat `final`, not a non-empty delta, as the end-of-message signal. In Agent SDK and `claude -p` runs, the single call carries the entire message
@@ -1201,7 +1212,7 @@
---|---
`displayContent`| Text displayed in place of the delta. Omit it to display the original
-MessageDisplay hooks have no decision control. They cannot block the message or change what is stored in the transcript or sent to Claude. This example strips markdown formatting from Claude’s responses for a plain-text display. The script reads each batch from stdin, removes bold markers and inline code backticks from `delta`, and returns the result as `displayContent`.
+MessageDisplay hooks have no decision control. They can’t block the message or change what is stored in the transcript or sent to Claude. This example strips markdown formatting from Claude’s responses for a plain-text display. The script reads each batch from stdin, removes bold markers and inline code backticks from `delta`, and returns the result as `displayContent`.
* macOS/Linux
@@ -1386,7 +1397,7 @@
Field| Type| Example| Description
---|---|---|---
-`status`| string| `"completed"`| `"completed"` for synchronous calls, `"async_launched"` for `run_in_background: true`
+`status`| string| `"completed"`| `"completed"` for foreground subagents, `"async_launched"` for background subagents. As of v2.1.198, subagents run in the background by default, so an omitted `run_in_background` also produces `"async_launched"`
`agentId`| string| `"a4d2c8f1e0b3a297"`| Identifier for the subagent run
`content`| array| `[{"type": "text", "text": "Found 12 endpoints..."}]`| The subagent’s final text blocks
`resolvedModel`| string| `"claude-sonnet-4-5"`| Model the subagent ran on, which may differ from the requested model. Requires Claude Code v2.1.174 or later
@@ -1395,7 +1406,7 @@
`totalToolUseCount`| number| `7`| Count of tool calls the subagent made
`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`
-For `run_in_background: true` calls, the tool returns immediately after launching the subagent, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later.
+For background subagents, the tool returns immediately after launching, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later.
##### AskUserQuestion
@@ -1404,7 +1415,7 @@
Field| Type| Example| Description
---|---|---|---
`questions`| array| `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]`| Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag
-`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude does not set this field; supply it via `updatedInput` to answer programmatically
+`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude doesn’t set this field; supply it via `updatedInput` to answer programmatically
##### ExitPlanMode
@@ -1428,7 +1439,7 @@
Field| Description
---|---
-`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
+`permissionDecision`| `"allow"` skips the permission prompt, except for tools that require user interaction. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored
`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
`additionalContext`| String added to Claude’s context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See Add context for Claude
@@ -1447,7 +1458,7 @@
}
}
-`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer.
+`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs.
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.
@@ -1459,12 +1470,12 @@
`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](</docs/en/headless>) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result.
-The `defer` value requires Claude Code v2.1.89 or later. Earlier versions do not recognize it and the tool proceeds through the normal permission flow.
+The `defer` value requires Claude Code v2.1.89 or later. Earlier versions don’t recognize it and the tool proceeds through the normal permission flow.
The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:
1. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires.
- 2. The hook returns `permissionDecision: "defer"`. The tool does not execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
+ 2. The hook returns `permissionDecision: "defer"`. The tool doesn’t execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
3. The calling process reads `deferred_tool_use` from the SDK result, surfaces the question in its own UI, and waits for an answer.
4. The calling process runs `claude -p --resume <session-id>`. The same tool call fires `PreToolUse` again.
5. The hook returns `permissionDecision: "allow"` with the answer in `updatedInput`. The tool executes and Claude continues.
@@ -1485,7 +1496,7 @@
There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
-`--resume` restores the permission mode that was active when the tool was deferred, so you do not need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.
+`--resume` restores the permission mode that was active when the tool was deferred, so you don’t need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.
###
@@ -1534,7 +1545,7 @@
Field| Description
---|---
-`behavior`| `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated, so a hook returning `"allow"` does not override a matching deny rule
+`behavior`| `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated, so a hook returning `"allow"` doesn’t override a matching deny rule
`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. The modified input is re-evaluated against deny and ask rules
`updatedPermissions`| For `"allow"` only: array of permission update entries to apply, such as adding an allow rule or changing the session permission mode
`message`| For `"deny"` only: tells Claude why the permission was denied
@@ -1652,7 +1663,7 @@
}
}
-`updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a PreToolUse hook instead.The replacement value must match the tool’s output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that does not match the tool’s output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption.
+`updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a PreToolUse hook instead.The replacement value must match the tool’s output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that doesn’t match the tool’s output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption.
###
@@ -1781,7 +1792,7 @@
PermissionDenied
-Runs when the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier denies a tool call. This hook only fires in auto mode: it does not run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call. Matches on tool name, same values as PreToolUse.
+Runs when the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier denies a tool call. This hook only fires in auto mode: it doesn’t run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call. Matches on tool name, same values as PreToolUse.
####
@@ -1825,7 +1836,7 @@
}
}
-When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook does not return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.
+When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook doesn’t return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.
###
@@ -1833,7 +1844,20 @@
Notification
-Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`. Omit the matcher to run hooks for all notification types. Use 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:
+Runs when Claude Code sends notifications. Matches on notification type. Omit the matcher to run hooks for all notification types.
+
+Matcher| When it fires
+---|---
+`permission_prompt`| Claude needs you to approve a tool use
+`idle_prompt`| Claude is done and waiting for your next prompt
+`auth_success`| Authentication completes
+`elicitation_dialog`| An MCP server opens an elicitation form
+`elicitation_complete`| An MCP elicitation form is submitted or dismissed
+`elicitation_response`| An MCP elicitation response is sent back to the server
+`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal
+`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal
+
+The `agent_needs_input` and `agent_completed` types require Claude Code v2.1.198 or later. Use 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:
{
"hooks": {
@@ -1878,7 +1902,7 @@
"notification_type": "permission_prompt"
}
-Notification hooks cannot block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The common JSON output fields such as `systemMessage` apply.
+Notification hooks can’t block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The common JSON output fields such as `systemMessage` apply.
###
@@ -1894,7 +1918,7 @@
SubagentStart input
-In addition to the 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 `"general-purpose"`, `"Explore"`, `"Plan"`, or custom agent names).
+In addition to the common input fields, SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name that the matcher filters on.
{
"session_id": "abc123",
@@ -1905,7 +1929,7 @@
"agent_type": "Explore"
}
-SubagentStart hooks cannot block subagent creation, but they can inject context into the subagent. In addition to the JSON output fields available to all hooks, you can return:
+SubagentStart hooks can’t block subagent creation, but they can inject context into the subagent. In addition to the JSON output fields available to all hooks, you can return:
Field| Description
---|---
@@ -1957,7 +1981,7 @@
TaskCreated
-Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks do not support matchers and fire on every occurrence.
+Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks don’t support matchers and fire on every occurrence.
####
@@ -2018,7 +2042,7 @@
TaskCompleted
-Runs 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](</docs/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. When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks do not support matchers and fire on every occurrence.
+Runs 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](</docs/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. When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks don’t support matchers and fire on every occurrence.
####
@@ -2176,7 +2200,7 @@
StopFailure
-Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.
+Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude can’t complete a response due to rate limits, authentication problems, or other API errors.
####
@@ -2210,7 +2234,7 @@
TeammateIdle
-Runs when an [agent team](</docs/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. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
+Runs when an [agent team](</docs/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. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks don’t support matchers and fire on every occurrence.
####
@@ -2326,7 +2350,7 @@
"reason": "Configuration changes to project settings require admin approval"
}
-`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.
+`policy_settings` changes can’t 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.
###
@@ -2334,7 +2358,7 @@
CwdChanged
-Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. CwdChanged does not support matchers and fires on every directory change.
+Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. CwdChanged doesn’t support matchers and fires on every directory change.
####
@@ -2363,9 +2387,9 @@
Field| Description
---|---
-`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Returning an empty array clears the dynamic list, which is typical when entering a new directory
-
-CwdChanged hooks have no decision control. They cannot block the directory change.
+`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Returning an empty array clears the dynamic list, which is typical when entering a new directory
+
+CwdChanged hooks have no decision control. They can’t block the directory change.
###
@@ -2391,7 +2415,7 @@
Field| Description
---|---
`file_path`| Absolute path to the file that changed
-`event`| What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted)
+`event`| What happened: `"change"` for a modified file, `"add"` for a created file, or `"unlink"` for a deleted file
{
"session_id": "abc123",
@@ -2412,9 +2436,9 @@
Field| Description
---|---
-`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Use this when your hook script discovers additional files to watch based on the changed file
-
-FileChanged hooks have no decision control. They cannot block the file change from occurring.
+`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Use this when your hook script discovers additional files to watch based on the changed file
+
+FileChanged hooks have no decision control. They can’t block the file change from occurring.
###
@@ -2422,7 +2446,7 @@
WorktreeCreate
-When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+Runs when a worktree is being created, either from `claude --worktree` or from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>). By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
{
"hooks": {
@@ -2447,7 +2471,7 @@
WorktreeCreate input
-In addition to the 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`).
+In addition to the 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`.
{
"session_id": "abc123",
@@ -2463,7 +2487,7 @@
WorktreeCreate output
-WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
+WorktreeCreate hooks don’t use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
* **Command hooks** (`type: "command"`): print the path on stdout.
* **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
@@ -2476,7 +2500,7 @@
WorktreeRemove
-The cleanup counterpart to 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. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
+Runs 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. This is the cleanup counterpart to WorktreeCreate. For git-based worktrees, Claude Code 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. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
{
"hooks": {
@@ -2509,7 +2533,7 @@
"worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
}
-WorktreeRemove 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.
+WorktreeRemove hooks have no decision control. They can’t block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only.
###
@@ -2573,7 +2597,7 @@
"compact_summary": "Summary of the compacted conversation..."
}
-PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
+PostCompact hooks have no decision control. They can’t affect the compaction result but can perform follow-up tasks.
###
@@ -2608,7 +2632,7 @@
"reason": "other"
}
-SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If a hook needs more time, set a per-hook `timeout` in the hook configuration. The overall budget is automatically raised to the highest per-hook timeout configured in settings files, up to 60 seconds. Timeouts set on plugin-provided hooks do not raise the budget. To override the budget explicitly, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable in milliseconds.
+SessionEnd hooks have no decision control. They can’t block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If a hook needs more time, set a per-hook `timeout` in the hook configuration. The overall budget is automatically raised to the highest per-hook timeout configured in settings files, up to 60 seconds. Timeouts set on plugin-provided hooks don’t raise the budget. To override the budget explicitly, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable in milliseconds.
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
@@ -2626,7 +2650,7 @@
Elicitation input
-In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation (the most common case):
+In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation, the most common case:
{
"session_id": "abc123",
@@ -2645,7 +2669,7 @@
}
}
-For URL-mode elicitation (browser-based authentication):
+For URL-mode elicitation, used for browser-based authentication:
{
"session_id": "abc123",
@@ -2775,7 +2799,7 @@
* `WorktreeCreate`
* `WorktreeRemove`
-`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They do not support `http`, `prompt`, or `agent` hooks.
+`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They don’t support `http`, `prompt`, or `agent` hooks.
###
@@ -2847,7 +2871,7 @@
* `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`
* `TeammateIdle`: by default the teammate stops and the reason appears as a warning line. Set `continueOnBlock: true` to feed the reason back to the teammate and keep it working instead
* `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
- * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks cannot set. They run on this event, but their output is discarded. Use a command hook to return `retry`
+ * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks can’t set. They run on this event, but their output is discarded. Use a command hook to return `retry`
If you need finer control on any event, use a command hook with the per-event fields described in Decision control.
@@ -2855,9 +2879,9 @@
-Example: Multi-criteria Stop hook
-
-This `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](</docs/en/sub-agents>) should stop:
+Check multiple conditions before stopping
+
+This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. `SubagentStop` hooks use the same format to evaluate whether a [subagent](</docs/en/sub-agents>) should stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction:
{
"hooks": {
@@ -2939,7 +2963,7 @@
Run hooks in the background
-By 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.
+By 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 can’t 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.
###
@@ -2981,7 +3005,7 @@
-Example: run tests after file changes
+Run tests after file changes
This 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`:
@@ -3037,8 +3061,8 @@
Async hooks have several constraints compared to synchronous hooks:
- * Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.
- * Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
+ * Only `type: "command"` hooks support `async`. Prompt-based hooks can’t run asynchronously.
+ * Async hooks can’t block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction. Exception: an `asyncRewake` hook that exits with code 2 wakes Claude immediately even when the session is idle.
* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
@@ -3078,7 +3102,7 @@
Windows PowerShell tool
-On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (5.1).
+On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe`, the PowerShell 7 and later executable, and falls back to `powershell.exe` for Windows PowerShell 5.1.
{
"hooks": {
@@ -3097,7 +3121,7 @@
}
}
-To reference the project root from a PowerShell shell-form command, read it as an environment variable with `$env:CLAUDE_PROJECT_DIR`. PowerShell treats the bare `${CLAUDE_PROJECT_DIR}` form as a local variable, not an environment lookup, and Claude Code substitutes that placeholder in shell form only for plugin hooks. For a hook defined in `settings.json`, either use the `$env:` form or switch to exec form, where `${CLAUDE_PROJECT_DIR}` is substituted in each `args` element regardless of where the hook is defined. The example below shows a `settings.json` hook that runs a project script with the `$env:` form:
+To reference the project root from a PowerShell shell-form command, write `${CLAUDE_PROJECT_DIR}` or `$env:CLAUDE_PROJECT_DIR`. As of v2.1.198, Claude Code rewrites the `${CLAUDE_PROJECT_DIR}`, `${CLAUDE_PLUGIN_ROOT}`, and `${CLAUDE_PLUGIN_DATA}` placeholders in a PowerShell shell-form command to PowerShell’s `${env:NAME}` form, whether the hook is defined in `settings.json`, a plugin, or a skill. PowerShell then resolves the value from the exported environment after parsing, so the placeholder works inside double-quoted strings but not inside single-quoted strings, where PowerShell never expands variables. Before v2.1.198, this rewrite applied only to plugin hooks. On earlier versions, a `settings.json` hook needs the `$env:` form or exec form, where `${CLAUDE_PROJECT_DIR}` is substituted in each `args` element regardless of where the hook is defined. Don’t write the bare `$CLAUDE_PROJECT_DIR` spelling in a PowerShell hook. PowerShell parses it as an undefined local variable and resolves it to `$null`, which leaves the script path without its project-root prefix. Claude Code doesn’t rewrite that form; it logs a warning in the debug log instead. The example below shows a `settings.json` hook that runs a project script with the `$env:` form, which works on every version:
{
"type": "command",
@@ -3111,7 +3135,7 @@
Debug hooks
-Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag does not print to the terminal.
+Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag doesn’t print to the terminal.
[DEBUG] Executing hooks for PostToolUse:Write
[DEBUG] Found 1 hook commands to execute
--- a/hooks.md
+++ b/hooks.md
@@ -867,7 +867,7 @@
"cwd": "/Users/...",
"hook_event_name": "SessionStart",
"source": "startup",
- "model": "claude-sonnet-4-6"
+ "model": "claude-sonnet-5"
}
####
@@ -1275,7 +1275,11 @@
PreToolUse
-Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names. Use PreToolUse decision control to allow, deny, ask, or defer the tool call.
+Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names.
+
+PreToolUse runs only when Claude calls a tool. Files you [reference with `@` in your prompt](</docs/en/common-workflows#reference-files-and-directories>) are added without any tool call: Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. To block specific paths from `@` references, use a [`Read` deny rule](</docs/en/permissions#read-and-edit>) instead.
+
+Use PreToolUse decision control to allow, deny, ask, or defer the tool call.
####
@@ -3093,6 +3097,14 @@
}
}
+To reference the project root from a PowerShell shell-form command, read it as an environment variable with `$env:CLAUDE_PROJECT_DIR`. PowerShell treats the bare `${CLAUDE_PROJECT_DIR}` form as a local variable, not an environment lookup, and Claude Code substitutes that placeholder in shell form only for plugin hooks. For a hook defined in `settings.json`, either use the `$env:` form or switch to exec form, where `${CLAUDE_PROJECT_DIR}` is substituted in each `args` element regardless of where the hook is defined. The example below shows a `settings.json` hook that runs a project script with the `$env:` form:
+
+ {
+ "type": "command",
+ "shell": "powershell",
+ "command": "& \"$env:CLAUDE_PROJECT_DIR\\.claude\\hooks\\check.ps1\""
+ }
+
##
Show diff (101 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -181,10 +181,10 @@
Matcher value| Evaluated as| Example
---|---|---
`"*"`, `""`, or omitted| Match all| fires on every occurrence of the event
-Only letters, digits, `_`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly
-Contains any other character| JavaScript regular expression| `^Notebook` matches any tool starting with Notebook; `mcp__memory__.*` matches every tool from the `memory` server
-
-Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. The `FileChanged` and `StopFailure` events accept only `|` as the list separator and treat `,` as a literal character; all other events listed in the table that follows accept `|` or `,`. The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
+Only letters, digits, `_`, `-`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly; `code-reviewer` matches only that agent type
+Contains any other character| JavaScript regular expression, unanchored| `^Notebook` matches any tool whose name starts with `Notebook`; `mcp__memory__.*` matches every tool from the `memory` server
+
+A matcher on the regular-expression path is tested with JavaScript’s `RegExp.prototype.test`, which succeeds on a match anywhere in the value. `Edit.*` matches both `Edit` and `NotebookEdit`; wrap the pattern in `^` and `$`, as in `^Edit$`, when you need a whole-string match. Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression, so it also fires for `senior-code-reviewer`; anchor it as `^code-reviewer$` on those versions to match only that name. `FileChanged` and `StopFailure` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives. Every other event with matcher support in the table that follows accepts `|` or `,`. The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
Event| What the matcher filters| Example matcher values
---|---|---
@@ -193,7 +193,7 @@
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`
-`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
+`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, custom agent names, or plugin-scoped names like `^my-plugin:reviewer$`
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
@@ -224,7 +224,7 @@
}
}
-`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
+`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `MessageDisplay`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
####
@@ -238,12 +238,13 @@
* `mcp__filesystem__read_file`: Filesystem server’s read file tool
* `mcp__github__search_repositories`: GitHub server’s search tool
-To match every tool from a server, append `.*` to the server prefix. The `.*` is required: a matcher like `mcp__memory` contains only letters and underscores, so it is compared as an exact string and matches no tool.
+To match every tool from a server, append `.*` to the server prefix. The `.*` is required: a matcher like `mcp__memory` or `mcp__brave-search` contains only exact-match characters, so it is compared as an exact string and matches no tool.
* `mcp__memory__.*` matches all tools from the `memory` server
+ * `mcp__brave-search__.*` matches all tools from a server whose name contains a hyphen
* `mcp__.*__write.*` matches any tool whose name starts with `write` from any server
-This example logs all memory server operations and validates write operations from any MCP server:
+Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a bare hyphenated prefix like `mcp__brave-search` is evaluated as an unanchored regular expression and matches every tool from that server. The `mcp__brave-search__.*` form works on every version. This example logs all memory server operations and validates write operations from any MCP server:
{
"hooks": {
@@ -328,7 +329,7 @@
`args`| no| Argument list. When present, `command` is resolved as an executable and spawned directly with `args` as the argument vector, with no shell involved. See Exec form and shell form
`async`| no| If `true`, runs in the background without blocking. See Run hooks in the background
`asyncRewake`| no| If `true`, runs in the background and wakes Claude on exit code 2. Implies `async`. The hook’s stderr, or stdout if stderr is empty, is shown to Claude as a system reminder so it can react to a long-running background failure
-`shell`| no| Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly. Ignored when `args` is set
+`shell`| no| Shell to use for this hook. Accepts `"bash"` or `"powershell"`. Defaults to `"bash"`, or to `"powershell"` on Windows when Git Bash isn’t installed. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly. Ignored when `args` is set
##### Exec form and shell form
@@ -564,6 +565,7 @@
Field| Description
---|---
`session_id`| Current session identifier
+`prompt_id`| UUID identifying the user prompt currently being processed. Matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>), so you can correlate hook output with telemetry for a single prompt. Absent until the first user input. Requires Claude Code v2.1.196 or later
`transcript_path`| Path to conversation JSON
`cwd`| Current working directory when the hook is invoked
`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
@@ -575,12 +577,13 @@
Field| Description
---|---
`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
-`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename.
+`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), this is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. See SubagentStart for how to write a matcher against a plugin-scoped name.
Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value does not change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
{
"session_id": "abc123",
+ "prompt_id": "550e8400-e29b-41d4-a716-446655440000",
"transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
"cwd": "/home/user/my-project",
"permission_mode": "default",
@@ -1040,7 +1043,7 @@
UserPromptSubmit
-Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry.
+Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. A `UserPromptSubmit` hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. As of v2.1.196, the transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. Earlier versions cancel the hook with no notice.
####
@@ -1879,7 +1882,7 @@
SubagentStart
-Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name. For built-in agents, this is the agent name like `general-purpose`, `Explore`, or `Plan`. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename.
+Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name. For built-in agents, this is the agent name like `general-purpose`, `Explore`, or `Plan`. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), the agent type is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. The colon places a plugin-scoped name on the regular-expression path, so anchor the matcher with `^` and `$` for an exact match: `^my-plugin:reviewer$`.
####
--- a/hooks.md
+++ b/hooks.md
@@ -284,6 +284,8 @@
* **Prompt hooks** (`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.
* **Agent hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks.
+All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
+
####
@@ -436,8 +438,6 @@
---|---|---
`prompt`| yes| Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON. Escape with a backslash to include literal text: `\$1.00` renders as `$1.00`
`model`| no| Model to use for evaluation. Defaults to a fast model
-
-All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
###
@@ -781,10 +781,10 @@
A few events can also rewrite content rather than only allow or block it:
- * `PreToolUse` — `updatedInput` directly under `hookSpecificOutput` replaces a tool’s arguments before it runs (details)
- * `PermissionRequest` — `updatedInput` inside the `decision` object (details)
- * `PostToolUse` — `updatedToolOutput` replaces the tool’s result (details)
- * `UserPromptSubmit` — cannot replace the prompt; only injects `additionalContext` alongside it
+ * `PreToolUse`: `updatedInput` directly under `hookSpecificOutput` replaces a tool’s arguments before it runs. See PreToolUse decision control
+ * `PermissionRequest`: `updatedInput` inside the `decision` object. See PermissionRequest decision control
+ * `PostToolUse`: `updatedToolOutput` replaces the tool’s result. See PostToolUse decision control
+ * `UserPromptSubmit`: cannot replace the prompt; it only injects `additionalContext` alongside it
For redaction or transformation use cases, intercept at `PreToolUse` for outbound tool inputs and `PostToolUse` for inbound tool results. Here are examples of each pattern in action:
@@ -2840,7 +2840,7 @@
* `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`
* `TeammateIdle`: by default the teammate stops and the reason appears as a warning line. Set `continueOnBlock: true` to feed the reason back to the teammate and keep it working instead
* `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
- * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks cannot set — they run on this event, but their output is discarded. Use a command hook to return `retry`
+ * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks cannot set. They run on this event, but their output is discarded. Use a command hook to return `retry`
If you need finer control on any event, use a command hook with the per-event fields described in Decision control.
--- a/hooks.md
+++ b/hooks.md
@@ -181,10 +181,10 @@
Matcher value| Evaluated as| Example
---|---|---
`"*"`, `""`, or omitted| Match all| fires on every occurrence of the event
-Only letters, digits, `_`, and `|`| Exact string, or `|`-separated list of exact strings| `Bash` matches only the Bash tool; `Edit|Write` matches either tool exactly
+Only letters, digits, `_`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly
Contains any other character| JavaScript regular expression| `^Notebook` matches any tool starting with Notebook; `mcp__memory__.*` matches every tool from the `memory` server
-The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
+Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. The `FileChanged` and `StopFailure` events accept only `|` as the list separator and treat `,` as a literal character; all other events listed in the table that follows accept `|` or `,`. The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
Event| What the matcher filters| Example matcher values
---|---|---
--- a/hooks.md
+++ b/hooks.md
@@ -1388,7 +1388,7 @@
`totalToolUseCount`| number| `7`| Count of tool calls the subagent made
`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`
-For `run_in_background: true` calls, the tool returns immediately after launching the subagent, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`. It requires Claude Code v2.1.174 or later.
+For `run_in_background: true` calls, the tool returns immediately after launching the subagent, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later.
##### AskUserQuestion
@@ -1970,7 +1970,7 @@
"task_subject": "Implement user authentication",
"task_description": "Add login and signup endpoints",
"teammate_name": "implementer",
- "team_name": "my-project"
+ "team_name": "session-a1b2c3d4"
}
Field| Description
@@ -1979,7 +1979,7 @@
`task_subject`| Title of the task
`task_description`| Detailed description of the task. May be absent
`teammate_name`| Name of the teammate creating the task. May be absent
-`team_name`| Name of the team. May be absent
+`team_name`| Deprecated. Session-derived team name; will be removed in a future release
####
@@ -2031,7 +2031,7 @@
"task_subject": "Implement user authentication",
"task_description": "Add login and signup endpoints",
"teammate_name": "implementer",
- "team_name": "my-project"
+ "team_name": "session-a1b2c3d4"
}
Field| Description
@@ -2040,7 +2040,7 @@
`task_subject`| Title of the task
`task_description`| Detailed description of the task. May be absent
`teammate_name`| Name of the teammate completing the task. May be absent
-`team_name`| Name of the team. May be absent
+`team_name`| Deprecated. Session-derived team name; will be removed in a future release
####
@@ -2220,13 +2220,13 @@
"permission_mode": "default",
"hook_event_name": "TeammateIdle",
"teammate_name": "researcher",
- "team_name": "my-project"
+ "team_name": "session-a1b2c3d4"
}
Field| Description
---|---
`teammate_name`| Name of the teammate that is about to go idle
-`team_name`| Name of the team
+`team_name`| Deprecated. Session-derived team name; will be removed in a future release
####
--- a/hooks.md
+++ b/hooks.md
@@ -577,7 +577,7 @@
`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename.
-Only `SessionStart` hooks receive a `model` field. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value does not change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
+Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value does not change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
{
"session_id": "abc123",
@@ -856,7 +856,7 @@
SessionStart input
-In addition to the common input fields, SessionStart hooks receive `source`, `model`, and optionally `agent_type` and `session_title`. 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. The `session_title` field carries the current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly.
+In addition to the common input fields, SessionStart hooks receive `source` and optionally `model`, `agent_type`, and `session_title`. 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 active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it. If you start Claude Code with `claude --agent <name>`, an `agent_type` field contains the agent name. The `session_title` field carries the current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly.
{
"session_id": "abc123",
@@ -1382,12 +1382,13 @@
`status`| string| `"completed"`| `"completed"` for synchronous calls, `"async_launched"` for `run_in_background: true`
`agentId`| string| `"a4d2c8f1e0b3a297"`| Identifier for the subagent run
`content`| array| `[{"type": "text", "text": "Found 12 endpoints..."}]`| The subagent’s final text blocks
+`resolvedModel`| string| `"claude-sonnet-4-5"`| Model the subagent ran on, which may differ from the requested model. Requires Claude Code v2.1.174 or later
`totalTokens`| number| `12450`| Total tokens billed across the subagent’s turns
`totalDurationMs`| number| `48211`| Wall-clock duration of the subagent run
`totalToolUseCount`| number| `7`| Count of tool calls the subagent made
`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`
-For `run_in_background: true` calls, the tool returns immediately after launching the subagent, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, and `outputFile` instead.
+For `run_in_background: true` calls, the tool returns immediately after launching the subagent, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`. It requires Claude Code v2.1.174 or later.
##### AskUserQuestion
--- a/hooks.md
+++ b/hooks.md
@@ -163,7 +163,7 @@
---|---|---
`~/.claude/settings.json`| All your projects| No, local to your machine
`.claude/settings.json`| Single project| Yes, can be committed to the repo
-`.claude/settings.local.json`| Single project| No, gitignored
+`.claude/settings.local.json`| Single project| No, gitignored when Claude Code creates it
Managed policy settings| Organization-wide| Yes, admin-controlled
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
@@ -308,7 +308,7 @@
`Bash(git *)`| `npm test && git push`| yes| each subcommand is checked; `git push` matches
`Bash(rm *)`| `echo $(rm -rf /)`| yes| commands inside `$()` and backticks are checked; `rm -rf /` matches
`Bash(rm *)`| `echo $(date)`| no| no subcommand matches `rm *`
-`Bash(git push *)`| `echo $(date)`| yes| patterns that constrain past the command name fail open on `$()`, backticks, or `$VAR`
+`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny.
@@ -779,7 +779,14 @@
SessionStart, Setup, SubagentStart| Context only| `hookSpecificOutput.additionalContext` adds context for Claude. SessionStart also accepts `initialUserMessage`, `watchPaths`, `sessionTitle`, and `reloadSkills`. No blocking or decision control
WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged| None| No decision control. Used for side effects like logging or cleanup
-Here are examples of each pattern in action:
+A few events can also rewrite content rather than only allow or block it:
+
+ * `PreToolUse` — `updatedInput` directly under `hookSpecificOutput` replaces a tool’s arguments before it runs (details)
+ * `PermissionRequest` — `updatedInput` inside the `decision` object (details)
+ * `PostToolUse` — `updatedToolOutput` replaces the tool’s result (details)
+ * `UserPromptSubmit` — cannot replace the prompt; only injects `additionalContext` alongside it
+
+For redaction or transformation use cases, intercept at `PreToolUse` for outbound tool inputs and `PostToolUse` for inbound tool results. Here are examples of each pattern in action:
* Top-level decision
--- a/hooks.md
+++ b/hooks.md
@@ -295,12 +295,22 @@
Field| Required| Description
---|---|---
`type`| yes| `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"`
-`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern, or if a Bash command is too complex to parse. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
+`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the Bash matching table below for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30, and `MessageDisplay` lowers it to 10
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
-The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. For Bash, the rule is matched against each subcommand of the tool input after leading `VAR=value` assignments are stripped, so `if: "Bash(git push *)"` matches both `FOO=bar git push` and `npm test && git push`. The hook runs if any subcommand matches, and always runs when the command is too complex to parse.
+The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. For Bash patterns, whether your hook command runs depends on the shape of the pattern and the Bash command Claude is invoking. Leading `VAR=value` assignments are stripped before matching.
+
+`if` pattern| Bash command| Hook runs?| Why
+---|---|---|---
+`Bash(git *)`| `FOO=bar git push`| yes| leading assignments are stripped; `git push` matches
+`Bash(git *)`| `npm test && git push`| yes| each subcommand is checked; `git push` matches
+`Bash(rm *)`| `echo $(rm -rf /)`| yes| commands inside `$()` and backticks are checked; `rm -rf /` matches
+`Bash(rm *)`| `echo $(date)`| no| no subcommand matches `rm *`
+`Bash(git push *)`| `echo $(date)`| yes| patterns that constrain past the command name fail open on `$()`, backticks, or `$VAR`
+
+The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny.
####
@@ -424,7 +434,7 @@
Field| Required| Description
---|---|---
-`prompt`| yes| Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON
+`prompt`| yes| Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON. Escape with a backslash to include literal text: `\$1.00` renders as `$1.00`
`model`| no| Model to use for evaluation. Defaults to a fast model
All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
@@ -737,6 +747,7 @@
* SessionStart, Setup, and SubagentStart: at the start of the conversation, before the first prompt
* UserPromptSubmit and UserPromptExpansion: alongside the submitted prompt
* PreToolUse, PostToolUse, PostToolUseFailure, and PostToolBatch: next to the tool result
+ * Stop and SubagentStop: at the end of the turn. The conversation continues so Claude can act on the feedback. See Stop decision control
When several hooks return `additionalContext` for the same event, Claude receives all of the values. If a value exceeds 10,000 characters, Claude Code writes the full text to a file in the session directory and passes Claude the file path with a short preview instead. Use `additionalContext` for information Claude should know about the current state of your environment or the operation that just ran:
@@ -756,7 +767,7 @@
Events| Decision pattern| Key fields
---|---|---
-UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`
+UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`. Stop and SubagentStop also accept `hookSpecificOutput.additionalContext` for non-error feedback that continues the conversation
TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason`
PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
@@ -1923,7 +1934,7 @@
"session_crons": []
}
-SubagentStop hooks use the same decision control format as Stop hooks. They do not support `additionalContext`. Returning `decision: "block"` with a `reason` keeps the subagent running and delivers `reason` to the subagent as its next instruction. To inject context into the parent session after a subagent returns, use a `PostToolUse` hook on the `Agent` tool instead.
+SubagentStop hooks use the same decision control format as Stop hooks, including `hookSpecificOutput.additionalContext` with `hookEventName` set to `"SubagentStop"`, for non-error feedback that keeps the subagent running. Returning `decision: "block"` with a `reason` keeps the subagent running and delivers `reason` to the subagent as its next instruction. To inject context into the parent session after a subagent returns, use a `PostToolUse` hook on the `Agent` tool instead.
###
@@ -2128,10 +2139,20 @@
---|---
`decision`| `"block"` prevents Claude from stopping. Omit to allow Claude to stop
`reason`| Required when `decision` is `"block"`. Tells Claude why it should continue
+`hookSpecificOutput.additionalContext`| Non-error feedback for Claude. The conversation continues so Claude can act on it, but unlike `decision: "block"` it is shown in the transcript as hook feedback rather than a hook error
{
"decision": "block",
"reason": "Must be provided when Claude is blocked from stopping"
+ }
+
+Use `additionalContext` when the hook is working as designed and giving Claude guidance, such as “run the test suite before finishing”. It keeps the conversation going through the same loop protections as `decision: "block"`, namely the `stop_hook_active` input and the 8-consecutive-continuation cap, but the transcript labels it `Stop hook feedback` and no hook error notification is shown:
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "Stop",
+ "additionalContext": "Please run the test suite before finishing"
+ }
}
###
--- a/hooks.md
+++ b/hooks.md
@@ -1,9 +1,3 @@
-> ## Documentation Index
->
-> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
->
-> Use this file to discover all available pages before exploring further.
-
For a quickstart guide with examples, see [Automate actions with hooks](</docs/en/hooks-guide>).
Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you’re setting up hooks for the first time, start with the [guide](</docs/en/hooks-guide>) instead.
@@ -205,7 +199,7 @@
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`CwdChanged`| no matcher support| always fires on every directory change
`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env`
-`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`UserPromptExpansion`| command name| your skill or command names
`Elicitation`| MCP server name| your configured MCP server names
@@ -2158,7 +2152,7 @@
Field| Description
---|---
-`error`| Error type: `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown`
+`error`| Error type: `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown`
`error_details`| Additional details about the error, when available
`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"`
Show diff (119 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -4,7 +4,7 @@
>
> Use this file to discover all available pages before exploring further.
-For a quickstart guide with examples, see [Automate workflows with hooks](</docs/en/hooks-guide>).
+For a quickstart guide with examples, see [Automate actions with hooks](</docs/en/hooks-guide>).
Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you’re setting up hooks for the first time, start with the [guide](</docs/en/hooks-guide>) instead.
@@ -302,7 +302,7 @@
---|---|---
`type`| yes| `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"`
`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern, or if a Bash command is too complex to parse. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
-`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30
+`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30, and `MessageDisplay` lowers it to 10
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
@@ -1028,7 +1028,7 @@
UserPromptSubmit
-Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry.
+Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry.
####
@@ -1138,7 +1138,13 @@
MessageDisplay
-Runs while an assistant message streams to the screen. Claude Code displays the message in increments: each time a batch of newly completed lines is ready to render, the hook runs once with those lines and Claude Code renders the hook’s replacement text in their place. A long message produces several calls; a short message may produce only one. Use this to reformat, redact, or condense Claude’s responses as they appear on screen. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. MessageDisplay does not support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, do not trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
+Runs while an assistant message streams to the screen. Claude Code displays the message in increments: each time a batch of newly completed lines is ready to render, the hook runs once with those lines and Claude Code renders the hook’s replacement text in their place. A long message produces several calls; a short message may produce only one. Use MessageDisplay to:
+
+ * strip markdown for a minimal display
+ * transform the text an Agent SDK application shows its users
+ * redact API keys or internal hostnames from Claude’s responses
+
+Claude Code holds each batch until your hook returns, so keep the hook fast. If the hook fails or times out, Claude Code displays the original text. The default timeout for this event is 10 seconds; if your hook needs more time, set the `timeout` field in the hook entry. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. The hook receives assistant message text only, so tool results and the text you type render unchanged. MessageDisplay does not support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, do not trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
####
@@ -1180,7 +1186,73 @@
---|---
`displayContent`| Text displayed in place of the delta. Omit it to display the original
-MessageDisplay hooks have no decision control. They cannot block the message or change what is stored in the transcript or sent to Claude.
+MessageDisplay hooks have no decision control. They cannot block the message or change what is stored in the transcript or sent to Claude. This example strips markdown formatting from Claude’s responses for a plain-text display. The script reads each batch from stdin, removes bold markers and inline code backticks from `delta`, and returns the result as `displayContent`.
+
+ * macOS/Linux
+
+ * Windows (PowerShell)
+
+Register a command hook for the event in your settings file:
+
+ {
+ "hooks": {
+ "MessageDisplay": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/plain-display.sh",
+ "args": []
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+Save this script to `.claude/hooks/plain-display.sh` in your project and make it executable with `chmod +x`:
+
+ #!/bin/bash
+ jq '{hookSpecificOutput: {hookEventName: "MessageDisplay", displayContent: (.delta | gsub("\\*\\*"; "") | gsub("`"; ""))}}'
+
+The script needs `jq` on your `PATH`.
+
+Register a command hook that runs the script through PowerShell:
+
+ {
+ "hooks": {
+ "MessageDisplay": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "powershell.exe",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "${CLAUDE_PROJECT_DIR}/.claude/hooks/plain-display.ps1"
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The `-NoProfile` flag skips loading your PowerShell profile so the hook starts fast, and `-ExecutionPolicy Bypass` lets PowerShell run the local script file.Save this script to `.claude/hooks/plain-display.ps1` in your project:
+
+ $batch = [Console]::In.ReadToEnd() | ConvertFrom-Json
+ $text = $batch.delta -replace '\*\*', '' -replace '`', ''
+ @{
+ hookSpecificOutput = @{
+ hookEventName = "MessageDisplay"
+ displayContent = $text
+ }
+ } | ConvertTo-Json
+
+Batches with no markdown pass through unchanged. If the script fails, for example because `jq` is missing, Claude Code displays the original text and notes the failure only in debug output, not in the session.
###
--- a/hooks.md
+++ b/hooks.md
@@ -563,7 +563,7 @@
`transcript_path`| Path to conversation JSON
`cwd`| Current working directory when the hook is invoked
`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
-`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"`, or `"ultra"`. If the requested model effort exceeds what the current model supports, this is the downgraded level the model actually used. `"ultra"` is the stored value for ultracode and is reported here even though the model receives `xhigh`. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
+`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested model effort exceeds what the current model supports, this is the downgraded level the model actually used. Ultracode is not a distinct level and reports as `"xhigh"`. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
`hook_event_name`| Name of the event that fired
When running with `--agent` or inside a subagent, two additional fields are included:
--- a/hooks.md
+++ b/hooks.md
@@ -443,7 +443,7 @@
Use these placeholders to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
- * `${CLAUDE_PROJECT_DIR}`: the project root.
+ * `${CLAUDE_PROJECT_DIR}`: the project root. Claude Code also sets this variable in the environment of [stdio MCP servers](</docs/en/mcp#option-3-add-a-local-stdio-server>) and plugin LSP servers.
* `${CLAUDE_PLUGIN_ROOT}`: the plugin’s installation directory, for scripts bundled with a [plugin](</docs/en/plugins>). Changes on each plugin update.
* `${CLAUDE_PLUGIN_DATA}`: the plugin’s [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>), for dependencies and state that should survive plugin updates.
@@ -563,7 +563,7 @@
`transcript_path`| Path to conversation JSON
`cwd`| Current working directory when the hook is invoked
`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
-`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested effort exceeds what the current model supports, this is the downgraded level the model actually used, not the level you requested. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
+`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"`, or `"ultra"`. If the requested model effort exceeds what the current model supports, this is the downgraded level the model actually used. `"ultra"` is the stored value for ultracode and is reported here even though the model receives `xhigh`. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
`hook_event_name`| Name of the event that fired
When running with `--agent` or inside a subagent, two additional fields are included:
Show diff (135 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -31,6 +31,7 @@
`PostToolUseFailure`| After a tool call fails
`PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call
`Notification`| When Claude Code sends a notification
+`MessageDisplay`| While assistant message text is displayed
`SubagentStart`| When a subagent is spawned
`SubagentStop`| When a subagent finishes
`TaskCreated`| When a task is being created via `TaskCreate`
@@ -209,7 +210,7 @@
`UserPromptExpansion`| command name| your skill or command names
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
-`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
+`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `MessageDisplay`| no matcher support| always fires on every occurrence
The matcher runs against a field from the JSON input that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file:
@@ -648,6 +649,7 @@
`WorktreeCreate`| Yes| Any non-zero exit code causes worktree creation to fail
`WorktreeRemove`| No| Failures are logged in debug mode only
`InstructionsLoaded`| No| Exit code is ignored
+`MessageDisplay`| No| The original text is displayed
###
@@ -768,7 +770,8 @@
WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation
Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept)
ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
-SessionStart, Setup, SubagentStart| Context only| `hookSpecificOutput.additionalContext` adds context for Claude. SessionStart also accepts `initialUserMessage` and `watchPaths`. No blocking or decision control
+MessageDisplay| `hookSpecificOutput`| `displayContent` replaces the displayed text on screen. Display-only: the transcript and what Claude sees keep the original
+SessionStart, Setup, SubagentStart| Context only| `hookSpecificOutput.additionalContext` adds context for Claude. SessionStart also accepts `initialUserMessage`, `watchPaths`, `sessionTitle`, and `reloadSkills`. No blocking or decision control
WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged| None| No decision control. Used for side effects like logging or cleanup
Here are examples of each pattern in action:
@@ -841,7 +844,7 @@
SessionStart input
-In addition to the 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.
+In addition to the common input fields, SessionStart hooks receive `source`, `model`, and optionally `agent_type` and `session_title`. 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. The `session_title` field carries the current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly.
{
"session_id": "abc123",
@@ -864,16 +867,26 @@
---|---
`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it
`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) (`-p`), where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
+`sessionTitle`| Sets the session title, with the same effect as `/rename`. Use to name sessions automatically from the launch folder, git branch, or worktree name. Applies only when `source` is `"startup"` or `"resume"`; ignored on `"clear"` and `"compact"`
`watchPaths`| Array of absolute paths to watch for FileChanged events during this session
+`reloadSkills`| Boolean. When `true`, Claude Code re-scans the [skill](</docs/en/skills>) and command directories after the SessionStart hooks complete, so skills the hook installed are available in the same session, starting with the first prompt
{
"hookSpecificOutput": {
"hookEventName": "SessionStart",
- "additionalContext": "Current branch: feat/auth-refactor\nUncommitted changes: src/auth.ts, src/login.tsx\nActive issue: #4211 Migrate to OAuth2"
- }
- }
-
-Since plain stdout already reaches Claude for this event, a hook that only loads context can print to stdout directly without building JSON. Use the JSON form when you need to combine context with other fields such as `suppressOutput`.
+ "additionalContext": "Current branch: feat/auth-refactor\nUncommitted changes: src/auth.ts, src/login.tsx\nActive issue: #4211 Migrate to OAuth2",
+ "sessionTitle": "auth-refactor"
+ }
+ }
+
+Since plain stdout already reaches Claude for this event, a hook that only loads context can print to stdout directly without building JSON. Use the JSON form when you need to combine context with other fields such as `suppressOutput` or `sessionTitle`. Use `reloadSkills` when a SessionStart hook installs or updates skills. Skill discovery normally runs before SessionStart hooks finish, so files the hook writes into `~/.claude/skills/` or `.claude/skills/` would otherwise only appear in the next session. This example syncs a shared skills repository and requests the re-scan:
+
+ #!/bin/bash
+
+ git -C ~/.claude/skills/team-skills pull --quiet 2>/dev/null || \
+ git clone --quiet https://git.example.com/your-org/team-skills.git ~/.claude/skills/team-skills
+
+ echo '{"hookSpecificOutput": {"hookEventName": "SessionStart", "reloadSkills": true}}'
####
@@ -1118,6 +1131,56 @@
"additionalContext": "Additional context for this expansion"
}
}
+
+###
+
+
+
+MessageDisplay
+
+Runs while an assistant message streams to the screen. Claude Code displays the message in increments: each time a batch of newly completed lines is ready to render, the hook runs once with those lines and Claude Code renders the hook’s replacement text in their place. A long message produces several calls; a short message may produce only one. Use this to reformat, redact, or condense Claude’s responses as they appear on screen. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. MessageDisplay does not support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, do not trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
+
+####
+
+
+
+MessageDisplay input
+
+In addition to the common input fields, MessageDisplay hooks receive identifiers for the turn and message, the position of this call within the message, and the new text in `delta`. Batch boundaries depend on how the text streams, so use `index` and `final` to track progress through a message rather than expecting lines to be grouped a particular way.
+
+Field| Description
+---|---
+`turn_id`| UUID of the current turn
+`message_id`| UUID of the assistant message being displayed. Stable across every batch of the same message. This is not the API `msg_…` id, so it cannot be correlated with transcript message ids
+`index`| Zero-based index of this batch within the message
+`final`| `true` on the message’s last batch. Each message has exactly one final batch
+`delta`| The newly completed lines since the prior batch, terminating newlines included. Always whole lines, except the final batch which may end mid-line. In interactive runs, the final batch’s delta is empty when the message ends on a newline, so treat `final`, not a non-empty delta, as the end-of-message signal. In Agent SDK and `claude -p` runs, the single call carries the entire message
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
+ "cwd": "/Users/my-project",
+ "hook_event_name": "MessageDisplay",
+ "turn_id": "0c9e6a2f-7d41-4f4e-9a15-3f4f7c2b8d10",
+ "message_id": "5b2a9c8e-1f63-4d8a-b7c4-9e0d2a6f1c3b",
+ "index": 0,
+ "final": false,
+ "delta": "Here is the plan:\n"
+ }
+
+####
+
+
+
+MessageDisplay output
+
+In addition to the JSON output fields available to all hooks, MessageDisplay hooks can return `displayContent` to replace the delta on screen:
+
+Field| Description
+---|---
+`displayContent`| Text displayed in place of the delta. Omit it to display the original
+
+MessageDisplay hooks have no decision control. They cannot block the message or change what is stored in the transcript or sent to Claude.
###
Show diff (130 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -91,7 +91,7 @@
}
}'
else
- exit 0 # allow the command
+ exit 0 # no decision; normal permission flow applies
fi
Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here’s what happens:
@@ -130,7 +130,7 @@
}
}
-If the command had been a safer `rm` variant like `rm file.txt`, the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.
+If the command had been a safer `rm` variant like `rm file.txt`, the script would hit `exit 0` instead. Exit code 0 with no output means the hook has no decision to report, so the tool call continues through the normal [permission flow](</docs/en/permissions>). The hook can deny the call, but staying silent doesn’t approve it.
5
@@ -605,7 +605,7 @@
exit 2 # Blocking error: tool call is prevented
fi
- exit 0 # Success: tool call proceeds
+ exit 0 # No decision: the normal permission flow applies
For most hook events, only exit code 2 blocks the action. Claude Code treats exit code 1 as a non-blocking error and proceeds with the action, even though 1 is the conventional Unix failure code. If your hook is meant to enforce a policy, use `exit 2`. The exception is `WorktreeCreate`, where any non-zero exit code aborts worktree creation.
@@ -671,7 +671,7 @@
JSON output
-Exit 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 for blocking, allowing, or escalating to the user.
+Exit codes only let you block or stay silent, 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 for blocking, allowing, or escalating to the user.
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.
@@ -685,7 +685,7 @@
---|---|---
`continue`| `true`| If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields
`stopReason`| none| Message shown to the user when `continue` is `false`. Not shown to Claude
-`suppressOutput`| `false`| If `true`, omits stdout from the debug log
+`suppressOutput`| `false`| If `true`, hides the hook’s stdout from the transcript. Stdout still appears in the debug log
`systemMessage`| none| Warning message shown to the user
`terminalSequence`| none| A terminal escape sequence for Claude Code to emit on your behalf, such as a desktop notification, window title, or bell. Restricted to OSC `0`/`1`/`2`/`9`/`99`/`777` and BEL. If the value contains anything outside the allowlist, the field is ignored. Use this instead of writing to `/dev/tty`, which is unavailable to hooks
@@ -768,6 +768,7 @@
WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation
Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept)
ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
+SessionStart, Setup, SubagentStart| Context only| `hookSpecificOutput.additionalContext` adds context for Claude. SessionStart also accepts `initialUserMessage` and `watchPaths`. No blocking or decision control
WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged| None| No decision control. Used for side effects like logging or cleanup
Here are examples of each pattern in action:
@@ -862,6 +863,8 @@
Field| Description
---|---
`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it
+`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) (`-p`), where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
+`watchPaths`| Array of absolute paths to watch for FileChanged events during this session
{
"hookSpecificOutput": {
@@ -1050,6 +1053,7 @@
`reason`| Shown to the user when `decision` is `"block"`. Not added to context
`additionalContext`| String added to Claude’s context alongside the submitted prompt. See Add context for Claude
`sessionTitle`| Sets the session title. Use to name sessions automatically based on the prompt content
+`suppressOriginalPrompt`| If `true` when `decision` is `"block"`, omits the original prompt text from the block message shown to the user
{
"decision": "block",
@@ -1406,7 +1410,7 @@
`addRules`| `rules`, `behavior`, `destination`| Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"`
`replaceRules`| `rules`, `behavior`, `destination`| Replaces all rules of the given `behavior` at the `destination` with the provided `rules`
`removeRules`| `rules`, `behavior`, `destination`| Removes matching rules of the given `behavior`
-`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan`
+`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `auto`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan`
`addDirectories`| `directories`, `destination`| Adds working directories. `directories` is an array of path strings
`removeDirectories`| `directories`, `destination`| Removes working directories
@@ -1945,7 +1949,7 @@
`tool`| MCP tool name. Present only for `monitor` and `MCP task` tasks
`name`| Workflow name. Present only for `workflow` tasks
-Each entry in `session_crons` describes one session-scoped scheduled wakeup, sourced from `CronCreate` and `/loop`:
+Each entry in `session_crons` describes one session-scoped scheduled wakeup, sourced from `CronCreate`, `ScheduleWakeup`, and `/loop`:
Field| Description
---|---
@@ -2575,6 +2579,7 @@
In addition to command, HTTP, and MCP tool hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type. Events that support all five hook types (`command`, `http`, `mcp_tool`, `prompt`, and `agent`):
+ * `PermissionDenied`
* `PermissionRequest`
* `PostToolBatch`
* `PostToolUse`
@@ -2584,6 +2589,7 @@
* `SubagentStop`
* `TaskCompleted`
* `TaskCreated`
+ * `TeammateIdle`
* `UserPromptExpansion`
* `UserPromptSubmit`
@@ -2596,13 +2602,11 @@
* `FileChanged`
* `InstructionsLoaded`
* `Notification`
- * `PermissionDenied`
* `PostCompact`
* `PreCompact`
* `SessionEnd`
* `StopFailure`
* `SubagentStart`
- * `TeammateIdle`
* `WorktreeCreate`
* `WorktreeRemove`
@@ -2676,7 +2680,9 @@
* `PostToolUse`: by default the turn ends and the reason appears in the chat as a warning line. Set `continueOnBlock: true` to feed the reason back to Claude and continue the turn instead
* `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears as a warning line. These events end the turn on `decision: "block"` regardless of `continue`
* `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`
+ * `TeammateIdle`: by default the teammate stops and the reason appears as a warning line. Set `continueOnBlock: true` to feed the reason back to the teammate and keep it working instead
* `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
+ * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks cannot set — they run on this event, but their output is discarded. Use a command hook to return `retry`
If you need finer control on any event, use a command hook with the per-event fields described in Decision control.
Show diff (107 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -204,7 +204,7 @@
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`CwdChanged`| no matcher support| always fires on every directory change
`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env`
-`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`UserPromptExpansion`| command name| your skill or command names
`Elicitation`| MCP server name| your configured MCP server names
@@ -1714,7 +1714,7 @@
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "Notification",
- "message": "Claude needs your permission to use Bash",
+ "message": "Claude needs your permission",
"title": "Permission needed",
"notification_type": "permission_prompt"
}
@@ -1773,7 +1773,7 @@
SubagentStop input
-In addition to the 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.
+In addition to the 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. SubagentStop hooks also receive the `background_tasks` and `session_crons` arrays described under Stop input, available in Claude Code v2.1.145 or later. Both arrays are scoped to the parent session, not the subagent.
{
"session_id": "abc123",
@@ -1785,7 +1785,9 @@
"agent_id": "def456",
"agent_type": "Explore",
"agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
- "last_assistant_message": "Analysis complete. Found 3 potential issues..."
+ "last_assistant_message": "Analysis complete. Found 3 potential issues...",
+ "background_tasks": [],
+ "session_crons": []
}
SubagentStop hooks use the same decision control format as Stop hooks. They do not support `additionalContext`. Returning `decision: "block"` with a `reason` keeps the subagent running and delivers `reason` to the subagent as its next instruction. To inject context into the parent session after a subagent returns, use a `PostToolUse` hook on the `Agent` tool instead.
@@ -1929,7 +1931,30 @@
Stop input
-In addition to the 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 avoid blocking on a condition that will never resolve. Claude Code overrides the hook and ends the turn after 8 consecutive blocks. The `last_assistant_message` field contains the text content of Claude’s final response, so hooks can access it without parsing the transcript file.
+In addition to the common input fields, Stop hooks receive `stop_hook_active`, `last_assistant_message`, `background_tasks`, and `session_crons`. 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 avoid blocking on a condition that will never resolve. Claude Code overrides the hook and ends the turn after 8 consecutive blocks. The `last_assistant_message` field contains the text content of Claude’s final response, so hooks can access it without parsing the transcript file. The `background_tasks` and `session_crons` arrays, available in Claude Code v2.1.145 or later, let hooks distinguish “session is done” from “session is paused waiting for background work to wake it back up”. Both arrays are present when the task registry is reachable and are empty when nothing is in flight or scheduled. Each entry in `background_tasks` describes one in-flight task and uses these fields:
+
+Field| Description
+---|---
+`id`| Task identifier
+`type`| Friendly task-type label such as `shell`, `subagent`, `monitor`, `workflow`, `teammate`, `cloud session`, or `MCP task`. Each label identifies which Claude Code feature created the task. Falls back to the raw discriminant for unrecognized types
+`status`| Current task status
+`description`| Free-text description, capped at 1000 characters with an in-string `… [+N chars]` marker when clipped
+`command`| Shell command line, capped at 1000 characters. Present only for `shell` tasks
+`agent_type`| Subagent type name. Present only for `subagent` tasks
+`server`| MCP server name. Present only for `monitor` and `MCP task` tasks
+`tool`| MCP tool name. Present only for `monitor` and `MCP task` tasks
+`name`| Workflow name. Present only for `workflow` tasks
+
+Each entry in `session_crons` describes one session-scoped scheduled wakeup, sourced from `CronCreate` and `/loop`:
+
+Field| Description
+---|---
+`id`| Cron task identifier
+`schedule`| Cron expression, for example `0 9 * * 1-5`
+`recurring`| `false` for one-shot wakeups whose schedule encodes a single fire time, `true` for tasks that re-fire on every match
+`prompt`| Prompt submitted when the cron fires, capped at 1000 characters with the same `… [+N chars]` marker
+
+This example shows a Stop input with one in-flight shell task and one recurring cron:
{
"session_id": "abc123",
@@ -1938,7 +1963,24 @@
"permission_mode": "default",
"hook_event_name": "Stop",
"stop_hook_active": true,
- "last_assistant_message": "I've completed the refactoring. Here's a summary..."
+ "last_assistant_message": "I've completed the refactoring. Here's a summary...",
+ "background_tasks": [
+ {
+ "id": "task-001",
+ "type": "shell",
+ "status": "running",
+ "description": "tail logs",
+ "command": "tail -f /var/log/syslog"
+ }
+ ],
+ "session_crons": [
+ {
+ "id": "cron-001",
+ "schedule": "0 9 * * 1-5",
+ "recurring": true,
+ "prompt": "check the build"
+ }
+ ]
}
####
@@ -1977,7 +2019,7 @@
Field| Description
---|---
-`error`| Error type: `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown`
+`error`| Error type: `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown`
`error_details`| Additional details about the error, when available
`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"`
--- a/hooks.md
+++ b/hooks.md
@@ -1929,7 +1929,7 @@
Stop input
-In addition to the 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.
+In addition to the 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 avoid blocking on a condition that will never resolve. Claude Code overrides the hook and ends the turn after 8 consecutive blocks. The `last_assistant_message` field contains the text content of Claude’s final response, so hooks can access it without parsing the transcript file.
{
"session_id": "abc123",
@@ -2897,4 +2897,4 @@
[DEBUG] Executing hook command: <Your command> with timeout 600000ms
[DEBUG] Hook command completed with status 0: <Your stdout>
-For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide. For a broader diagnostic walkthrough covering `/context`, `/doctor`, and settings precedence, see [Debug your config](</docs/en/debug-your-config>).
+For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, Stop hooks that keep blocking, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide. For a broader diagnostic walkthrough covering `/context`, `/doctor`, and settings precedence, see [Debug your config](</docs/en/debug-your-config>).
Show diff (128 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -301,7 +301,7 @@
---|---|---
`type`| yes| `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"`
`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern, or if a Bash command is too complex to parse. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
-`timeout`| no| Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent
+`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
@@ -546,7 +546,7 @@
Hook input and output
-Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options.
+Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options. On macOS and Linux, command hooks run in their own session without a controlling terminal as of v2.1.139. The hook process and any child processes cannot open `/dev/tty` or send escape sequences directly to the Claude Code interface. Windows has no `/dev/tty`. To surface a message to the user on any platform, return `systemMessage` in JSON output. To trigger a desktop notification, set a window title, or ring the bell, return `terminalSequence` instead.
###
@@ -675,7 +675,7 @@
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.
-Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. Hook output injected into context (`additionalContext`, `systemMessage`, or plain stdout) is capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way large tool results are handled. The JSON object supports three kinds of fields:
+Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. Hook output strings, including `additionalContext`, `systemMessage`, and plain stdout, are capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way large tool results are handled. The JSON object supports three kinds of fields:
* **Universal fields** like `continue` work across all events. These are listed in the table below.
* **Top-level`decision` and `reason`** are used by some events to block or provide feedback.
@@ -687,10 +687,39 @@
`stopReason`| none| Message shown to the user when `continue` is `false`. Not shown to Claude
`suppressOutput`| `false`| If `true`, omits stdout from the debug log
`systemMessage`| none| Warning message shown to the user
+`terminalSequence`| none| A terminal escape sequence for Claude Code to emit on your behalf, such as a desktop notification, window title, or bell. Restricted to OSC `0`/`1`/`2`/`9`/`99`/`777` and BEL. If the value contains anything outside the allowlist, the field is ignored. Use this instead of writing to `/dev/tty`, which is unavailable to hooks
To stop Claude entirely regardless of event type:
{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
+
+####
+
+
+
+Emit terminal notifications
+
+The `terminalSequence` field requires Claude Code v2.1.141 or later. Hooks run without a controlling terminal, so writing escape sequences directly to `/dev/tty` fails. Instead, return the escape sequence in the `terminalSequence` field and Claude Code emits it for you through its own terminal write path. This is race-free, works inside tmux and GNU screen, and works on Windows where there is no `/dev/tty`. The field accepts a string of one or more allowlisted escape sequences:
+
+ * OSC `0`, `1`, `2`: window and icon titles
+ * OSC `9`: iTerm2, ConEmu, Windows Terminal, and WezTerm notifications, including `9;4` taskbar progress
+ * OSC `99`: Kitty notifications
+ * OSC `777`: urxvt, Ghostty, and Warp notifications
+ * Bare BEL
+
+Sequences may be terminated with BEL or with ST. Anything outside the allowlist, including CSI cursor and color sequences, OSC palette sequences, OSC 8 hyperlinks, OSC 52 clipboard writes, and OSC 1337, is rejected and the field is ignored. The example below fires a desktop notification from a `Notification` hook. The escape sequence is built with `printf` octal escapes so the control bytes never appear on the shell command line, and `jq -n --arg` builds the JSON output so quotes, backslashes, and newlines in the notification message are escaped correctly:
+
+ #!/bin/bash
+ # Notification hook: ping the desktop when Claude Code needs attention.
+ input=$(cat)
+ title="Claude Code"
+ body=$(jq -r '.message // "Needs your attention"' <<<"$input")
+ seq=$(printf '\033]777;notify;%s;%s\007' "$title" "$body")
+ jq -nc --arg seq "$seq" '{terminalSequence: $seq}'
+
+The `{ "terminalSequence": "..." }` shape is the same from any shell or language. On Windows, build the escape string in PowerShell or a script and emit the same JSON object.
+
+`terminalSequence` is the supported replacement for hooks that previously wrote escape sequences directly to `/dev/tty`. The allowlist is restricted to sequences that cannot move the cursor or alter colors, so a hook can never corrupt an on-screen prompt.
####
@@ -983,7 +1012,7 @@
UserPromptSubmit
-Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts.
+Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry.
####
@@ -1194,6 +1223,20 @@
`description`| string| `"Find API endpoints"`| Short description of the task
`subagent_type`| string| `"Explore"`| Type of specialized agent to use
`model`| string| `"sonnet"`| Optional model alias to override the default
+
+In `PostToolUse`, `tool_response` for a completed Agent call carries the subagent’s final text along with usage telemetry. Read these fields to record per-subagent cost from a hook:
+
+Field| Type| Example| Description
+---|---|---|---
+`status`| string| `"completed"`| `"completed"` for synchronous calls, `"async_launched"` for `run_in_background: true`
+`agentId`| string| `"a4d2c8f1e0b3a297"`| Identifier for the subagent run
+`content`| array| `[{"type": "text", "text": "Found 12 endpoints..."}]`| The subagent’s final text blocks
+`totalTokens`| number| `12450`| Total tokens billed across the subagent’s turns
+`totalDurationMs`| number| `48211`| Wall-clock duration of the subagent run
+`totalToolUseCount`| number| `7`| Count of tool calls the subagent made
+`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`
+
+For `run_in_background: true` calls, the tool returns immediately after launching the subagent, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, and `outputFile` instead.
##### AskUserQuestion
@@ -2719,7 +2762,7 @@
How async hooks execute
-When 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. After 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. Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
+When 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. After the background process exits, if the hook produced a JSON response with an `additionalContext` field, that content is delivered to Claude as context on the next conversation turn. A `systemMessage` field is shown to you, not to Claude. Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
###
@@ -2741,15 +2784,16 @@
exit 0
fi
- # Run tests and report results via systemMessage
+ # Run tests and report results to Claude via additionalContext
RESULT=$(npm test 2>&1)
EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
- echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
+ MSG="Tests passed after editing $FILE_PATH"
else
- echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
+ MSG="Tests failed after editing $FILE_PATH: $RESULT"
fi
+ jq -nc --arg msg "$MSG" '{hookSpecificOutput: {hookEventName: "PostToolUse", additionalContext: $msg}}'
Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:
Show diff (217 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -67,7 +67,8 @@
{
"type": "command",
"if": "Bash(rm *)",
- "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm.sh"
+ "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
+ "args": []
}
]
}
@@ -316,10 +317,36 @@
Field| Required| Description
---|---|---
-`command`| yes| Shell command to execute
+`command`| yes| Shell command to execute. With `args`, the executable to spawn directly. See Exec form and shell form
+`args`| no| Argument list. When present, `command` is resolved as an executable and spawned directly with `args` as the argument vector, with no shell involved. See Exec form and shell form
`async`| no| If `true`, runs in the background without blocking. See Run hooks in the background
`asyncRewake`| no| If `true`, runs in the background and wakes Claude on exit code 2. Implies `async`. The hook’s stderr, or stdout if stderr is empty, is shown to Claude as a system reminder so it can react to a long-running background failure
-`shell`| no| Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly
+`shell`| no| Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly. Ignored when `args` is set
+
+##### Exec form and shell form
+
+A command hook runs as exec form when `args` is set, and shell form when `args` is omitted. Set `args` whenever the hook references a path placeholder, since each element is passed as one argument with no quoting. Omit `args` when you need shell features like pipes or `&&`, or when neither concern applies. **Exec form** runs when `args` is present. Claude Code resolves `command` as an executable on `PATH` and spawns it directly with `args` as the argument vector. There is no shell, so each `args` element is one argument exactly as written, and path placeholders like `${CLAUDE_PLUGIN_ROOT}` are substituted into `command` and into each `args` element as plain strings. Special characters such as apostrophes, `$`, and backticks pass through verbatim because there is no shell to interpret them. No shell tokenization happens on any platform. **Shell form** runs when `args` is absent. The `command` string is passed to a shell: `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed. Set the `shell` field to choose explicitly. The shell tokenizes the string, expands variables, and interprets pipes, `&&`, redirects, and globs.
+
+On Windows, exec form requires `command` to resolve to a real executable such as a `.exe`. The `.cmd` and `.bat` shims that npm, npx, eslint, and other tools install in `node_modules/.bin` are not executables and cannot be spawned without a shell. To run them in exec form, invoke the underlying script with `node` directly, for example `"command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/node_modules/eslint/bin/eslint.js"]`. The `node` plus script-path pattern works on every platform because `node.exe` is a real binary. To run a `.cmd` or `.bat` shim by name, use shell form.
+
+This example runs a Node script bundled with a plugin. Exec form passes the resolved script path as one argument with no quoting:
+
+ {
+ "type": "command",
+ "command": "node",
+ "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/format.js", "--fix"]
+ }
+
+The equivalent shell form needs quoting to handle paths with spaces or special characters:
+
+ {
+ "type": "command",
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}\"/scripts/format.js --fix"
+ }
+
+Both forms support the same path placeholders, and both export them as the environment variables `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, and `CLAUDE_PLUGIN_DATA` on the spawned process, so a script can read `process.env.CLAUDE_PLUGIN_ROOT` regardless of how it was launched. Plugin hooks additionally substitute `${user_config.*}` values; see [User configuration](</docs/en/plugins-reference#user-configuration>).
+
+In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and do not trigger the warning.
####
@@ -405,7 +432,7 @@
`prompt`| yes| Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON
`model`| no| Model to use for evaluation. Defaults to a fast model
-All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
+All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
###
@@ -413,17 +440,19 @@
Reference scripts by path
-Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
-
- * `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.
+Use these placeholders to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
+
+ * `${CLAUDE_PROJECT_DIR}`: the project root.
* `${CLAUDE_PLUGIN_ROOT}`: the plugin’s installation directory, for scripts bundled with a [plugin](</docs/en/plugins>). Changes on each plugin update.
* `${CLAUDE_PLUGIN_DATA}`: the plugin’s [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>), for dependencies and state that should survive plugin updates.
+Prefer exec form for any hook that references a path placeholder. Exec form passes each `args` element as one argument with no shell tokenization, so paths with spaces or special characters need no quoting. In shell form, wrap each placeholder in double quotes.
+
* Project scripts
* Plugin scripts
-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:
+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:
{
"hooks": {
@@ -433,7 +462,8 @@
"hooks": [
{
"type": "command",
- "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
+ "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh",
+ "args": []
}
]
}
@@ -453,6 +483,7 @@
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
+ "args": [],
"timeout": 30
}
]
@@ -539,9 +570,9 @@
Field| Description
---|---
`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
-`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value.
-
-For example, a `PreToolUse` hook for a Bash command receives this on stdin:
+`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename.
+
+Only `SessionStart` hooks receive a `model` field. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value does not change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
{
"session_id": "abc123",
@@ -1173,6 +1204,18 @@
`questions`| array| `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]`| Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag
`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude does not set this field; supply it via `updatedInput` to answer programmatically
+##### ExitPlanMode
+
+Presents a plan and asks the user to approve it before Claude leaves [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). Claude writes the plan to a file on disk before calling the tool, so the literal `tool_input` from the model only carries `allowedPrompts`. Claude Code injects the plan content and file path before passing the input to hooks.
+
+Field| Type| Example| Description
+---|---|---|---
+`plan`| string| `"## Refactor auth\n1. Extract..."`| Plan content in Markdown. Injected from the plan file on disk
+`planFilePath`| string| `"/Users/.../plans/refactor-auth.md"`| Path to the plan file. Injected
+`allowedPrompts`| array| `[{"tool": "Bash", "prompt": "run tests"}]`| Optional. Prompt-based permissions Claude is requesting to implement the plan, each with a `tool` name and a `prompt` describing the category of action
+
+In `PostToolUse`, `tool_response` is an object with `plan` and `filePath` fields holding the approved plan, plus internal status flags. Read `tool_response.plan` for the plan content rather than re-reading the file from disk.
+
####
@@ -1641,7 +1684,7 @@
SubagentStart
-Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `general-purpose`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).
+Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name. For built-in agents, this is the agent name like `general-purpose`, `Explore`, or `Plan`. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename.
####
@@ -1702,7 +1745,7 @@
"last_assistant_message": "Analysis complete. Found 3 potential issues..."
}
-SubagentStop hooks use the same decision control format as Stop hooks.
+SubagentStop hooks use the same decision control format as Stop hooks. They do not support `additionalContext`. Returning `decision: "block"` with a `reason` keeps the subagent running and delivers `reason` to the subagent as its next instruction. To inject context into the parent session after a subagent returns, use a `PostToolUse` hook on the `Agent` tool instead.
###
@@ -1835,6 +1878,8 @@
Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt. API errors fire StopFailure instead.
+The [`/goal`](</docs/en/goal>) command is a built-in shortcut for a session-scoped prompt-based Stop hook. Use it when you want Claude to keep working until a condition holds without writing hook configuration.
+
####
@@ -1983,7 +2028,8 @@
"hooks": [
{
"type": "command",
- "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
+ "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/audit-config-change.sh",
+ "args": []
}
]
}
@@ -2518,6 +2564,7 @@
`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
`model`| no| Model to use for evaluation. Defaults to a fast model
`timeout`| no| Timeout in seconds. Default: 30
+`continueOnBlock`| no| When the prompt returns `ok: false`, feed the reason back to Claude and continue the turn instead of stopping. Default: `false`. Implemented as `continue: true` on the resulting `decision: "block"`. See Response schema for per-event behavior
###
@@ -2534,14 +2581,15 @@
Field| Description
---|---
-`ok`| `true` to allow, `false` to block. See the per-event behavior below
-`reason`| Required when `ok` is `false`. Explanation for the decision
+`ok`| `true` to allow. `false` produces a `decision: "block"`. See the per-event behavior below
+`reason`| Required when `ok` is `false`. Used as the block reason
What happens on `ok: false` depends on the event:
* `Stop` and `SubagentStop`: the reason is fed back to Claude as its next instruction and the turn continues
* `PreToolUse`: the tool call is denied and the reason is returned to Claude as the tool error, equivalent to a command hook’s `permissionDecision: "deny"`
- * `PostToolUse`, `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears in the chat as a warning line, equivalent to returning `"continue": false` from a command hook
+ * `PostToolUse`: by default the turn ends and the reason appears in the chat as a warning line. Set `continueOnBlock: true` to feed the reason back to Claude and continue the turn instead
+ * `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears as a warning line. These events end the turn on `decision: "block"` regardless of `continue`
* `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`
* `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
@@ -2713,7 +2761,8 @@
"hooks": [
{
"type": "command",
- "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",
+ "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/run-tests-async.sh",
+ "args": [],
"async": true,
"timeout": 300
}
@@ -2763,7 +2812,7 @@
* **Validate and sanitize inputs** : never trust input data blindly
* **Always quote shell variables** : use `"$VAR"` not `$VAR`
* **Block path traversal** : check for `..` in file paths
- * **Use absolute paths** : specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root
+ * **Use absolute paths** : specify full paths for scripts. In exec form, use `${CLAUDE_PROJECT_DIR}` and the path needs no quoting. In shell form, wrap it in double quotes
* **Skip sensitive files** : avoid `.env`, `.git/`, keys, etc.
##
--- a/hooks.md
+++ b/hooks.md
@@ -1240,7 +1240,7 @@
There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
-`--resume` does not restore the permission mode from the prior session. Pass the same `--permission-mode` flag on resume that was active when the tool was deferred. Claude Code logs a warning if the modes differ.
+`--resume` restores the permission mode that was active when the tool was deferred, so you do not need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.
###
--- a/hooks.md
+++ b/hooks.md
@@ -531,6 +531,7 @@
`transcript_path`| Path to conversation JSON
`cwd`| Current working directory when the hook is invoked
`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
+`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested effort exceeds what the current model supports, this is the downgraded level the model actually used, not the level you requested. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable.
`hook_event_name`| Name of the event that fired
When running with `--agent` or inside a subagent, two additional fields are included:
--- a/hooks.md
+++ b/hooks.md
@@ -1385,7 +1385,7 @@
Field| Description
---|---
-`decision`| `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed
+`decision`| `"block"` adds the `reason` next to the tool result. Claude still sees the original output; to replace it, use `updatedToolOutput`
`reason`| Explanation shown to Claude when `decision` is `"block"`
`additionalContext`| String added to Claude’s context alongside the tool result. See Add context for Claude
`updatedToolOutput`| Replaces the tool’s output with the provided value before it is sent to Claude. The value must match the tool’s output shape
@@ -2533,8 +2533,8 @@
Field| Description
---|---
-`ok`| `true` allows the action, `false` blocks it
-`reason`| Required when `ok` is `false`. Explanation for the block
+`ok`| `true` to allow, `false` to block. See the per-event behavior below
+`reason`| Required when `ok` is `false`. Explanation for the decision
What happens on `ok: false` depends on the event:
--- a/hooks.md
+++ b/hooks.md
@@ -988,7 +988,7 @@
`decision`| `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed
`reason`| Shown to the user when `decision` is `"block"`. Not added to context
`additionalContext`| String added to Claude’s context alongside the submitted prompt. See Add context for Claude
-`sessionTitle`| Sets the session title, same effect as `/rename`. Use to name sessions automatically based on the prompt content
+`sessionTitle`| Sets the session title. Use to name sessions automatically based on the prompt content
{
"decision": "block",
@@ -2536,7 +2536,15 @@
`ok`| `true` allows the action, `false` blocks it
`reason`| Required when `ok` is `false`. Explanation for the block
-For `Stop` and `SubagentStop`, an `ok: false` reason is fed back to Claude as its next instruction and the turn continues. For all other supported events, the turn ends and the reason appears in the chat as a warning line; Claude does not see it. This is equivalent to returning `"continue": false` from a command hook. If you need different blocking semantics on those events, use a command hook with the per-event fields described in Decision control.
+What happens on `ok: false` depends on the event:
+
+ * `Stop` and `SubagentStop`: the reason is fed back to Claude as its next instruction and the turn continues
+ * `PreToolUse`: the tool call is denied and the reason is returned to Claude as the tool error, equivalent to a command hook’s `permissionDecision: "deny"`
+ * `PostToolUse`, `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears in the chat as a warning line, equivalent to returning `"continue": false` from a command hook
+ * `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`
+ * `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
+
+If you need finer control on any event, use a command hook with the per-event fields described in Decision control.
###
--- a/hooks.md
+++ b/hooks.md
@@ -2533,8 +2533,10 @@
Field| Description
---|---
-`ok`| `true` allows the action, `false` prevents it
-`reason`| Required when `ok` is `false`. Explanation shown to Claude
+`ok`| `true` allows the action, `false` blocks it
+`reason`| Required when `ok` is `false`. Explanation for the block
+
+For `Stop` and `SubagentStop`, an `ok: false` reason is fed back to Claude as its next instruction and the turn continues. For all other supported events, the turn ends and the reason appears in the chat as a warning line; Claude does not see it. This is equivalent to returning `"continue": false` from a command hook. If you need different blocking semantics on those events, use a command hook with the per-event fields described in Decision control.
###
--- a/hooks.md
+++ b/hooks.md
@@ -2121,7 +2121,7 @@
WorktreeCreate
-When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/common-workflows#copy-gitignored-files-to-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
{
"hooks": {
--- a/hooks.md
+++ b/hooks.md
@@ -203,7 +203,7 @@
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`CwdChanged`| no matcher support| always fires on every directory change
`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env`
-`StopFailure`| error type| `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`UserPromptExpansion`| command name| your skill or command names
`Elicitation`| MCP server name| your configured MCP server names
@@ -1888,7 +1888,7 @@
Field| Description
---|---
-`error`| Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown`
+`error`| Error type: `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown`
`error_details`| Additional details about the error, when available
`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"`
Show diff (271 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -1,3 +1,9 @@
+> ## Documentation Index
+>
+> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
+>
+> Use this file to discover all available pages before exploring further.
+
For a quickstart guide with examples, see [Automate workflows with hooks](</docs/en/hooks-guide>).
Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you’re setting up hooks for the first time, start with the [guide](</docs/en/hooks-guide>) instead.
@@ -15,6 +21,7 @@
Event| When it fires
---|---
`SessionStart`| When a session begins or resumes
+`Setup`| When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
@@ -187,9 +194,10 @@
---|---|---
`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
+`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`
-`SubagentStart`| agent type| `Bash`, `Explore`, `Plan`, or custom agent names
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`
+`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
@@ -597,6 +605,7 @@
`Notification`| No| Shows stderr to user only
`SubagentStart`| No| Shows stderr to user only
`SessionStart`| No| Shows stderr to user only
+`Setup`| No| Shows stderr to user only
`SessionEnd`| No| Shows stderr to user only
`CwdChanged`| No| Shows stderr to user only
`FileChanged`| No| Shows stderr to user only
@@ -650,6 +659,35 @@
To stop Claude entirely regardless of event type:
{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
+
+####
+
+
+
+Add context for Claude
+
+The `additionalContext` field passes a string from your hook into Claude’s context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it does not appear as a chat message in the interface. Return `additionalContext` inside `hookSpecificOutput` alongside the event name:
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUse",
+ "additionalContext": "This file is generated. Edit src/schema.ts and run `bun generate` instead."
+ }
+ }
+
+Where the reminder appears depends on the event:
+
+ * SessionStart, Setup, and SubagentStart: at the start of the conversation, before the first prompt
+ * UserPromptSubmit and UserPromptExpansion: alongside the submitted prompt
+ * PreToolUse, PostToolUse, PostToolUseFailure, and PostToolBatch: next to the tool result
+
+When several hooks return `additionalContext` for the same event, Claude receives all of the values. If a value exceeds 10,000 characters, Claude Code writes the full text to a file in the session directory and passes Claude the file path with a short preview instead. Use `additionalContext` for information Claude should know about the current state of your environment or the operation that just ran:
+
+ * **Environment state** : the current branch, deployment target, or active feature flags
+ * **Conditional project rules** : which test command applies to the file just edited, which directories are read-only in this worktree
+ * **External data** : open issues assigned to you, recent CI results, content fetched from an internal service
+
+For instructions that never change, prefer [CLAUDE.md](</docs/en/memory>). It loads without running a script and is the standard place for static project conventions. Write the text as factual statements rather than imperative system instructions. Phrasing such as “The deployment target is production” or “This repo uses `bun test`” reads as project information. Text framed as out-of-band system commands can trigger Claude’s prompt-injection defenses, which causes Claude to surface the text to you instead of treating it as context. Once injected, the text is saved in the session transcript. For mid-session events like `PostToolUse` or `UserPromptSubmit`, resuming with `--continue` or `--resume` replays the saved text rather than re-running the hook for past turns, so values like timestamps or commit SHAs become stale on resume. `SessionStart` hooks run again on resume with `source` set to `"resume"`, so they can refresh their context.
####
@@ -762,14 +800,16 @@
Field| Description
---|---
-`additionalContext`| String added to Claude’s context. Multiple hooks’ values are concatenated
+`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it
{
"hookSpecificOutput": {
"hookEventName": "SessionStart",
- "additionalContext": "My additional context here"
- }
- }
+ "additionalContext": "Current branch: feat/auth-refactor\nUncommitted changes: src/auth.ts, src/login.tsx\nActive issue: #4211 Migrate to OAuth2"
+ }
+ }
+
+Since plain stdout already reaches Claude for this event, a hook that only loads context can print to stdout directly without building JSON. Use the JSON form when you need to combine context with other fields such as `suppressOutput`.
####
@@ -808,7 +848,59 @@
Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
-`CLAUDE_ENV_FILE` is available for SessionStart, CwdChanged, and FileChanged hooks. Other hook types do not have access to this variable.
+`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types do not have access to this variable.
+
+###
+
+
+
+Setup
+
+Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in print mode (`-p`). It does not fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use SessionStart instead. The matcher value corresponds to the CLI flag that triggered the hook:
+
+Matcher| When it fires
+---|---
+`init`| `claude --init-only` or `claude -p --init`
+`maintenance`| `claude -p --maintenance`
+
+`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p` (print mode); in an interactive session those two flags do not currently fire Setup hooks. Because Setup does not fire on every launch, a plugin that needs a dependency installed cannot rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
+
+####
+
+
+
+Setup input
+
+In addition to the common input fields, Setup hooks receive a `trigger` field set to either `"init"` or `"maintenance"`:
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "Setup",
+ "trigger": "init"
+ }
+
+####
+
+
+
+Setup decision control
+
+Setup hooks cannot block. On exit code 2, stderr is shown to the user; on any other non-zero exit code, stderr appears only when you launch with `--verbose`. In both cases execution continues. To pass information into Claude’s context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
+
+Field| Description
+---|---
+`additionalContext`| String added to Claude’s context. Multiple hooks’ values are concatenated
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "Setup",
+ "additionalContext": "Dependencies installed: node_modules, .venv"
+ }
+ }
+
+Setup hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` and `type: "mcp_tool"` hooks are supported.
###
@@ -895,7 +987,7 @@
---|---
`decision`| `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed
`reason`| Shown to the user when `decision` is `"block"`. Not added to context
-`additionalContext`| String added to Claude’s context
+`additionalContext`| String added to Claude’s context alongside the submitted prompt. See Add context for Claude
`sessionTitle`| Sets the session title, same effect as `/rename`. Use to name sessions automatically based on the prompt content
{
@@ -951,7 +1043,7 @@
---|---
`decision`| `"block"` prevents the slash command from expanding. Omit to allow it to proceed
`reason`| Shown to the user when `decision` is `"block"`
-`additionalContext`| String added to Claude’s context alongside the expanded prompt
+`additionalContext`| String added to Claude’s context alongside the expanded prompt. See Add context for Claude
{
"decision": "block",
@@ -1093,7 +1185,7 @@
`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored
`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
-`additionalContext`| String added to Claude’s context before the tool executes. For `"defer"`, ignored
+`additionalContext`| String added to Claude’s context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See Add context for Claude
When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`. When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
@@ -1295,7 +1387,7 @@
---|---
`decision`| `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed
`reason`| Explanation shown to Claude when `decision` is `"block"`
-`additionalContext`| Additional context for Claude to consider
+`additionalContext`| String added to Claude’s context alongside the tool result. See Add context for Claude
`updatedToolOutput`| Replaces the tool’s output with the provided value before it is sent to Claude. The value must match the tool’s output shape
`updatedMCPToolOutput`| Replaces the output for MCP tools only. Prefer `updatedToolOutput`, which works for all tools
@@ -1365,7 +1457,7 @@
Field| Description
---|---
-`additionalContext`| Additional context for Claude to consider alongside the error
+`additionalContext`| String added to Claude’s context alongside the error. See Add context for Claude
{
"hookSpecificOutput": {
@@ -1426,7 +1518,7 @@
Field| Description
---|---
-`additionalContext`| Context string injected once before the next model call
+`additionalContext`| Context string injected once before the next model call. See Add context for Claude for delivery details, what to put in it, and how resumed sessions handle past values
{
"hookSpecificOutput": {
@@ -1434,8 +1526,6 @@
"additionalContext": "These files are part of the ledger module. Run pytest before marking the task complete."
}
}
-
-Injected `additionalContext` is persisted to the session transcript. On `--continue` or `--resume`, the saved text is replayed from disk and the hook does not re-run for past turns. Prefer static context such as conventions or file-type guidance over dynamic values like timestamps or the current commit SHA, since those become stale on resume.Frame the context as factual information rather than imperative system instructions. Text written as out-of-band system commands can trigger Claude’s prompt-injection defenses, which surfaces the injection to the user instead of acting on it.
Returning `decision: "block"` or `continue: false` stops the agentic loop before the next model call.
@@ -1497,7 +1587,7 @@
Notification
-Runs 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. Use 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:
+Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`. Omit the matcher to run hooks for all notification types. Use 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:
{
"hooks": {
@@ -1542,11 +1632,7 @@
"notification_type": "permission_prompt"
}
-Notification hooks cannot block or modify notifications. In addition to the JSON output fields available to all hooks, you can return `additionalContext` to add context to the conversation:
-
-Field| Description
----|---
-`additionalContext`| String added to Claude’s context
+Notification hooks cannot block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The common JSON output fields such as `systemMessage` apply.
###
@@ -1554,7 +1640,7 @@
SubagentStart
-Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).
+Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `general-purpose`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).
####
@@ -1562,7 +1648,7 @@
SubagentStart input
-In addition to the 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).
+In addition to the 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 `"general-purpose"`, `"Explore"`, `"Plan"`, or custom agent names).
{
"session_id": "abc123",
@@ -1577,7 +1663,7 @@
Field| Description
---|---
-`additionalContext`| String added to the subagent’s context
+`additionalContext`| String added to the subagent’s context at the start of its conversation, before its first prompt. See Add context for Claude
{
"hookSpecificOutput": {
--- a/hooks.md
+++ b/hooks.md
@@ -1296,16 +1296,25 @@
`decision`| `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed
`reason`| Explanation shown to Claude when `decision` is `"block"`
`additionalContext`| Additional context for Claude to consider
-`updatedMCPToolOutput`| For MCP tools only: replaces the tool’s output with the provided value
-
- {
- "decision": "block",
- "reason": "Explanation for decision",
+`updatedToolOutput`| Replaces the tool’s output with the provided value before it is sent to Claude. The value must match the tool’s output shape
+`updatedMCPToolOutput`| Replaces the output for MCP tools only. Prefer `updatedToolOutput`, which works for all tools
+
+The example below replaces the output of a `Bash` call. The replacement value matches the `Bash` tool’s output shape:
+
+ {
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
- "additionalContext": "Additional information for Claude"
- }
- }
+ "additionalContext": "Additional information for Claude",
+ "updatedToolOutput": {
+ "stdout": "[redacted]",
+ "stderr": "",
+ "interrupted": false,
+ "isImage": false
+ }
+ }
+ }
+
+`updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a PreToolUse hook instead.The replacement value must match the tool’s output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that does not match the tool’s output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption.
###
--- a/hooks.md
+++ b/hooks.md
@@ -1275,8 +1275,13 @@
"filePath": "/path/to/file.txt",
"success": true
},
- "tool_use_id": "toolu_01ABC123..."
- }
+ "tool_use_id": "toolu_01ABC123...",
+ "duration_ms": 12
+ }
+
+Field| Description
+---|---
+`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks
####
@@ -1331,13 +1336,15 @@
},
"tool_use_id": "toolu_01ABC123...",
"error": "Command exited with non-zero status code 1",
- "is_interrupt": false
+ "is_interrupt": false,
+ "duration_ms": 4187
}
Field| Description
---|---
`error`| String describing what went wrong
`is_interrupt`| Optional boolean indicating whether the failure was caused by user interruption
+`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks
####
Show diff (248 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -22,6 +22,7 @@
`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
`PostToolUse`| After a tool call succeeds
`PostToolUseFailure`| After a tool call fails
+`PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call
`Notification`| When Claude Code sends a notification
`SubagentStart`| When a subagent is spawned
`SubagentStop`| When a subagent finishes
@@ -145,7 +146,7 @@
See How a hook resolves above for a complete walkthrough with an annotated example.
-This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, prompt, or agent that runs. “Hook” on its own refers to the general feature.
+This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, MCP tool, prompt, or agent that runs. “Hook” on its own refers to the general feature.
###
@@ -199,7 +200,7 @@
`UserPromptExpansion`| command name| your skill or command names
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
+`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
The matcher runs against a field from the JSON input that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file:
@@ -219,7 +220,7 @@
}
}
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
+`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
####
@@ -271,10 +272,11 @@
Hook handler fields
-Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, LLM prompt, or agent that runs when the matcher matches. There are four types:
+Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, MCP tool, LLM prompt, or agent that runs when the matcher matches. There are five types:
* **Command hooks** (`type: "command"`): run a shell command. Your script receives the event’s JSON input on stdin and communicates results back through exit codes and stdout.
* **HTTP hooks** (`type: "http"`): send the event’s JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same JSON output format as command hooks.
+ * **MCP tool hooks** (`type: "mcp_tool"`): call a tool on an already-connected [MCP server](</docs/en/mcp>). The tool’s text output is treated like command-hook stdout.
* **Prompt hooks** (`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.
* **Agent hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks.
@@ -288,8 +290,8 @@
Field| Required| Description
---|---|---
-`type`| yes| `"command"`, `"http"`, `"prompt"`, or `"agent"`
-`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern, or if a Bash command is too complex to parse. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
+`type`| yes| `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"`
+`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern, or if a Bash command is too complex to parse. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
`timeout`| no| Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
@@ -352,6 +354,40 @@
+MCP tool hook fields
+
+In addition to the common fields, MCP tool hooks accept these fields:
+
+Field| Required| Description
+---|---|---
+`server`| yes| Name of a configured MCP server. The server must already be connected; the hook never triggers an OAuth or connection flow
+`tool`| yes| Name of the tool to call on that server
+`input`| no| Arguments passed to the tool. String values support `${path}` substitution from the hook’s JSON input, such as `"${tool_input.file_path}"`
+
+The tool’s text content is treated like command-hook stdout: if it parses as valid JSON output it is processed as a decision, otherwise it is shown as plain text. If the named server is not connected, or the tool returns `isError: true`, the hook produces a non-blocking error and execution continues. MCP tool hooks are available on every hook event once Claude Code has connected to your MCP servers. `SessionStart` and `Setup` typically fire before servers finish connecting, so hooks on those events should expect the “not connected” error on first run. This example calls the `security_scan` tool on the `my_server` MCP server after each `Write` or `Edit`, passing the edited file’s path:
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Write|Edit",
+ "hooks": [
+ {
+ "type": "mcp_tool",
+ "server": "my_server",
+ "tool": "security_scan",
+ "input": { "file_path": "${tool_input.file_path}" }
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+####
+
+
+
Prompt and agent hook fields
In addition to the common fields, prompt and agent hooks accept these fields:
@@ -446,7 +482,7 @@
The `/hooks` menu
-Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook’s command, prompt, or URL. The menu displays all four hook types: `command`, `prompt`, `agent`, and `http`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:
+Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook’s command, prompt, or URL. The menu displays all five hook types: `command`, `prompt`, `agent`, `http`, and `mcp_tool`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:
* `User`: from `~/.claude/settings.json`
* `Project`: from `.claude/settings.json`
@@ -556,6 +592,7 @@
`StopFailure`| No| Output and exit code are ignored
`PostToolUse`| No| Shows stderr to Claude (tool already ran)
`PostToolUseFailure`| No| Shows stderr to Claude (tool already failed)
+`PostToolBatch`| Yes| Stops the agentic loop before the next model call
`PermissionDenied`| No| Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry
`Notification`| No| Shows stderr to user only
`SubagentStart`| No| Shows stderr to user only
@@ -624,7 +661,7 @@
Events| Decision pattern| Key fields
---|---|---
-UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`
+UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`
TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason`
PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
@@ -642,7 +679,7 @@
* PermissionRequest
-Used by `UserPromptSubmit`, `UserPromptExpansion`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
+Used by `UserPromptSubmit`, `UserPromptExpansion`, `PostToolUse`, `PostToolUseFailure`, `PostToolBatch`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
{
"decision": "block",
@@ -689,7 +726,7 @@
SessionStart
-Runs 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](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported. The matcher value corresponds to how the session was initiated:
+Runs 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](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. The matcher value corresponds to how the session was initiated:
Matcher| When it fires
---|---
@@ -1320,6 +1357,71 @@
"additionalContext": "Additional information about the failure for Claude"
}
}
+
+###
+
+
+
+PostToolBatch
+
+Runs once after every tool call in a batch has resolved, before Claude Code sends the next request to the model. `PostToolUse` fires once per tool, which means it fires concurrently when Claude makes parallel tool calls. `PostToolBatch` fires exactly once with the full batch, so it is the right place to inject context that depends on the set of tools that ran rather than on any single tool. There is no matcher for this event.
+
+####
+
+
+
+PostToolBatch input
+
+In addition to the common input fields, PostToolBatch hooks receive `tool_calls`, an array describing every tool call in the batch:
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolBatch",
+ "tool_calls": [
+ {
+ "tool_name": "Read",
+ "tool_input": {"file_path": "/.../ledger/accounts.py"},
+ "tool_use_id": "toolu_01...",
+ "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."
+ },
+ {
+ "tool_name": "Read",
+ "tool_input": {"file_path": "/.../ledger/transactions.py"},
+ "tool_use_id": "toolu_02...",
+ "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."
+ }
+ ]
+ }
+
+`tool_response` contains the same content the model receives in the corresponding `tool_result` block. The value is a serialized string or content-block array, exactly as the tool emitted it. For `Read`, that means line-number-prefixed text rather than raw file contents. Responses can be large, so parse only the fields you need.
+
+The `tool_response` shape differs from `PostToolUse`’s. `PostToolUse` passes the tool’s structured `Output` object, such as `{filePath: "...", success: true}` for `Write`; `PostToolBatch` passes the serialized `tool_result` content the model sees.
+
+####
+
+
+
+PostToolBatch decision control
+
+`PostToolBatch` hooks can inject context for Claude. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
+
+Field| Description
+---|---
+`additionalContext`| Context string injected once before the next model call
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolBatch",
+ "additionalContext": "These files are part of the ledger module. Run pytest before marking the task complete."
+ }
+ }
+
+Injected `additionalContext` is persisted to the session transcript. On `--continue` or `--resume`, the saved text is replayed from disk and the hook does not re-run for past turns. Prefer static context such as conventions or file-type guidance over dynamic values like timestamps or the current commit SHA, since those become stale on resume.Frame the context as factual information rather than imperative system instructions. Text written as out-of-band system commands can trigger Claude’s prompt-injection defenses, which surfaces the injection to the user instead of acting on it.
+
+Returning `decision: "block"` or `continue: false` stops the agentic loop before the next model call.
###
@@ -2237,9 +2339,10 @@
Prompt-based hooks
-In addition to command and HTTP hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type. Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):
+In addition to command, HTTP, and MCP tool hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type. Events that support all five hook types (`command`, `http`, `mcp_tool`, `prompt`, and `agent`):
* `PermissionRequest`
+ * `PostToolBatch`
* `PostToolUse`
* `PostToolUseFailure`
* `PreToolUse`
@@ -2250,7 +2353,7 @@
* `UserPromptExpansion`
* `UserPromptSubmit`
-Events that support `command` and `http` hooks but not `prompt` or `agent`:
+Events that support `command`, `http`, and `mcp_tool` hooks but not `prompt` or `agent`:
* `ConfigChange`
* `CwdChanged`
@@ -2269,7 +2372,7 @@
* `WorktreeCreate`
* `WorktreeRemove`
-`SessionStart` supports only `command` hooks.
+`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They do not support `http`, `prompt`, or `agent` hooks.
###
--- a/hooks.md
+++ b/hooks.md
@@ -1108,7 +1108,7 @@
}
}
-There is no timeout or retry limit. The session remains on disk until you resume it. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
+There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
`--resume` does not restore the permission mode from the prior session. Pass the same `--permission-mode` flag on resume that was active when the tool was deferred. Claude Code logs a warning if the modes differ.
Show diff (144 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -16,6 +16,7 @@
---|---
`SessionStart`| When a session begins or resumes
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
+`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
`PermissionRequest`| When a permission dialog appears
`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
@@ -195,6 +196,7 @@
`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env`
`StopFailure`| error type| `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
+`UserPromptExpansion`| command name| your skill or command names
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
@@ -516,7 +518,7 @@
Exit code output
-The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr, so you can identify the cause without `--debug`. Execution continues and the full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
+The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr, so you can identify the cause without `--debug`. Execution continues and the full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
#!/bin/bash
# Reads JSON input from stdin, checks the command
@@ -544,6 +546,7 @@
`PreToolUse`| Yes| Blocks the tool call
`PermissionRequest`| Yes| Denies the permission
`UserPromptSubmit`| Yes| Blocks prompt processing and erases the prompt
+`UserPromptExpansion`| Yes| Blocks the expansion
`Stop`| Yes| Prevents Claude from stopping, continues the conversation
`SubagentStop`| Yes| Prevents the subagent from stopping
`TeammateIdle`| Yes| Prevents the teammate from going idle (teammate continues working)
@@ -621,7 +624,7 @@
Events| Decision pattern| Key fields
---|---|---
-UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`
+UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`
TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason`
PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
@@ -639,7 +642,7 @@
* PermissionRequest
-Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
+Used by `UserPromptSubmit`, `UserPromptExpansion`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
{
"decision": "block",
@@ -869,6 +872,58 @@
}
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 block prompts or want more structured control.
+
+###
+
+
+
+UserPromptExpansion
+
+Runs when a user-typed slash command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team’s review checklist as `additionalContext`. This event covers the path `PreToolUse` does not: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path. Matches on `command_name`. Leave the matcher empty to fire on every prompt-type slash command.
+
+####
+
+
+
+UserPromptExpansion input
+
+In addition to the common input fields, UserPromptExpansion hooks receive `expansion_type`, `command_name`, `command_args`, `command_source`, and the original `prompt` string. The `expansion_type` field is `slash_command` for skill and custom commands, or `mcp_prompt` for MCP server prompts.
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../00893aaf.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "UserPromptExpansion",
+ "expansion_type": "slash_command",
+ "command_name": "example-skill",
+ "command_args": "arg1 arg2",
+ "command_source": "plugin",
+ "prompt": "/example-skill arg1 arg2"
+ }
+
+####
+
+
+
+UserPromptExpansion decision control
+
+`UserPromptExpansion` hooks can block the expansion or add context. All JSON output fields are available.
+
+Field| Description
+---|---
+`decision`| `"block"` prevents the slash command from expanding. Omit to allow it to proceed
+`reason`| Shown to the user when `decision` is `"block"`
+`additionalContext`| String added to Claude’s context alongside the expanded prompt
+
+ {
+ "decision": "block",
+ "reason": "This slash command is not available",
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptExpansion",
+ "additionalContext": "Additional context for this expansion"
+ }
+ }
###
@@ -1774,7 +1829,7 @@
CwdChanged
-Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` hooks are supported. CwdChanged does not support matchers and fires on every directory change.
+Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. CwdChanged does not support matchers and fires on every directory change.
####
@@ -1818,7 +1873,7 @@
* **Build the watch list** : the value is split on `|` and each segment is registered as a literal filename in the working directory, so `".envrc|.env"` watches exactly those two files. Regex patterns are not useful here: a value like `^\.env` would watch a file literally named `^\.env`.
* **Filter which hooks run** : when a watched file changes, the same value filters which hook groups run using the standard matcher rules against the changed file’s basename.
-FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` hooks are supported.
+FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks.
####
@@ -2192,6 +2247,7 @@
* `SubagentStop`
* `TaskCompleted`
* `TaskCreated`
+ * `UserPromptExpansion`
* `UserPromptSubmit`
Events that support `command` and `http` hooks but not `prompt` or `agent`:
@@ -2532,4 +2588,4 @@
[DEBUG] Executing hook command: <Your command> with timeout 600000ms
[DEBUG] Hook command completed with status 0: <Your stdout>
-For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide.
+For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide. For a broader diagnostic walkthrough covering `/context`, `/doctor`, and settings precedence, see [Debug your config](</docs/en/debug-your-config>).
--- a/hooks.md
+++ b/hooks.md
@@ -47,7 +47,7 @@
How a hook resolves
-To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The `matcher` narrows to Bash tool calls and the `if` condition narrows further to commands starting with `rm`, so `block-rm.sh` only spawns when both filters match:
+To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The `matcher` narrows to Bash tool calls and the `if` condition narrows further to Bash subcommands matching `rm *`, so `block-rm.sh` only spawns when both filters match:
{
"hooks": {
@@ -104,7 +104,7 @@
If condition checks
-The `if` condition `"Bash(rm *)"` matches because the command starts with `rm`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs.
+The `if` condition `"Bash(rm *)"` matches because `rm -rf /tmp/build` is a subcommand matching `rm *`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs.
4
@@ -217,7 +217,7 @@
}
}
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs only for `git` commands and `"Edit(*.ts)"` runs only for TypeScript files.
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.
####
@@ -274,7 +274,7 @@
* **Command hooks** (`type: "command"`): run a shell command. Your script receives the event’s JSON input on stdin and communicates results back through exit codes and stdout.
* **HTTP hooks** (`type: "http"`): send the event’s JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same JSON output format as command hooks.
* **Prompt hooks** (`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.
- * **Agent hooks** (`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 hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks.
####
@@ -287,10 +287,12 @@
Field| Required| Description
---|---|---
`type`| yes| `"command"`, `"http"`, `"prompt"`, or `"agent"`
-`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
+`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern, or if a Bash command is too complex to parse. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
`timeout`| no| Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
+
+The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. For Bash, the rule is matched against each subcommand of the tool input after leading `VAR=value` assignments are stripped, so `if: "Bash(git push *)"` matches both `FOO=bar git push` and `npm test && git push`. The hook runs if any subcommand matches, and always runs when the command is too complex to parse.
####
@@ -2303,6 +2305,8 @@
Agent-based hooks
+Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer command hooks.
+
Agent-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.
###
--- a/hooks.md
+++ b/hooks.md
@@ -290,7 +290,7 @@
`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
`timeout`| no| Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent
`statusMessage`| no| Custom spinner message displayed while the hook runs
-`once`| no| If `true`, runs only once per session then is removed. Skills only, not agents. See Hooks in skills and agents
+`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter
####
--- a/hooks.md
+++ b/hooks.md
@@ -1102,8 +1102,8 @@
Field| Description
---|---
-`behavior`| `"allow"` grants the permission, `"deny"` denies it
-`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones
+`behavior`| `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated, so a hook returning `"allow"` does not override a matching deny rule
+`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. The modified input is re-evaluated against deny and ask rules
`updatedPermissions`| For `"allow"` only: array of permission update entries to apply, such as adding an allow rule or changing the session permission mode
`message`| For `"deny"` only: tells Claude why the permission was denied
`interrupt`| For `"deny"` only: if `true`, stops Claude
@@ -1136,6 +1136,8 @@
`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan`
`addDirectories`| `directories`, `destination`| Adds working directories. `directories` is an array of path strings
`removeDirectories`| `directories`, `destination`| Removes working directories
+
+`setMode` with `bypassPermissions` only takes effect if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and the mode is not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). Otherwise the update is a no-op. `bypassPermissions` is never persisted as `defaultMode` regardless of `destination`.
The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.
--- a/hooks.md
+++ b/hooks.md
@@ -304,6 +304,7 @@
---|---|---
`command`| yes| Shell command to execute
`async`| no| If `true`, runs in the background without blocking. See Run hooks in the background
+`asyncRewake`| no| If `true`, runs in the background and wakes Claude on exit code 2. Implies `async`. The hook’s stderr, or stdout if stderr is empty, is shown to Claude as a system reminder so it can react to a long-running background failure
`shell`| no| Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly
####
@@ -557,7 +558,7 @@
`SessionEnd`| No| Shows stderr to user only
`CwdChanged`| No| Shows stderr to user only
`FileChanged`| No| Shows stderr to user only
-`PreCompact`| No| Shows stderr to user only
+`PreCompact`| Yes| Blocks compaction
`PostCompact`| No| Shows stderr to user only
`Elicitation`| Yes| Denies the elicitation
`ElicitationResult`| Yes| Blocks the response (action becomes decline)
@@ -618,7 +619,7 @@
Events| Decision pattern| Key fields
---|---|---
-UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange| Top-level `decision`| `decision: "block"`, `reason`
+UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`
TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason`
PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
@@ -626,7 +627,7 @@
WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation
Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept)
ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
-WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged| None| No decision control. Used for side effects like logging or cleanup
+WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged| None| No decision control. Used for side effects like logging or cleanup
Here are examples of each pattern in action:
@@ -636,7 +637,7 @@
* PermissionRequest
-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:
+Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:
{
"decision": "block",
@@ -995,7 +996,7 @@
Field| Description
---|---
-`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) still apply when a hook returns `"allow"`
+`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored
`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
`additionalContext`| String added to Claude’s context before the tool executes. For `"defer"`, ignored
@@ -1959,6 +1960,8 @@
`manual`| `/compact`
`auto`| Auto-compact when the context window is full
+Exit with code 2 to block compaction. For a manual `/compact`, the stderr message is shown to the user. You can also block by returning JSON with `"decision": "block"`. Blocking automatic compaction has different effects depending on when it fires. If compaction was triggered proactively before the context limit, Claude Code skips it and the conversation continues uncompacted. If compaction was triggered to recover from a context-limit error already returned by the API, the underlying error surfaces and the current request fails.
+
####
@@ -2041,7 +2044,7 @@
"reason": "other"
}
-SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.
+SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If a hook needs more time, set a per-hook `timeout` in the hook configuration. The overall budget is automatically raised to the highest per-hook timeout configured in settings files, up to 60 seconds. Timeouts set on plugin-provided hooks do not raise the budget. To override the budget explicitly, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable in milliseconds.
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
@@ -2452,7 +2455,7 @@
* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.
* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
- * Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.
+ * Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction. Exception: an `asyncRewake` hook that exits with code 2 wakes Claude immediately even when the session is idle.
* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
##
--- a/hooks.md
+++ b/hooks.md
@@ -163,7 +163,7 @@
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
-For details on settings file resolution, see [settings](</docs/en/settings>). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](</docs/en/settings#hook-configuration>).
+For details on settings file resolution, see [settings](</docs/en/settings>). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt, so administrators can distribute vetted hooks through an organization marketplace. See [Hook configuration](</docs/en/settings#hook-configuration>).
###
--- a/hooks.md
+++ b/hooks.md
@@ -8,7 +8,7 @@
Hook lifecycle
-Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:
+Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences: once per session (`SessionStart`, `SessionEnd`), once per turn (`UserPromptSubmit`, `Stop`, `StopFailure`), and on every tool call inside the agentic loop (`PreToolUse`, `PostToolUse`):
The table below summarizes when each event fires. The Hook events section documents the full input schema and decision control options for each one.
@@ -171,7 +171,15 @@
Matcher patterns
-The `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:
+The `matcher` field filters when hooks fire. How a matcher is evaluated depends on the characters it contains:
+
+Matcher value| Evaluated as| Example
+---|---|---
+`"*"`, `""`, or omitted| Match all| fires on every occurrence of the event
+Only letters, digits, `_`, and `|`| Exact string, or `|`-separated list of exact strings| `Bash` matches only the Bash tool; `Edit|Write` matches either tool exactly
+Contains any other character| JavaScript regular expression| `^Notebook` matches any tool starting with Notebook; `mcp__memory__.*` matches every tool from the `memory` server
+
+The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
Event| What the matcher filters| Example matcher values
---|---|---
@@ -184,14 +192,14 @@
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`CwdChanged`| no matcher support| always fires on every directory change
-`FileChanged`| filename (basename of the changed file)| `.envrc`, `.env`, any filename you want to watch
+`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env`
`StopFailure`| error type| `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
-The 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 that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file:
+The matcher runs against a field from the JSON input that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file:
{
"hooks": {
@@ -223,10 +231,10 @@
* `mcp__filesystem__read_file`: Filesystem server’s read file tool
* `mcp__github__search_repositories`: GitHub server’s search tool
-Use regex patterns to target specific MCP tools or groups of tools:
+To match every tool from a server, append `.*` to the server prefix. The `.*` is required: a matcher like `mcp__memory` contains only letters and underscores, so it is compared as an exact string and matches no tool.
* `mcp__memory__.*` matches all tools from the `memory` server
- * `mcp__.*__write.*` matches any tool containing “write” from any server
+ * `mcp__.*__write.*` matches any tool whose name starts with `write` from any server
This example logs all memory server operations and validates write operations from any MCP server:
@@ -505,7 +513,7 @@
Exit code output
-The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a one-line `<hook name> hook error` notice and execution continues. The full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
+The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr, so you can identify the cause without `--debug`. Execution continues and the full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
#!/bin/bash
# Reads JSON input from stdin, checks the command
@@ -1800,7 +1808,12 @@
FileChanged
-Runs when a watched file changes on disk. The `matcher` field in your hook configuration controls which filenames to watch: it is a pipe-separated list of basenames (filenames without directory paths, for example `".envrc|.env"`). The same `matcher` value is also used to filter which hooks run when a file changes, matching against the basename of the changed file. Useful for reloading environment variables when project configuration files are modified. FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` hooks are supported.
+Runs when a watched file changes on disk. Useful for reloading environment variables when project configuration files are modified. The `matcher` for this event serves two roles:
+
+ * **Build the watch list** : the value is split on `|` and each segment is registered as a literal filename in the working directory, so `".envrc|.env"` watches exactly those two files. Regex patterns are not useful here: a value like `^\.env` would watch a file literally named `^\.env`.
+ * **Filter which hooks run** : when a watched file changes, the same value filters which hook groups run using the standard matcher rules against the changed file’s basename.
+
+FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` hooks are supported.
####
--- a/hooks.md
+++ b/hooks.md
@@ -505,7 +505,7 @@
Exit code output
-The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. 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. **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 for the full list. **Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues. For example, a hook command script that blocks dangerous Bash commands:
+The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on. **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 for the full list. **Any other exit code** is a non-blocking error for most hook events. The transcript shows a one-line `<hook name> hook error` notice and execution continues. The full stderr is written to the debug log. For example, a hook command script that blocks dangerous Bash commands:
#!/bin/bash
# Reads JSON input from stdin, checks the command
@@ -517,6 +517,8 @@
fi
exit 0 # Success: tool call proceeds
+
+For most hook events, only exit code 2 blocks the action. Claude Code treats exit code 1 as a non-blocking error and proceeds with the action, even though 1 is the conventional Unix failure code. If your hook is meant to enforce a policy, use `exit 2`. The exception is `WorktreeCreate`, where any non-zero exit code aborts worktree creation.
####
@@ -591,7 +593,7 @@
---|---|---
`continue`| `true`| If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields
`stopReason`| none| Message shown to the user when `continue` is `false`. Not shown to Claude
-`suppressOutput`| `false`| If `true`, hides stdout from verbose mode output
+`suppressOutput`| `false`| If `true`, omits stdout from the debug log
`systemMessage`| none| Warning message shown to the user
To stop Claude entirely regardless of event type:
@@ -843,13 +845,15 @@
`decision`| `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed
`reason`| Shown to the user when `decision` is `"block"`. Not added to context
`additionalContext`| String added to Claude’s context
+`sessionTitle`| Sets the session title, same effect as `/rename`. Use to name sessions automatically based on the prompt content
{
"decision": "block",
"reason": "Explanation for decision",
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
- "additionalContext": "My additional context here"
+ "additionalContext": "My additional context here",
+ "sessionTitle": "My session title"
}
}
@@ -2499,7 +2503,7 @@
Debug hooks
-Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output.
+Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag does not print to the terminal.
[DEBUG] Executing hooks for PostToolUse:Write
[DEBUG] Found 1 hook commands to execute
Show diff (208 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -18,6 +18,7 @@
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
`PreToolUse`| Before a tool call executes. Can block it
`PermissionRequest`| When a permission dialog appears
+`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
`PostToolUse`| After a tool call succeeds
`PostToolUseFailure`| After a tool call fails
`Notification`| When Claude Code sends a notification
@@ -174,7 +175,7 @@
Event| What the matcher filters| Example matcher values
---|---|---
-`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
+`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`
@@ -216,7 +217,7 @@
Match MCP tools
-[MCP](</docs/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. MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
+[MCP](</docs/en/mcp>) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`), so you can match them the same way you match any other tool name. MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
* `mcp__memory__create_entities`: Memory server’s create entities tool
* `mcp__filesystem__read_file`: Filesystem server’s read file tool
@@ -278,7 +279,7 @@
Field| Required| Description
---|---|---
`type`| yes| `"command"`, `"http"`, `"prompt"`, or `"agent"`
-`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
+`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
`timeout`| no| Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs only once per session then is removed. Skills only, not agents. See Hooks in skills and agents
@@ -539,6 +540,7 @@
`StopFailure`| No| Output and exit code are ignored
`PostToolUse`| No| Shows stderr to Claude (tool already ran)
`PostToolUseFailure`| No| Shows stderr to Claude (tool already failed)
+`PermissionDenied`| No| Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry
`Notification`| No| Shows stderr to user only
`SubagentStart`| No| Shows stderr to user only
`SessionStart`| No| Shows stderr to user only
@@ -579,7 +581,7 @@
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.
-Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. The JSON object supports three kinds of fields:
+Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. Hook output injected into context (`additionalContext`, `systemMessage`, or plain stdout) is capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way large tool results are handled. The JSON object supports three kinds of fields:
* **Universal fields** like `continue` work across all events. These are listed in the table below.
* **Top-level`decision` and `reason`** are used by some events to block or provide feedback.
@@ -608,8 +610,9 @@
---|---|---
UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange| Top-level `decision`| `decision: "block"`, `reason`
TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
-PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask), `permissionDecisionReason`
+PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason`
PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
+PermissionDenied| `hookSpecificOutput`| `retry: true` tells the model it may retry the denied tool call
WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation
Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept)
ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
@@ -858,7 +861,7 @@
PreToolUse
-Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names. Use PreToolUse decision control to allow, deny, or ask for permission to use the tool.
+Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names. Use PreToolUse decision control to allow, deny, ask, or defer the tool call.
####
@@ -976,16 +979,16 @@
PreToolUse decision control
-`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.
+`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: four outcomes (allow, deny, ask, or defer) plus the ability to modify tool input before execution.
Field| Description
---|---
-`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. [Deny and ask rules](</docs/en/permissions#manage-permissions>) still apply when a hook returns `"allow"`
-`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude
-`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user
-`additionalContext`| String added to Claude’s context before the tool executes
-
-When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
+`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) still apply when a hook returns `"allow"`
+`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored
+`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
+`additionalContext`| String added to Claude’s context before the tool executes. For `"defer"`, ignored
+
+When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`. When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
{
"hookSpecificOutput": {
@@ -1002,6 +1005,42 @@
`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer.
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.
+
+####
+
+
+
+Defer a tool call for later
+
+`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](</docs/en/headless>) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result.
+
+The `defer` value requires Claude Code v2.1.89 or later. Earlier versions do not recognize it and the tool proceeds through the normal permission flow.
+
+The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:
+
+ 1. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires.
+ 2. The hook returns `permissionDecision: "defer"`. The tool does not execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
+ 3. The calling process reads `deferred_tool_use` from the SDK result, surfaces the question in its own UI, and waits for an answer.
+ 4. The calling process runs `claude -p --resume <session-id>`. The same tool call fires `PreToolUse` again.
+ 5. The hook returns `permissionDecision: "allow"` with the answer in `updatedInput`. The tool executes and Claude continues.
+
+The `deferred_tool_use` field carries the tool’s `id`, `name`, and `input`. The `input` is the parameters Claude generated for the tool call, captured before execution:
+
+ {
+ "type": "result",
+ "subtype": "success",
+ "stop_reason": "tool_deferred",
+ "session_id": "abc123",
+ "deferred_tool_use": {
+ "id": "toolu_01abc",
+ "name": "AskUserQuestion",
+ "input": { "questions": [{ "question": "Which framework?", "header": "Framework", "options": [{"label": "React"}, {"label": "Vue"}], "multiSelect": false }] }
+ }
+ }
+
+There is no timeout or retry limit. The session remains on disk until you resume it. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
+
+`--resume` does not restore the permission mode from the prior session. Pass the same `--permission-mode` flag on resume that was active when the tool was deferred. Claude Code logs a warning if the modes differ.
###
@@ -1209,6 +1248,58 @@
"additionalContext": "Additional information about the failure for Claude"
}
}
+
+###
+
+
+
+PermissionDenied
+
+Runs when the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier denies a tool call. This hook only fires in auto mode: it does not run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call. Matches on tool name, same values as PreToolUse.
+
+####
+
+
+
+PermissionDenied input
+
+In addition to the common input fields, PermissionDenied hooks receive `tool_name`, `tool_input`, `tool_use_id`, and `reason`.
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "auto",
+ "hook_event_name": "PermissionDenied",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "rm -rf /tmp/build",
+ "description": "Clean build directory"
+ },
+ "tool_use_id": "toolu_01ABC123...",
+ "reason": "Auto mode denied: command targets a path outside the project"
+ }
+
+Field| Description
+---|---
+`reason`| The classifier’s explanation for why the tool call was denied
+
+####
+
+
+
+PermissionDenied decision control
+
+PermissionDenied hooks can tell the model it may retry the denied tool call. Return a JSON object with `hookSpecificOutput.retry` set to `true`:
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PermissionDenied",
+ "retry": true
+ }
+ }
+
+When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook does not return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.
###
@@ -2088,6 +2179,7 @@
* `FileChanged`
* `InstructionsLoaded`
* `Notification`
+ * `PermissionDenied`
* `PostCompact`
* `PreCompact`
* `SessionEnd`
--- a/hooks.md
+++ b/hooks.md
@@ -533,7 +533,7 @@
`Stop`| Yes| Prevents Claude from stopping, continues the conversation
`SubagentStop`| Yes| Prevents the subagent from stopping
`TeammateIdle`| Yes| Prevents the teammate from going idle (teammate continues working)
-`TaskCreated`| Yes| Prevents the task from being created
+`TaskCreated`| Yes| Rolls back the task creation
`TaskCompleted`| Yes| Prevents the task from being marked as completed
`ConfigChange`| Yes| Blocks the configuration change from taking effect (except `policy_settings`)
`StopFailure`| No| Output and exit code are ignored
@@ -2407,14 +2407,11 @@
Debug hooks
-Run `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.
+Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output.
[DEBUG] Executing hooks for PostToolUse:Write
- [DEBUG] Getting matching hook commands for PostToolUse with query: Write
- [DEBUG] Found 1 hook matchers in settings
- [DEBUG] Matched 1 hooks for query "Write"
[DEBUG] Found 1 hook commands to execute
[DEBUG] Executing hook command: <Your command> with timeout 600000ms
[DEBUG] Hook command completed with status 0: <Your stdout>
-For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide.
+For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide.
Show diff (134 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -46,7 +46,7 @@
How a hook resolves
-To 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:
+To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The `matcher` narrows to Bash tool calls and the `if` condition narrows further to commands starting with `rm`, so `block-rm.sh` only spawns when both filters match:
{
"hooks": {
@@ -56,7 +56,8 @@
"hooks": [
{
"type": "command",
- "command": ".claude/hooks/block-rm.sh"
+ "if": "Bash(rm *)",
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm.sh"
}
]
}
@@ -96,13 +97,19 @@
Matcher checks
-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.
+The matcher `"Bash"` matches the tool name, so this hook group activates. If you omit the matcher or use `"*"`, the group activates on every occurrence of the event.
3
+If condition checks
+
+The `if` condition `"Bash(rm *)"` matches because the command starts with `rm`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs.
+
+4
+
Hook handler runs
-The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:
+The script inspects the full command and finds `rm -rf`, so it prints a decision to stdout:
{
"hookSpecificOutput": {
@@ -112,9 +119,9 @@
}
}
-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.
-
-4
+If the command had been a safer `rm` variant like `rm file.txt`, the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.
+
+5
Claude Code acts on the result
@@ -201,7 +208,7 @@
}
}
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs only for `git` commands and `"Edit(*.ts)"` runs only for TypeScript files.
####
@@ -271,6 +278,7 @@
Field| Required| Description
---|---|---
`type`| yes| `"command"`, `"http"`, `"prompt"`, or `"agent"`
+`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>)
`timeout`| no| Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent
`statusMessage`| no| Custom spinner message displayed while the hook runs
`once`| no| If `true`, runs only once per session then is removed. Skills only, not agents. See Hooks in skills and agents
@@ -850,7 +858,7 @@
PreToolUse
-Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, and any MCP tool names. Use PreToolUse decision control to allow, deny, or ask for permission to use the tool.
+Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names. Use PreToolUse decision control to allow, deny, or ask for permission to use the tool.
####
@@ -953,6 +961,15 @@
`subagent_type`| string| `"Explore"`| Type of specialized agent to use
`model`| string| `"sonnet"`| Optional model alias to override the default
+##### AskUserQuestion
+
+Asks the user one to four multiple-choice questions.
+
+Field| Type| Example| Description
+---|---|---|---
+`questions`| array| `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]`| Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag
+`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude does not set this field; supply it via `updatedInput` to answer programmatically
+
####
@@ -965,7 +982,7 @@
---|---
`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. [Deny and ask rules](</docs/en/permissions#manage-permissions>) still apply when a hook returns `"allow"`
`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude
-`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
+`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user
`additionalContext`| String added to Claude’s context before the tool executes
When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
@@ -981,6 +998,8 @@
"additionalContext": "Current environment: production. Proceed with caution."
}
}
+
+`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer.
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.
@@ -1032,7 +1051,7 @@
Field| Description
---|---
`behavior`| `"allow"` grants the permission, `"deny"` denies it
-`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution
+`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones
`updatedPermissions`| For `"allow"` only: array of permission update entries to apply, such as adding an allow rule or changing the session permission mode
`message`| For `"deny"` only: tells Claude why the permission was denied
`interrupt`| For `"deny"` only: if `true`, stops Claude
@@ -1730,7 +1749,7 @@
WorktreeCreate
-When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/common-workflows#copy-gitignored-files-to-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
{
"hooks": {
Show diff (1218 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -23,10 +23,11 @@
`Notification`| When Claude Code sends a notification
`SubagentStart`| When a subagent is spawned
`SubagentStop`| When a subagent finishes
+`TaskCreated`| When a task is being created via `TaskCreate`
+`TaskCompleted`| When a task is being marked as completed
`Stop`| When Claude finishes responding
`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored
`TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle
-`TaskCompleted`| When a task is being marked as completed
`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
`ConfigChange`| When a configuration file changes during a session
`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
@@ -46,12 +47,6 @@
How a hook resolves
To 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:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -71,12 +66,6 @@
The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:
-Report incorrect code
-
-Copy
-
-Ask AI
-
#!/bin/bash
# .claude/hooks/block-rm.sh
COMMAND=$(jq -r '.tool_input.command')
@@ -101,12 +90,6 @@
The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{ "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
2
@@ -120,12 +103,6 @@
Hook handler runs
The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hookSpecificOutput": {
@@ -204,15 +181,9 @@
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
The 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 that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -230,7 +201,7 @@
}
}
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
####
@@ -250,12 +221,6 @@
* `mcp__.*__write.*` matches any tool containing “write” from any server
This example logs all memory server operations and validates write operations from any MCP server:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -340,12 +305,6 @@
Claude Code sends the hook’s JSON input as the POST request body with `Content-Type: application/json`. The response body uses the same JSON output format as command hooks. Error handling differs from command hooks: non-2xx responses, connection failures, and timeouts all produce non-blocking errors that allow execution to continue. To block a tool call or deny a permission, return a 2xx response with a JSON body containing `decision: "block"` or a `hookSpecificOutput` with `permissionDecision: "deny"`. This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PreToolUse": [
@@ -400,12 +359,6 @@
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:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PostToolUse": [
@@ -423,12 +376,6 @@
}
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.This example runs a formatting script bundled with the plugin:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"description": "Automatic code formatting",
@@ -458,12 +405,6 @@
In addition to settings files and plugins, hooks can be defined directly in [skills](</docs/en/skills>) and [subagents](</docs/en/sub-agents>) using frontmatter. These hooks are scoped to the component’s lifecycle and only run when that component is active. All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes. Hooks use the same configuration format as settings-based hooks but are scoped to the component’s lifetime and cleaned up when it finishes. This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
-Report incorrect code
-
-Copy
-
-Ask AI
-
---
name: secure-operations
description: Perform operations with security checks
@@ -535,12 +476,6 @@
For example, a `PreToolUse` hook for a Bash command receives this on stdin:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
@@ -562,12 +497,6 @@
Exit code output
The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. 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. **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 for the full list. **Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues. For example, a hook command script that blocks dangerous Bash commands:
-
-Report incorrect code
-
-Copy
-
-Ask AI
#!/bin/bash
# Reads JSON input from stdin, checks the command
@@ -596,6 +525,7 @@
`Stop`| Yes| Prevents Claude from stopping, continues the conversation
`SubagentStop`| Yes| Prevents the subagent from stopping
`TeammateIdle`| Yes| Prevents the teammate from going idle (teammate continues working)
+`TaskCreated`| Yes| Prevents the task from being created
`TaskCompleted`| Yes| Prevents the task from being marked as completed
`ConfigChange`| Yes| Blocks the configuration change from taking effect (except `policy_settings`)
`StopFailure`| No| Output and exit code are ignored
@@ -656,12 +586,6 @@
To stop Claude entirely regardless of event type:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }
####
@@ -675,7 +599,7 @@
Events| Decision pattern| Key fields
---|---|---
UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange| Top-level `decision`| `decision: "block"`, `reason`
-TeammateIdle, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
+TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask), `permissionDecisionReason`
PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation
@@ -693,24 +617,12 @@
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:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"decision": "block",
"reason": "Test suite must pass before proceeding"
}
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 for the full set of options.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hookSpecificOutput": {
@@ -721,12 +633,6 @@
}
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 for the full set of options.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hookSpecificOutput": {
@@ -773,12 +679,6 @@
In addition to the 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.
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -800,12 +700,6 @@
---|---
`additionalContext`| String added to Claude’s context. Multiple hooks’ values are concatenated
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "SessionStart",
@@ -820,12 +714,6 @@
Persist environment variables
SessionStart 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. To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:
-
-Report incorrect code
-
-Copy
-
-Ask AI
#!/bin/bash
@@ -838,12 +726,6 @@
exit 0
To capture all environment changes from setup commands, compare the exported variables before and after:
-
-Report incorrect code
-
-Copy
-
-Ask AI
#!/bin/bash
@@ -889,12 +771,6 @@
`trigger_file_path`| Path to the file whose access triggered this load, for lazy loads
`parent_file_path`| Path to the parent instruction file that included this one, for `include` loads
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
@@ -929,12 +805,6 @@
In addition to the common input fields, UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -962,12 +832,6 @@
`decision`| `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed
`reason`| Shown to the user when `decision` is `"block"`. Not added to context
`additionalContext`| String added to Claude’s context
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"decision": "block",
@@ -1106,12 +970,6 @@
When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
@@ -1141,12 +999,6 @@
PermissionRequest input
PermissionRequest 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.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -1185,12 +1037,6 @@
`message`| For `"deny"` only: tells Claude why the permission was denied
`interrupt`| For `"deny"` only: if `true`, stops Claude
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "PermissionRequest",
@@ -1246,12 +1092,6 @@
PostToolUse input
`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.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -1286,12 +1126,6 @@
`additionalContext`| Additional context for Claude to consider
`updatedMCPToolOutput`| For MCP tools only: replaces the tool’s output with the provided value
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"decision": "block",
"reason": "Explanation for decision",
@@ -1316,12 +1150,6 @@
PostToolUseFailure input
PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -1356,12 +1184,6 @@
---|---
`additionalContext`| Additional context for Claude to consider alongside the error
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "PostToolUseFailure",
@@ -1376,12 +1198,6 @@
Notification
Runs 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. Use 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:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -1416,12 +1232,6 @@
In addition to the common input fields, Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired.
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -1454,12 +1264,6 @@
In addition to the 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).
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -1475,12 +1279,6 @@
---|---
`additionalContext`| String added to the subagent’s context
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "SubagentStart",
@@ -1503,12 +1301,6 @@
SubagentStop input
In addition to the 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.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -1529,158 +1321,58 @@
-Stop
-
-Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt. API errors fire StopFailure instead.
-
-####
-
-
-
-Stop input
-
-In addition to the 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.
-
-Report incorrect code
-
-Copy
-
-Ask AI
-
- {
- "session_id": "abc123",
- "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "permission_mode": "default",
- "hook_event_name": "Stop",
- "stop_hook_active": true,
- "last_assistant_message": "I've completed the refactoring. Here's a summary..."
- }
-
-####
-
-
-
-Stop decision control
-
-`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
-
-Field| Description
----|---
-`decision`| `"block"` prevents Claude from stopping. Omit to allow Claude to stop
-`reason`| Required when `decision` is `"block"`. Tells Claude why it should continue
-
-Report incorrect code
-
-Copy
-
-Ask AI
-
- {
- "decision": "block",
- "reason": "Must be provided when Claude is blocked from stopping"
- }
-
-###
-
-
-
-StopFailure
-
-Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.
-
-####
-
-
-
-StopFailure input
-
-In addition to the common input fields, StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering.
-
-Field| Description
----|---
-`error`| Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown`
-`error_details`| Additional details about the error, when available
-`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"`
-
-Report incorrect code
-
-Copy
-
-Ask AI
-
- {
- "session_id": "abc123",
- "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
- "cwd": "/Users/...",
- "hook_event_name": "StopFailure",
- "error": "rate_limit",
- "error_details": "429 Too Many Requests",
- "last_assistant_message": "API Error: Rate limit reached"
- }
-
-StopFailure hooks have no decision control. They run for notification and logging purposes only.
-
-###
-
-
-
-TeammateIdle
-
-Runs when an [agent team](</docs/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. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
-
-####
-
-
-
-TeammateIdle input
-
-In addition to the common input fields, TeammateIdle hooks receive `teammate_name` and `team_name`.
-
-Report incorrect code
-
-Copy
-
-Ask AI
+TaskCreated
+
+Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks do not support matchers and fire on every occurrence.
+
+####
+
+
+
+TaskCreated input
+
+In addition to the common input fields, TaskCreated hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"permission_mode": "default",
- "hook_event_name": "TeammateIdle",
- "teammate_name": "researcher",
+ "hook_event_name": "TaskCreated",
+ "task_id": "task-001",
+ "task_subject": "Implement user authentication",
+ "task_description": "Add login and signup endpoints",
+ "teammate_name": "implementer",
"team_name": "my-project"
}
Field| Description
---|---
-`teammate_name`| Name of the teammate that is about to go idle
-`team_name`| Name of the team
-
-####
-
-
-
-TeammateIdle decision control
-
-TeammateIdle hooks support two ways to control teammate behavior:
-
- * **Exit code 2** : the teammate receives the stderr message as feedback and continues working instead of going idle.
+`task_id`| Identifier of the task being created
+`task_subject`| Title of the task
+`task_description`| Detailed description of the task. May be absent
+`teammate_name`| Name of the teammate creating the task. May be absent
+`team_name`| Name of the team. May be absent
+
+####
+
+
+
+TaskCreated decision control
+
+TaskCreated hooks support two ways to control task creation:
+
+ * **Exit code 2** : the task is not created and the stderr message is fed back to the model as feedback.
* **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
-This example checks that a build artifact exists before allowing a teammate to go idle:
-
-Report incorrect code
-
-Copy
-
-Ask AI
+This example blocks tasks whose subjects don’t follow the required format:
#!/bin/bash
-
- if [ ! -f "./dist/output.js" ]; then
- echo "Build artifact missing. Run the build before stopping." >&2
+ INPUT=$(cat)
+ TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
+
+ if [[ ! "$TASK_SUBJECT" =~ ^\[TICKET-[0-9]+\] ]]; then
+ echo "Task subject must start with a ticket number, e.g. '[TICKET-123] Add feature'" >&2
exit 2
fi
@@ -1701,12 +1393,6 @@
TaskCompleted input
In addition to the common input fields, TaskCompleted hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -1742,12 +1428,6 @@
This example runs tests and blocks task completion if they fail:
-Report incorrect code
-
-Copy
-
-Ask AI
-
#!/bin/bash
INPUT=$(cat)
TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
@@ -1764,6 +1444,137 @@
+Stop
+
+Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt. API errors fire StopFailure instead.
+
+####
+
+
+
+Stop input
+
+In addition to the 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.
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "Stop",
+ "stop_hook_active": true,
+ "last_assistant_message": "I've completed the refactoring. Here's a summary..."
+ }
+
+####
+
+
+
+Stop decision control
+
+`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
+
+Field| Description
+---|---
+`decision`| `"block"` prevents Claude from stopping. Omit to allow Claude to stop
+`reason`| Required when `decision` is `"block"`. Tells Claude why it should continue
+
+ {
+ "decision": "block",
+ "reason": "Must be provided when Claude is blocked from stopping"
+ }
+
+###
+
+
+
+StopFailure
+
+Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.
+
+####
+
+
+
+StopFailure input
+
+In addition to the common input fields, StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering.
+
+Field| Description
+---|---
+`error`| Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown`
+`error_details`| Additional details about the error, when available
+`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"`
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "StopFailure",
+ "error": "rate_limit",
+ "error_details": "429 Too Many Requests",
+ "last_assistant_message": "API Error: Rate limit reached"
+ }
+
+StopFailure hooks have no decision control. They run for notification and logging purposes only.
+
+###
+
+
+
+TeammateIdle
+
+Runs when an [agent team](</docs/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. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
+
+####
+
+
+
+TeammateIdle input
+
+In addition to the common input fields, TeammateIdle hooks receive `teammate_name` and `team_name`.
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "TeammateIdle",
+ "teammate_name": "researcher",
+ "team_name": "my-project"
+ }
+
+Field| Description
+---|---
+`teammate_name`| Name of the teammate that is about to go idle
+`team_name`| Name of the team
+
+####
+
+
+
+TeammateIdle decision control
+
+TeammateIdle hooks support two ways to control teammate behavior:
+
+ * **Exit code 2** : the teammate receives the stderr message as feedback and continues working instead of going idle.
+ * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
+
+This example checks that a build artifact exists before allowing a teammate to go idle:
+
+ #!/bin/bash
+
+ if [ ! -f "./dist/output.js" ]; then
+ echo "Build artifact missing. Run the build before stopping." >&2
+ exit 2
+ fi
+
+ exit 0
+
+###
+
+
+
ConfigChange
Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files. ConfigChange 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. The matcher filters on the configuration source:
@@ -1777,12 +1588,6 @@
`skills`| A skill file in `.claude/skills/` changes
This example logs all configuration changes for security auditing:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -1807,12 +1612,6 @@
In addition to the 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.
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -1835,12 +1634,6 @@
`decision`| `"block"` prevents the configuration change from being applied. Omit to allow the change
`reason`| Explanation shown to the user when `decision` is `"block"`
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"decision": "block",
"reason": "Configuration changes to project settings require admin approval"
@@ -1863,12 +1656,6 @@
CwdChanged input
In addition to the common input fields, CwdChanged hooks receive `old_cwd` and `new_cwd`.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -1914,12 +1701,6 @@
`file_path`| Absolute path to the file that changed
`event`| What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted)
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
@@ -1950,12 +1731,6 @@
WorktreeCreate
When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -1982,12 +1757,6 @@
In addition to the 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`).
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -2016,12 +1785,6 @@
WorktreeRemove
The cleanup counterpart to 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. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -2046,12 +1809,6 @@
In addition to the common input fields, WorktreeRemove hooks receive the `worktree_path` field, which is the absolute path to the worktree being removed.
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -2082,12 +1839,6 @@
PreCompact input
In addition to the 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.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -2118,12 +1869,6 @@
PostCompact input
In addition to the common input fields, PostCompact hooks receive `trigger` and `compact_summary`. The `compact_summary` field contains the conversation summary generated by the compact operation.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -2161,12 +1906,6 @@
In addition to the common input fields, SessionEnd hooks receive a `reason` field indicating why the session ended. See the reason table above for all values.
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -2177,12 +1916,6 @@
SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.
-Report incorrect code
-
-Copy
-
-Ask AI
-
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
###
@@ -2200,12 +1933,6 @@
Elicitation input
In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation (the most common case):
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -2226,12 +1953,6 @@
For URL-mode elicitation (browser-based authentication):
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
@@ -2252,12 +1973,6 @@
To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "Elicitation",
@@ -2290,12 +2005,6 @@
ElicitationResult input
In addition to the common input fields, ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"session_id": "abc123",
@@ -2318,12 +2027,6 @@
To override the user’s response, return a JSON object with `hookSpecificOutput`:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "ElicitationResult",
@@ -2354,6 +2057,7 @@
* `Stop`
* `SubagentStop`
* `TaskCompleted`
+ * `TaskCreated`
* `UserPromptSubmit`
Events that support `command` and `http` hooks but not `prompt` or `agent`:
@@ -2396,12 +2100,6 @@
Set `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. This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"Stop": [
@@ -2432,12 +2130,6 @@
The LLM must respond with JSON containing:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"ok": true | false,
"reason": "Explanation for the decision"
@@ -2455,12 +2147,6 @@
Example: Multi-criteria Stop hook
This `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](</docs/en/sub-agents>) should stop:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -2518,12 +2204,6 @@
The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block. This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"Stop": [
@@ -2555,12 +2235,6 @@
Configure an async hook
Add `"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. This 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:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -2598,12 +2272,6 @@
This 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`:
-Report incorrect code
-
-Copy
-
-Ask AI
-
#!/bin/bash
# run-tests-async.sh
@@ -2627,12 +2295,6 @@
fi
Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -2703,12 +2365,6 @@
On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (5.1).
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PostToolUse": [
@@ -2734,12 +2390,6 @@
Run `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.
-Report incorrect code
-
-Copy
-
-Ask AI
-
[DEBUG] Executing hooks for PostToolUse:Write
[DEBUG] Getting matching hook commands for PostToolUse with query: Write
[DEBUG] Found 1 hook matchers in settings
Show diff (272 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -29,6 +29,8 @@
`TaskCompleted`| When a task is being marked as completed
`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
`ConfigChange`| When a configuration file changes during a session
+`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
+`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
`WorktreeCreate`| When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior
`WorktreeRemove`| When a worktree is being removed, either at session exit or when a subagent finishes
`PreCompact`| Before context compaction
@@ -196,6 +198,8 @@
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
+`CwdChanged`| no matcher support| always fires on every directory change
+`FileChanged`| filename (basename of the changed file)| `.envrc`, `.env`, any filename you want to watch
`StopFailure`| error type| `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
@@ -226,7 +230,7 @@
}
}
-`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.
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
####
@@ -318,6 +322,7 @@
---|---|---
`command`| yes| Shell command to execute
`async`| no| If `true`, runs in the background without blocking. See Run hooks in the background
+`shell`| no| Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly
####
@@ -600,6 +605,8 @@
`SubagentStart`| No| Shows stderr to user only
`SessionStart`| No| Shows stderr to user only
`SessionEnd`| No| Shows stderr to user only
+`CwdChanged`| No| Shows stderr to user only
+`FileChanged`| No| Shows stderr to user only
`PreCompact`| No| Shows stderr to user only
`PostCompact`| No| Shows stderr to user only
`Elicitation`| Yes| Denies the elicitation
@@ -671,10 +678,10 @@
TeammateIdle, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask), `permissionDecisionReason`
PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
-WorktreeCreate| stdout path| Hook prints absolute path to created worktree. Non-zero exit fails creation
+WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation
Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept)
ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
-WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure| None| No decision control. Used for side effects like logging or cleanup
+WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged| None| No decision control. Used for side effects like logging or cleanup
Here are examples of each pattern in action:
@@ -855,7 +862,7 @@
Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
-`CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.
+`CLAUDE_ENV_FILE` is available for SessionStart, CwdChanged, and FileChanged hooks. Other hook types do not have access to this variable.
###
@@ -1845,9 +1852,104 @@
+CwdChanged
+
+Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` hooks are supported. CwdChanged does not support matchers and fires on every directory change.
+
+####
+
+
+
+CwdChanged input
+
+In addition to the common input fields, CwdChanged hooks receive `old_cwd` and `new_cwd`.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
+ "cwd": "/Users/my-project/src",
+ "hook_event_name": "CwdChanged",
+ "old_cwd": "/Users/my-project",
+ "new_cwd": "/Users/my-project/src"
+ }
+
+####
+
+
+
+CwdChanged output
+
+In addition to the JSON output fields available to all hooks, CwdChanged hooks can return `watchPaths` to dynamically set which file paths FileChanged watches:
+
+Field| Description
+---|---
+`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Returning an empty array clears the dynamic list, which is typical when entering a new directory
+
+CwdChanged hooks have no decision control. They cannot block the directory change.
+
+###
+
+
+
+FileChanged
+
+Runs when a watched file changes on disk. The `matcher` field in your hook configuration controls which filenames to watch: it is a pipe-separated list of basenames (filenames without directory paths, for example `".envrc|.env"`). The same `matcher` value is also used to filter which hooks run when a file changes, matching against the basename of the changed file. Useful for reloading environment variables when project configuration files are modified. FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` hooks are supported.
+
+####
+
+
+
+FileChanged input
+
+In addition to the common input fields, FileChanged hooks receive `file_path` and `event`.
+
+Field| Description
+---|---
+`file_path`| Absolute path to the file that changed
+`event`| What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted)
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
+ "cwd": "/Users/my-project",
+ "hook_event_name": "FileChanged",
+ "file_path": "/Users/my-project/.envrc",
+ "event": "change"
+ }
+
+####
+
+
+
+FileChanged output
+
+In addition to the JSON output fields available to all hooks, FileChanged hooks can return `watchPaths` to dynamically update which file paths are watched:
+
+Field| Description
+---|---
+`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Use this when your hook script discovers additional files to watch based on the changed file
+
+FileChanged hooks have no decision control. They cannot block the file change from occurring.
+
+###
+
+
+
WorktreeCreate
-When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. The 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. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
Report incorrect code
@@ -1900,7 +2002,12 @@
WorktreeCreate output
-The 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. WorktreeCreate 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.
+WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
+
+ * **Command hooks** (`type: "command"`): print the path on stdout.
+ * **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
+
+If the hook fails or produces no path, worktree creation fails with an error.
###
@@ -1908,7 +2015,7 @@
WorktreeRemove
-The cleanup counterpart to 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. Claude 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:
+The cleanup counterpart to 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. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
Report incorrect code
@@ -1953,7 +2060,7 @@
"worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
}
-WorktreeRemove 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.
+WorktreeRemove 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.
###
@@ -2249,22 +2356,25 @@
* `TaskCompleted`
* `UserPromptSubmit`
-Events that only support `type: "command"` hooks:
+Events that support `command` and `http` hooks but not `prompt` or `agent`:
* `ConfigChange`
+ * `CwdChanged`
* `Elicitation`
* `ElicitationResult`
+ * `FileChanged`
* `InstructionsLoaded`
* `Notification`
* `PostCompact`
* `PreCompact`
* `SessionEnd`
- * `SessionStart`
* `StopFailure`
* `SubagentStart`
* `TeammateIdle`
* `WorktreeCreate`
* `WorktreeRemove`
+
+`SessionStart` supports only `command` hooks.
###
@@ -2589,6 +2699,37 @@
+Windows PowerShell tool
+
+On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (5.1).
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Write",
+ "hooks": [
+ {
+ "type": "command",
+ "shell": "powershell",
+ "command": "Write-Host 'File written'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+##
+
+
+
Debug hooks
Run `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.
--- a/hooks.md
+++ b/hooks.md
@@ -518,7 +518,7 @@
`session_id`| Current session identifier
`transcript_path`| Path to conversation JSON
`cwd`| Current working directory when the hook is invoked
-`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
+`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
`hook_event_name`| Name of the event that fired
When running with `--agent` or inside a subagent, two additional fields are included:
Show diff (2613 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -0,0 +1,2610 @@
+For a quickstart guide with examples, see [Automate workflows with hooks](</docs/en/hooks-guide>).
+
+Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you’re setting up hooks for the first time, start with the [guide](</docs/en/hooks-guide>) instead.
+
+##
+
+
+
+Hook lifecycle
+
+Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:
+
+The table below summarizes when each event fires. The Hook events section documents the full input schema and decision control options for each one.
+
+Event| When it fires
+---|---
+`SessionStart`| When a session begins or resumes
+`UserPromptSubmit`| When you submit a prompt, before Claude processes it
+`PreToolUse`| Before a tool call executes. Can block it
+`PermissionRequest`| When a permission dialog appears
+`PostToolUse`| After a tool call succeeds
+`PostToolUseFailure`| After a tool call fails
+`Notification`| When Claude Code sends a notification
+`SubagentStart`| When a subagent is spawned
+`SubagentStop`| When a subagent finishes
+`Stop`| When Claude finishes responding
+`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored
+`TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle
+`TaskCompleted`| When a task is being marked as completed
+`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
+`ConfigChange`| When a configuration file changes during a session
+`WorktreeCreate`| When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior
+`WorktreeRemove`| When a worktree is being removed, either at session exit or when a subagent finishes
+`PreCompact`| Before context compaction
+`PostCompact`| After context compaction completes
+`Elicitation`| When an MCP server requests user input during a tool call
+`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server
+`SessionEnd`| When a session terminates
+
+###
+
+
+
+How a hook resolves
+
+To 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:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": ".claude/hooks/block-rm.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+ # .claude/hooks/block-rm.sh
+ COMMAND=$(jq -r '.tool_input.command')
+
+ if echo "$COMMAND" | grep -q 'rm -rf'; then
+ jq -n '{
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ permissionDecision: "deny",
+ permissionDecisionReason: "Destructive command blocked by hook"
+ }
+ }'
+ else
+ exit 0 # allow the command
+ fi
+
+Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here’s what happens:
+
+1
+
+Event fires
+
+The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }
+
+2
+
+Matcher checks
+
+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.
+
+3
+
+Hook handler runs
+
+The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Destructive command blocked by hook"
+ }
+ }
+
+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.
+
+4
+
+Claude Code acts on the result
+
+Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.
+
+The Configuration section below documents the full schema, and each hook event section documents what input your command receives and what output it can return.
+
+##
+
+
+
+Configuration
+
+Hooks are defined in JSON settings files. The configuration has three levels of nesting:
+
+ 1. Choose a hook event to respond to, like `PreToolUse` or `Stop`
+ 2. Add a matcher group to filter when it fires, like “only for the Bash tool”
+ 3. Define one or more hook handlers to run when matched
+
+See How a hook resolves above for a complete walkthrough with an annotated example.
+
+This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, prompt, or agent that runs. “Hook” on its own refers to the general feature.
+
+###
+
+
+
+Hook locations
+
+Where you define a hook determines its scope:
+
+Location| Scope| Shareable
+---|---|---
+`~/.claude/settings.json`| All your projects| No, local to your machine
+`.claude/settings.json`| Single project| Yes, can be committed to the repo
+`.claude/settings.local.json`| Single project| No, gitignored
+Managed policy settings| Organization-wide| Yes, admin-controlled
+[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
+[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file
+
+For details on settings file resolution, see [settings](</docs/en/settings>). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](</docs/en/settings#hook-configuration>).
+
+###
+
+
+
+Matcher patterns
+
+The `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:
+
+Event| What the matcher filters| Example matcher values
+---|---|---
+`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
+`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
+`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`
+`SubagentStart`| agent type| `Bash`, `Explore`, `Plan`, or custom agent names
+`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
+`SubagentStop`| agent type| same values as `SubagentStart`
+`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
+`StopFailure`| error type| `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
+`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
+`Elicitation`| MCP server name| your configured MCP server names
+`ElicitationResult`| MCP server name| same values as `Elicitation`
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
+
+The 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 that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "/path/to/lint-check.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+`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.
+
+####
+
+
+
+Match MCP tools
+
+[MCP](</docs/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. MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
+
+ * `mcp__memory__create_entities`: Memory server’s create entities tool
+ * `mcp__filesystem__read_file`: Filesystem server’s read file tool
+ * `mcp__github__search_repositories`: GitHub server’s search tool
+
+Use regex patterns to target specific MCP tools or groups of tools:
+
+ * `mcp__memory__.*` matches all tools from the `memory` server
+ * `mcp__.*__write.*` matches any tool containing “write” from any server
+
+This example logs all memory server operations and validates write operations from any MCP server:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "mcp__memory__.*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
+ }
+ ]
+ },
+ {
+ "matcher": "mcp__.*__write.*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "/home/user/scripts/validate-mcp-write.py"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+###
+
+
+
+Hook handler fields
+
+Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, LLM prompt, or agent that runs when the matcher matches. There are four types:
+
+ * **Command hooks** (`type: "command"`): run a shell command. Your script receives the event’s JSON input on stdin and communicates results back through exit codes and stdout.
+ * **HTTP hooks** (`type: "http"`): send the event’s JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same JSON output format as command hooks.
+ * **Prompt hooks** (`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.
+ * **Agent hooks** (`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.
+
+####
+
+
+
+Common fields
+
+These fields apply to all hook types:
+
+Field| Required| Description
+---|---|---
+`type`| yes| `"command"`, `"http"`, `"prompt"`, or `"agent"`
+`timeout`| no| Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent
+`statusMessage`| no| Custom spinner message displayed while the hook runs
+`once`| no| If `true`, runs only once per session then is removed. Skills only, not agents. See Hooks in skills and agents
+
+####
+
+
+
+Command hook fields
+
+In addition to the common fields, command hooks accept these fields:
+
+Field| Required| Description
+---|---|---
+`command`| yes| Shell command to execute
+`async`| no| If `true`, runs in the background without blocking. See Run hooks in the background
+
+####
+
+
+
+HTTP hook fields
+
+In addition to the common fields, HTTP hooks accept these fields:
+
+Field| Required| Description
+---|---|---
+`url`| yes| URL to send the POST request to
+`headers`| no| Additional HTTP headers as key-value pairs. Values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in `allowedEnvVars` are resolved
+`allowedEnvVars`| no| List of environment variable names that may be interpolated into header values. References to unlisted variables are replaced with empty strings. Required for any env var interpolation to work
+
+Claude Code sends the hook’s JSON input as the POST request body with `Content-Type: application/json`. The response body uses the same JSON output format as command hooks. Error handling differs from command hooks: non-2xx responses, connection failures, and timeouts all produce non-blocking errors that allow execution to continue. To block a tool call or deny a permission, return a 2xx response with a JSON body containing `decision: "block"` or a `hookSpecificOutput` with `permissionDecision: "deny"`. This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "http",
+ "url": "http://localhost:8080/hooks/pre-tool-use",
+ "timeout": 30,
+ "headers": {
+ "Authorization": "Bearer $MY_TOKEN"
+ },
+ "allowedEnvVars": ["MY_TOKEN"]
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+####
+
+
+
+Prompt and agent hook fields
+
+In addition to the common fields, prompt and agent hooks accept these fields:
+
+Field| Required| Description
+---|---|---
+`prompt`| yes| Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON
+`model`| no| Model to use for evaluation. Defaults to a fast model
+
+All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
+
+###
+
+
+
+Reference scripts by path
+
+Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:
+
+ * `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.
+ * `${CLAUDE_PLUGIN_ROOT}`: the plugin’s installation directory, for scripts bundled with a [plugin](</docs/en/plugins>). Changes on each plugin update.
+ * `${CLAUDE_PLUGIN_DATA}`: the plugin’s [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>), for dependencies and state that should survive plugin updates.
+
+ * Project scripts
+
+ * Plugin scripts
+
+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:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Write|Edit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+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.This example runs a formatting script bundled with the plugin:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "description": "Automatic code formatting",
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Write|Edit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
+ "timeout": 30
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+See the [plugin components reference](</docs/en/plugins-reference#hooks>) for details on creating plugin hooks.
+
+###
+
+
+
+Hooks in skills and agents
+
+In addition to settings files and plugins, hooks can be defined directly in [skills](</docs/en/skills>) and [subagents](</docs/en/sub-agents>) using frontmatter. These hooks are scoped to the component’s lifecycle and only run when that component is active. All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes. Hooks use the same configuration format as settings-based hooks but are scoped to the component’s lifetime and cleaned up when it finishes. This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ ---
+ name: secure-operations
+ description: Perform operations with security checks
+ hooks:
+ PreToolUse:
+ - matcher: "Bash"
+ hooks:
+ - type: command
+ command: "./scripts/security-check.sh"
+ ---
+
+Agents use the same format in their YAML frontmatter.
+
+###
+
+
+
+The `/hooks` menu
+
+Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook’s command, prompt, or URL. The menu displays all four hook types: `command`, `prompt`, `agent`, and `http`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:
+
+ * `User`: from `~/.claude/settings.json`
+ * `Project`: from `.claude/settings.json`
+ * `Local`: from `.claude/settings.local.json`
+ * `Plugin`: from a plugin’s `hooks/hooks.json`
+ * `Session`: registered in memory for the current session
+ * `Built-in`: registered internally by Claude Code
+
+Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.
+
+###
+
+
+
+Disable or remove hooks
+
+To remove a hook, delete its entry from the settings JSON file. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration. The `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. Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
+
+##
+
+
+
+Hook input and output
+
+Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options.
+
+###
+
+
+
+Common input fields
+
+Hook events receive these fields as JSON, in addition to event-specific fields documented in each hook event section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.
+
+Field| Description
+---|---
+`session_id`| Current session identifier
+`transcript_path`| Path to conversation JSON
+`cwd`| Current working directory when the hook is invoked
+`permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check
+`hook_event_name`| Name of the event that fired
+
+When running with `--agent` or inside a subagent, two additional fields are included:
+
+Field| Description
+---|---
+`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
+`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value.
+
+For example, a `PreToolUse` hook for a Bash command receives this on stdin:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
+ "cwd": "/home/user/my-project",
+ "permission_mode": "default",
+ "hook_event_name": "PreToolUse",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "npm test"
+ }
+ }
+
+The `tool_name` and `tool_input` fields are event-specific. Each hook event section documents the additional fields for that event.
+
+###
+
+
+
+Exit code output
+
+The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. 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. **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 for the full list. **Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues. For example, a hook command script that blocks dangerous Bash commands:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+ # Reads JSON input from stdin, checks the command
+ command=$(jq -r '.tool_input.command' < /dev/stdin)
+
+ if [[ "$command" == rm* ]]; then
+ echo "Blocked: rm commands are not allowed" >&2
+ exit 2 # Blocking error: tool call is prevented
+ fi
+
+ exit 0 # Success: tool call proceeds
+
+####
+
+
+
+Exit code 2 behavior per event
+
+Exit 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.
+
+Hook event| Can block?| What happens on exit 2
+---|---|---
+`PreToolUse`| Yes| Blocks the tool call
+`PermissionRequest`| Yes| Denies the permission
+`UserPromptSubmit`| Yes| Blocks prompt processing and erases the prompt
+`Stop`| Yes| Prevents Claude from stopping, continues the conversation
+`SubagentStop`| Yes| Prevents the subagent from stopping
+`TeammateIdle`| Yes| Prevents the teammate from going idle (teammate continues working)
+`TaskCompleted`| Yes| Prevents the task from being marked as completed
+`ConfigChange`| Yes| Blocks the configuration change from taking effect (except `policy_settings`)
+`StopFailure`| No| Output and exit code are ignored
+`PostToolUse`| No| Shows stderr to Claude (tool already ran)
+`PostToolUseFailure`| No| Shows stderr to Claude (tool already failed)
+`Notification`| No| Shows stderr to user only
+`SubagentStart`| No| Shows stderr to user only
+`SessionStart`| No| Shows stderr to user only
+`SessionEnd`| No| Shows stderr to user only
+`PreCompact`| No| Shows stderr to user only
+`PostCompact`| No| Shows stderr to user only
+`Elicitation`| Yes| Denies the elicitation
+`ElicitationResult`| Yes| Blocks the response (action becomes decline)
+`WorktreeCreate`| Yes| Any non-zero exit code causes worktree creation to fail
+`WorktreeRemove`| No| Failures are logged in debug mode only
+`InstructionsLoaded`| No| Exit code is ignored
+
+###
+
+
+
+HTTP response handling
+
+HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:
+
+ * **2xx with an empty body** : success, equivalent to exit code 0 with no output
+ * **2xx with a plain text body** : success, the text is added as context
+ * **2xx with a JSON body** : success, parsed using the same JSON output schema as command hooks
+ * **Non-2xx status** : non-blocking error, execution continues
+ * **Connection failure or timeout** : non-blocking error, execution continues
+
+Unlike command hooks, HTTP hooks cannot signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.
+
+###
+
+
+
+JSON output
+
+Exit 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 for blocking, allowing, or escalating to the user.
+
+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.
+
+Your 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](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. The JSON object supports three kinds of fields:
+
+ * **Universal fields** like `continue` work across all events. These are listed in the table below.
+ * **Top-level`decision` and `reason`** are used by some events to block or provide feedback.
+ * **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.
+
+Field| Default| Description
+---|---|---
+`continue`| `true`| If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields
+`stopReason`| none| Message shown to the user when `continue` is `false`. Not shown to Claude
+`suppressOutput`| `false`| If `true`, hides stdout from verbose mode output
+`systemMessage`| none| Warning message shown to the user
+
+To stop Claude entirely regardless of event type:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ { "continue": false, "stopReason": "Build failed, fix errors before continuing" }
+
+####
+
+
+
+Decision control
+
+Not 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:
+
+Events| Decision pattern| Key fields
+---|---|---
+UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange| Top-level `decision`| `decision: "block"`, `reason`
+TeammateIdle, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior
+PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask), `permissionDecisionReason`
+PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny)
+WorktreeCreate| stdout path| Hook prints absolute path to created worktree. Non-zero exit fails creation
+Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept)
+ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override)
+WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure| None| No decision control. Used for side effects like logging or cleanup
+
+Here are examples of each pattern in action:
+
+ * Top-level decision
+
+ * PreToolUse
+
+ * PermissionRequest
+
+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:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "decision": "block",
+ "reason": "Test suite must pass before proceeding"
+ }
+
+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 for the full set of options.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Database writes are not allowed"
+ }
+ }
+
+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 for the full set of options.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PermissionRequest",
+ "decision": {
+ "behavior": "allow",
+ "updatedInput": {
+ "command": "npm run lint"
+ }
+ }
+ }
+ }
+
+For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](</docs/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>).
+
+##
+
+
+
+Hook events
+
+Each 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.
+
+###
+
+
+
+SessionStart
+
+Runs 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](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported. The matcher value corresponds to how the session was initiated:
+
+Matcher| When it fires
+---|---
+`startup`| New session
+`resume`| `--resume`, `--continue`, or `/resume`
+`clear`| `/clear`
+`compact`| Auto or manual compaction
+
+####
+
+
+
+SessionStart input
+
+In addition to the 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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "SessionStart",
+ "source": "startup",
+ "model": "claude-sonnet-4-6"
+ }
+
+####
+
+
+
+SessionStart decision control
+
+Any text your hook script prints to stdout is added as context for Claude. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
+
+Field| Description
+---|---
+`additionalContext`| String added to Claude’s context. Multiple hooks’ values are concatenated
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "SessionStart",
+ "additionalContext": "My additional context here"
+ }
+ }
+
+####
+
+
+
+Persist environment variables
+
+SessionStart 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. To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+
+ if [ -n "$CLAUDE_ENV_FILE" ]; then
+ echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
+ echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"
+ echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
+ fi
+
+ exit 0
+
+To capture all environment changes from setup commands, compare the exported variables before and after:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+
+ ENV_BEFORE=$(export -p | sort)
+
+ # Run your setup commands that modify the environment
+ source ~/.nvm/nvm.sh
+ nvm use 20
+
+ if [ -n "$CLAUDE_ENV_FILE" ]; then
+ ENV_AFTER=$(export -p | sort)
+ comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE"
+ fi
+
+ exit 0
+
+Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
+
+`CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.
+
+###
+
+
+
+InstructionsLoaded
+
+Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes. The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
+
+####
+
+
+
+InstructionsLoaded input
+
+In addition to the common input fields, InstructionsLoaded hooks receive these fields:
+
+Field| Description
+---|---
+`file_path`| Absolute path to the instruction file that was loaded
+`memory_type`| Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"`
+`load_reason`| Why the file was loaded: `"session_start"`, `"nested_traversal"`, `"path_glob_match"`, `"include"`, or `"compact"`. The `"compact"` value fires when instruction files are re-loaded after a compaction event
+`globs`| Path glob patterns from the file’s `paths:` frontmatter, if any. Present only for `path_glob_match` loads
+`trigger_file_path`| Path to the file whose access triggered this load, for lazy loads
+`parent_file_path`| Path to the parent instruction file that included this one, for `include` loads
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
+ "cwd": "/Users/my-project",
+ "hook_event_name": "InstructionsLoaded",
+ "file_path": "/Users/my-project/CLAUDE.md",
+ "memory_type": "Project",
+ "load_reason": "session_start"
+ }
+
+####
+
+
+
+InstructionsLoaded decision control
+
+InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
+
+###
+
+
+
+UserPromptSubmit
+
+Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts.
+
+####
+
+
+
+UserPromptSubmit input
+
+In addition to the common input fields, UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "UserPromptSubmit",
+ "prompt": "Write a function to calculate the factorial of a number"
+ }
+
+####
+
+
+
+UserPromptSubmit decision control
+
+`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All JSON output fields are available. There are two ways to add context to the conversation on exit code 0:
+
+ * **Plain text stdout** : any non-JSON text written to stdout is added as context
+ * **JSON with`additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
+
+Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely. To block a prompt, return a JSON object with `decision` set to `"block"`:
+
+Field| Description
+---|---
+`decision`| `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed
+`reason`| Shown to the user when `decision` is `"block"`. Not added to context
+`additionalContext`| String added to Claude’s context
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "decision": "block",
+ "reason": "Explanation for decision",
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": "My additional context here"
+ }
+ }
+
+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 block prompts or want more structured control.
+
+###
+
+
+
+PreToolUse
+
+Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, and any MCP tool names. Use PreToolUse decision control to allow, deny, or ask for permission to use the tool.
+
+####
+
+
+
+PreToolUse input
+
+In addition to the common input fields, PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool:
+
+##### Bash
+
+Executes shell commands.
+
+Field| Type| Example| Description
+---|---|---|---
+`command`| string| `"npm test"`| The shell command to execute
+`description`| string| `"Run test suite"`| Optional description of what the command does
+`timeout`| number| `120000`| Optional timeout in milliseconds
+`run_in_background`| boolean| `false`| Whether to run the command in background
+
+##### Write
+
+Creates or overwrites a file.
+
+Field| Type| Example| Description
+---|---|---|---
+`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to write
+`content`| string| `"file content"`| Content to write to the file
+
+##### Edit
+
+Replaces a string in an existing file.
+
+Field| Type| Example| Description
+---|---|---|---
+`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to edit
+`old_string`| string| `"original text"`| Text to find and replace
+`new_string`| string| `"replacement text"`| Replacement text
+`replace_all`| boolean| `false`| Whether to replace all occurrences
+
+##### Read
+
+Reads file contents.
+
+Field| Type| Example| Description
+---|---|---|---
+`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to read
+`offset`| number| `10`| Optional line number to start reading from
+`limit`| number| `50`| Optional number of lines to read
+
+##### Glob
+
+Finds files matching a glob pattern.
+
+Field| Type| Example| Description
+---|---|---|---
+`pattern`| string| `"**/*.ts"`| Glob pattern to match files against
+`path`| string| `"/path/to/dir"`| Optional directory to search in. Defaults to current working directory
+
+##### Grep
+
+Searches file contents with regular expressions.
+
+Field| Type| Example| Description
+---|---|---|---
+`pattern`| string| `"TODO.*fix"`| Regular expression pattern to search for
+`path`| string| `"/path/to/dir"`| Optional file or directory to search in
+`glob`| string| `"*.ts"`| Optional glob pattern to filter files
+`output_mode`| string| `"content"`| `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"`
+`-i`| boolean| `true`| Case insensitive search
+`multiline`| boolean| `false`| Enable multiline matching
+
+##### WebFetch
+
+Fetches and processes web content.
+
+Field| Type| Example| Description
+---|---|---|---
+`url`| string| `"https://example.com/api"`| URL to fetch content from
+`prompt`| string| `"Extract the API endpoints"`| Prompt to run on the fetched content
+
+##### WebSearch
+
+Searches the web.
+
+Field| Type| Example| Description
+---|---|---|---
+`query`| string| `"react hooks best practices"`| Search query
+`allowed_domains`| array| `["docs.example.com"]`| Optional: only include results from these domains
+`blocked_domains`| array| `["spam.example.com"]`| Optional: exclude results from these domains
+
+##### Agent
+
+Spawns a [subagent](</docs/en/sub-agents>).
+
+Field| Type| Example| Description
+---|---|---|---
+`prompt`| string| `"Find all API endpoints"`| The task for the agent to perform
+`description`| string| `"Find API endpoints"`| Short description of the task
+`subagent_type`| string| `"Explore"`| Type of specialized agent to use
+`model`| string| `"sonnet"`| Optional model alias to override the default
+
+####
+
+
+
+PreToolUse decision control
+
+`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.
+
+Field| Description
+---|---
+`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. [Deny and ask rules](</docs/en/permissions#manage-permissions>) still apply when a hook returns `"allow"`
+`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude
+`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
+`additionalContext`| String added to Claude’s context before the tool executes
+
+When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "allow",
+ "permissionDecisionReason": "My reason here",
+ "updatedInput": {
+ "field_to_modify": "new value"
+ },
+ "additionalContext": "Current environment: production. Proceed with caution."
+ }
+ }
+
+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.
+
+###
+
+
+
+PermissionRequest
+
+Runs when the user is shown a permission dialog. Use PermissionRequest decision control to allow or deny on behalf of the user. Matches on tool name, same values as PreToolUse.
+
+####
+
+
+
+PermissionRequest input
+
+PermissionRequest 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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "PermissionRequest",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "rm -rf node_modules",
+ "description": "Remove node_modules directory"
+ },
+ "permission_suggestions": [
+ {
+ "type": "addRules",
+ "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],
+ "behavior": "allow",
+ "destination": "localSettings"
+ }
+ ]
+ }
+
+####
+
+
+
+PermissionRequest decision control
+
+`PermissionRequest` hooks can allow or deny permission requests. In addition to the JSON output fields available to all hooks, your hook script can return a `decision` object with these event-specific fields:
+
+Field| Description
+---|---
+`behavior`| `"allow"` grants the permission, `"deny"` denies it
+`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution
+`updatedPermissions`| For `"allow"` only: array of permission update entries to apply, such as adding an allow rule or changing the session permission mode
+`message`| For `"deny"` only: tells Claude why the permission was denied
+`interrupt`| For `"deny"` only: if `true`, stops Claude
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PermissionRequest",
+ "decision": {
+ "behavior": "allow",
+ "updatedInput": {
+ "command": "npm run lint"
+ }
+ }
+ }
+ }
+
+####
+
+
+
+Permission update entries
+
+The `updatedPermissions` output field and the `permission_suggestions` input field both use the same array of entry objects. Each entry has a `type` that determines its other fields, and a `destination` that controls where the change is written.
+
+`type`| Fields| Effect
+---|---|---
+`addRules`| `rules`, `behavior`, `destination`| Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"`
+`replaceRules`| `rules`, `behavior`, `destination`| Replaces all rules of the given `behavior` at the `destination` with the provided `rules`
+`removeRules`| `rules`, `behavior`, `destination`| Removes matching rules of the given `behavior`
+`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan`
+`addDirectories`| `directories`, `destination`| Adds working directories. `directories` is an array of path strings
+`removeDirectories`| `directories`, `destination`| Removes working directories
+
+The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.
+
+`destination`| Writes to
+---|---
+`session`| in-memory only, discarded when the session ends
+`localSettings`| `.claude/settings.local.json`
+`projectSettings`| `.claude/settings.json`
+`userSettings`| `~/.claude/settings.json`
+
+A hook can echo one of the `permission_suggestions` it received as its own `updatedPermissions` output, which is equivalent to the user selecting that “always allow” option in the dialog.
+
+###
+
+
+
+PostToolUse
+
+Runs immediately after a tool completes successfully. Matches on tool name, same values as PreToolUse.
+
+####
+
+
+
+PostToolUse input
+
+`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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Write",
+ "tool_input": {
+ "file_path": "/path/to/file.txt",
+ "content": "file content"
+ },
+ "tool_response": {
+ "filePath": "/path/to/file.txt",
+ "success": true
+ },
+ "tool_use_id": "toolu_01ABC123..."
+ }
+
+####
+
+
+
+PostToolUse decision control
+
+`PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
+
+Field| Description
+---|---
+`decision`| `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed
+`reason`| Explanation shown to Claude when `decision` is `"block"`
+`additionalContext`| Additional context for Claude to consider
+`updatedMCPToolOutput`| For MCP tools only: replaces the tool’s output with the provided value
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "decision": "block",
+ "reason": "Explanation for decision",
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUse",
+ "additionalContext": "Additional information for Claude"
+ }
+ }
+
+###
+
+
+
+PostToolUseFailure
+
+Runs 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. Matches on tool name, same values as PreToolUse.
+
+####
+
+
+
+PostToolUseFailure input
+
+PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUseFailure",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "npm test",
+ "description": "Run test suite"
+ },
+ "tool_use_id": "toolu_01ABC123...",
+ "error": "Command exited with non-zero status code 1",
+ "is_interrupt": false
+ }
+
+Field| Description
+---|---
+`error`| String describing what went wrong
+`is_interrupt`| Optional boolean indicating whether the failure was caused by user interruption
+
+####
+
+
+
+PostToolUseFailure decision control
+
+`PostToolUseFailure` hooks can provide context to Claude after a tool failure. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
+
+Field| Description
+---|---
+`additionalContext`| Additional context for Claude to consider alongside the error
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUseFailure",
+ "additionalContext": "Additional information about the failure for Claude"
+ }
+ }
+
+###
+
+
+
+Notification
+
+Runs 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. Use 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:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Notification": [
+ {
+ "matcher": "permission_prompt",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "/path/to/permission-alert.sh"
+ }
+ ]
+ },
+ {
+ "matcher": "idle_prompt",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "/path/to/idle-notification.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+####
+
+
+
+Notification input
+
+In addition to the common input fields, Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "Notification",
+ "message": "Claude needs your permission to use Bash",
+ "title": "Permission needed",
+ "notification_type": "permission_prompt"
+ }
+
+Notification hooks cannot block or modify notifications. In addition to the JSON output fields available to all hooks, you can return `additionalContext` to add context to the conversation:
+
+Field| Description
+---|---
+`additionalContext`| String added to Claude’s context
+
+###
+
+
+
+SubagentStart
+
+Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).
+
+####
+
+
+
+SubagentStart input
+
+In addition to the 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).
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "SubagentStart",
+ "agent_id": "agent-abc123",
+ "agent_type": "Explore"
+ }
+
+SubagentStart hooks cannot block subagent creation, but they can inject context into the subagent. In addition to the JSON output fields available to all hooks, you can return:
+
+Field| Description
+---|---
+`additionalContext`| String added to the subagent’s context
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "SubagentStart",
+ "additionalContext": "Follow security guidelines for this task"
+ }
+ }
+
+###
+
+
+
+SubagentStop
+
+Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.
+
+####
+
+
+
+SubagentStop input
+
+In addition to the 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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "~/.claude/projects/.../abc123.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "SubagentStop",
+ "stop_hook_active": false,
+ "agent_id": "def456",
+ "agent_type": "Explore",
+ "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
+ "last_assistant_message": "Analysis complete. Found 3 potential issues..."
+ }
+
+SubagentStop hooks use the same decision control format as Stop hooks.
+
+###
+
+
+
+Stop
+
+Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt. API errors fire StopFailure instead.
+
+####
+
+
+
+Stop input
+
+In addition to the 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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "Stop",
+ "stop_hook_active": true,
+ "last_assistant_message": "I've completed the refactoring. Here's a summary..."
+ }
+
+####
+
+
+
+Stop decision control
+
+`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields:
+
+Field| Description
+---|---
+`decision`| `"block"` prevents Claude from stopping. Omit to allow Claude to stop
+`reason`| Required when `decision` is `"block"`. Tells Claude why it should continue
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "decision": "block",
+ "reason": "Must be provided when Claude is blocked from stopping"
+ }
+
+###
+
+
+
+StopFailure
+
+Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.
+
+####
+
+
+
+StopFailure input
+
+In addition to the common input fields, StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering.
+
+Field| Description
+---|---
+`error`| Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown`
+`error_details`| Additional details about the error, when available
+`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"`
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "StopFailure",
+ "error": "rate_limit",
+ "error_details": "429 Too Many Requests",
+ "last_assistant_message": "API Error: Rate limit reached"
+ }
+
+StopFailure hooks have no decision control. They run for notification and logging purposes only.
+
+###
+
+
+
+TeammateIdle
+
+Runs when an [agent team](</docs/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. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
+
+####
+
+
+
+TeammateIdle input
+
+In addition to the common input fields, TeammateIdle hooks receive `teammate_name` and `team_name`.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "TeammateIdle",
+ "teammate_name": "researcher",
+ "team_name": "my-project"
+ }
+
+Field| Description
+---|---
+`teammate_name`| Name of the teammate that is about to go idle
+`team_name`| Name of the team
+
+####
+
+
+
+TeammateIdle decision control
+
+TeammateIdle hooks support two ways to control teammate behavior:
+
+ * **Exit code 2** : the teammate receives the stderr message as feedback and continues working instead of going idle.
+ * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
+
+This example checks that a build artifact exists before allowing a teammate to go idle:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+
+ if [ ! -f "./dist/output.js" ]; then
+ echo "Build artifact missing. Run the build before stopping." >&2
+ exit 2
+ fi
+
+ exit 0
+
+###
+
+
+
+TaskCompleted
+
+Runs 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](</docs/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. When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks do not support matchers and fire on every occurrence.
+
+####
+
+
+
+TaskCompleted input
+
+In addition to the common input fields, TaskCompleted hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "TaskCompleted",
+ "task_id": "task-001",
+ "task_subject": "Implement user authentication",
+ "task_description": "Add login and signup endpoints",
+ "teammate_name": "implementer",
+ "team_name": "my-project"
+ }
+
+Field| Description
+---|---
+`task_id`| Identifier of the task being completed
+`task_subject`| Title of the task
+`task_description`| Detailed description of the task. May be absent
+`teammate_name`| Name of the teammate completing the task. May be absent
+`team_name`| Name of the team. May be absent
+
+####
+
+
+
+TaskCompleted decision control
+
+TaskCompleted hooks support two ways to control task completion:
+
+ * **Exit code 2** : the task is not marked as completed and the stderr message is fed back to the model as feedback.
+ * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
+
+This example runs tests and blocks task completion if they fail:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+ INPUT=$(cat)
+ TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
+
+ # Run the test suite
+ if ! npm test 2>&1; then
+ echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2
+ exit 2
+ fi
+
+ exit 0
+
+###
+
+
+
+ConfigChange
+
+Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files. ConfigChange 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. The matcher filters on the configuration source:
+
+Matcher| When it fires
+---|---
+`user_settings`| `~/.claude/settings.json` changes
+`project_settings`| `.claude/settings.json` changes
+`local_settings`| `.claude/settings.local.json` changes
+`policy_settings`| Managed policy settings change
+`skills`| A skill file in `.claude/skills/` changes
+
+This example logs all configuration changes for security auditing:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "ConfigChange": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+####
+
+
+
+ConfigChange input
+
+In addition to the 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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "ConfigChange",
+ "source": "project_settings",
+ "file_path": "/Users/.../my-project/.claude/settings.json"
+ }
+
+####
+
+
+
+ConfigChange decision control
+
+ConfigChange 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.
+
+Field| Description
+---|---
+`decision`| `"block"` prevents the configuration change from being applied. Omit to allow the change
+`reason`| Explanation shown to the user when `decision` is `"block"`
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "decision": "block",
+ "reason": "Configuration changes to project settings require admin approval"
+ }
+
+`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.
+
+###
+
+
+
+WorktreeCreate
+
+When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/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. The 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. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "WorktreeCreate": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The 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.
+
+####
+
+
+
+WorktreeCreate input
+
+In addition to the 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`).
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "WorktreeCreate",
+ "name": "feature-auth"
+ }
+
+####
+
+
+
+WorktreeCreate output
+
+The 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. WorktreeCreate 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.
+
+###
+
+
+
+WorktreeRemove
+
+The cleanup counterpart to 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. Claude 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:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "WorktreeRemove": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+####
+
+
+
+WorktreeRemove input
+
+In addition to the common input fields, WorktreeRemove hooks receive the `worktree_path` field, which is the absolute path to the worktree being removed.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "WorktreeRemove",
+ "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
+ }
+
+WorktreeRemove 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.
+
+###
+
+
+
+PreCompact
+
+Runs before Claude Code is about to run a compact operation. The matcher value indicates whether compaction was triggered manually or automatically:
+
+Matcher| When it fires
+---|---
+`manual`| `/compact`
+`auto`| Auto-compact when the context window is full
+
+####
+
+
+
+PreCompact input
+
+In addition to the 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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "PreCompact",
+ "trigger": "manual",
+ "custom_instructions": ""
+ }
+
+###
+
+
+
+PostCompact
+
+Runs after Claude Code completes a compact operation. Use this event to react to the new compacted state, for example to log the generated summary or update external state. The same matcher values apply as for `PreCompact`:
+
+Matcher| When it fires
+---|---
+`manual`| After `/compact`
+`auto`| After auto-compact when the context window is full
+
+####
+
+
+
+PostCompact input
+
+In addition to the common input fields, PostCompact hooks receive `trigger` and `compact_summary`. The `compact_summary` field contains the conversation summary generated by the compact operation.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "PostCompact",
+ "trigger": "manual",
+ "compact_summary": "Summary of the compacted conversation..."
+ }
+
+PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
+
+###
+
+
+
+SessionEnd
+
+Runs when a Claude Code session ends. Useful for cleanup tasks, logging session statistics, or saving session state. Supports matchers to filter by exit reason. The `reason` field in the hook input indicates why the session ended:
+
+Reason| Description
+---|---
+`clear`| Session cleared with `/clear` command
+`resume`| Session switched via interactive `/resume`
+`logout`| User logged out
+`prompt_input_exit`| User exited while prompt input was visible
+`bypass_permissions_disabled`| Bypass permissions mode was disabled
+`other`| Other exit reasons
+
+####
+
+
+
+SessionEnd input
+
+In addition to the common input fields, SessionEnd hooks receive a `reason` field indicating why the session ended. See the reason table above for all values.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "hook_event_name": "SessionEnd",
+ "reason": "other"
+ }
+
+SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
+
+###
+
+
+
+Elicitation
+
+Runs when an MCP server requests user input mid-task. By default, Claude Code shows an interactive dialog for the user to respond. Hooks can intercept this request and respond programmatically, skipping the dialog entirely. The matcher field matches against the MCP server name.
+
+####
+
+
+
+Elicitation input
+
+In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation (the most common case):
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "Elicitation",
+ "mcp_server_name": "my-mcp-server",
+ "message": "Please provide your credentials",
+ "mode": "form",
+ "requested_schema": {
+ "type": "object",
+ "properties": {
+ "username": { "type": "string", "title": "Username" }
+ }
+ }
+ }
+
+For URL-mode elicitation (browser-based authentication):
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "Elicitation",
+ "mcp_server_name": "my-mcp-server",
+ "message": "Please authenticate",
+ "mode": "url",
+ "url": "https://auth.example.com/login"
+ }
+
+####
+
+
+
+Elicitation output
+
+To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "Elicitation",
+ "action": "accept",
+ "content": {
+ "username": "alice"
+ }
+ }
+ }
+
+Field| Values| Description
+---|---|---
+`action`| `accept`, `decline`, `cancel`| Whether to accept, decline, or cancel the request
+`content`| object| Form field values to submit. Only used when `action` is `accept`
+
+Exit code 2 denies the elicitation and shows stderr to the user.
+
+###
+
+
+
+ElicitationResult
+
+Runs after a user responds to an MCP elicitation. Hooks can observe, modify, or block the response before it is sent back to the MCP server. The matcher field matches against the MCP server name.
+
+####
+
+
+
+ElicitationResult input
+
+In addition to the common input fields, ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123",
+ "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
+ "cwd": "/Users/...",
+ "permission_mode": "default",
+ "hook_event_name": "ElicitationResult",
+ "mcp_server_name": "my-mcp-server",
+ "action": "accept",
+ "content": { "username": "alice" },
+ "mode": "form",
+ "elicitation_id": "elicit-123"
+ }
+
+####
+
+
+
+ElicitationResult output
+
+To override the user’s response, return a JSON object with `hookSpecificOutput`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "ElicitationResult",
+ "action": "decline",
+ "content": {}
+ }
+ }
+
+Field| Values| Description
+---|---|---
+`action`| `accept`, `decline`, `cancel`| Overrides the user’s action
+`content`| object| Overrides form field values. Only meaningful when `action` is `accept`
+
+Exit code 2 blocks the response, changing the effective action to `decline`.
+
+##
+
+
+
+Prompt-based hooks
+
+In addition to command and HTTP hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type. Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):
+
+ * `PermissionRequest`
+ * `PostToolUse`
+ * `PostToolUseFailure`
+ * `PreToolUse`
+ * `Stop`
+ * `SubagentStop`
+ * `TaskCompleted`
+ * `UserPromptSubmit`
+
+Events that only support `type: "command"` hooks:
+
+ * `ConfigChange`
+ * `Elicitation`
+ * `ElicitationResult`
+ * `InstructionsLoaded`
+ * `Notification`
+ * `PostCompact`
+ * `PreCompact`
+ * `SessionEnd`
+ * `SessionStart`
+ * `StopFailure`
+ * `SubagentStart`
+ * `TeammateIdle`
+ * `WorktreeCreate`
+ * `WorktreeRemove`
+
+###
+
+
+
+How prompt-based hooks work
+
+Instead of executing a Bash command, prompt-based hooks:
+
+ 1. Send the hook input and your prompt to a Claude model, Haiku by default
+ 2. The LLM responds with structured JSON containing a decision
+ 3. Claude Code processes the decision automatically
+
+###
+
+
+
+Prompt hook configuration
+
+Set `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. This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "prompt",
+ "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+Field| Required| Description
+---|---|---
+`type`| yes| Must be `"prompt"`
+`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
+`model`| no| Model to use for evaluation. Defaults to a fast model
+`timeout`| no| Timeout in seconds. Default: 30
+
+###
+
+
+
+Response schema
+
+The LLM must respond with JSON containing:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "ok": true | false,
+ "reason": "Explanation for the decision"
+ }
+
+Field| Description
+---|---
+`ok`| `true` allows the action, `false` prevents it
+`reason`| Required when `ok` is `false`. Explanation shown to Claude
+
+###
+
+
+
+Example: Multi-criteria Stop hook
+
+This `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](</docs/en/sub-agents>) should stop:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "prompt",
+ "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.",
+ "timeout": 30
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+##
+
+
+
+Agent-based hooks
+
+Agent-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.
+
+###
+
+
+
+How agent hooks work
+
+When an agent hook fires:
+
+ 1. Claude Code spawns a subagent with your prompt and the hook’s JSON input
+ 2. The subagent can use tools like Read, Grep, and Glob to investigate
+ 3. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision
+ 4. Claude Code processes the decision the same way as a prompt hook
+
+Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.
+
+###
+
+
+
+Agent hook configuration
+
+Set `type` to `"agent"` and provide a `prompt` string. The configuration fields are the same as prompt hooks, with a longer default timeout:
+
+Field| Required| Description
+---|---|---
+`type`| yes| Must be `"agent"`
+`prompt`| yes| Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON
+`model`| no| Model to use. Defaults to a fast model
+`timeout`| no| Timeout in seconds. Default: 60
+
+The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block. This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "agent",
+ "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",
+ "timeout": 120
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+##
+
+
+
+Run hooks in the background
+
+By 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.
+
+###
+
+
+
+Configure an async hook
+
+Add `"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. This 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:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Write",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "/path/to/run-tests.sh",
+ "async": true,
+ "timeout": 120
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The `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.
+
+###
+
+
+
+How async hooks execute
+
+When 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. After 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. Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.
+
+###
+
+
+
+Example: run tests after file changes
+
+This 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`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+ # run-tests-async.sh
+
+ # Read hook input from stdin
+ INPUT=$(cat)
+ FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
+
+ # Only run tests for source files
+ if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then
+ exit 0
+ fi
+
+ # Run tests and report results via systemMessage
+ RESULT=$(npm test 2>&1)
+ EXIT_CODE=$?
+
+ if [ $EXIT_CODE -eq 0 ]; then
+ echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"
+ else
+ echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"
+ fi
+
+Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Write|Edit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",
+ "async": true,
+ "timeout": 300
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+###
+
+
+
+Limitations
+
+Async hooks have several constraints compared to synchronous hooks:
+
+ * Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.
+ * Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
+ * Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.
+ * Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
+
+##
+
+
+
+Security considerations
+
+###
+
+
+
+Disclaimer
+
+Command hooks run with your system user’s full permissions.
+
+Command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration.
+
+###
+
+
+
+Security best practices
+
+Keep these practices in mind when writing hooks:
+
+ * **Validate and sanitize inputs** : never trust input data blindly
+ * **Always quote shell variables** : use `"$VAR"` not `$VAR`
+ * **Block path traversal** : check for `..` in file paths
+ * **Use absolute paths** : specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root
+ * **Skip sensitive files** : avoid `.env`, `.git/`, keys, etc.
+
+##
+
+
+
+Debug hooks
+
+Run `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.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ [DEBUG] Executing hooks for PostToolUse:Write
+ [DEBUG] Getting matching hook commands for PostToolUse with query: Write
+ [DEBUG] Found 1 hook matchers in settings
+ [DEBUG] Matched 1 hooks for query "Write"
+ [DEBUG] Found 1 hook commands to execute
+ [DEBUG] Executing hook command: <Your command> with timeout 600000ms
+ [DEBUG] Hook command completed with status 0: <Your stdout>
+
+For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide.