Claude Code hooks: which event to use when
Claude Code can run your own code at fixed points in a session: when it starts, before a prompt, before and after each tool call, and when Claude stops. These points are hook events.
This page sorts the events by when they fire and what they can do. It helps you pick the right one. Every fact comes from the official hooks reference.
What a hook is
A hook is a handler that Claude Code runs when an event fires. The handler can be a shell command, an HTTP endpoint, an MCP tool, a prompt to a Claude model, or a subagent.
Claude Code passes the event as JSON. A command reads it on stdin. An HTTP hook gets it as the body of a POST request.
You define hooks in a settings file, in three levels: the event, a matcher group that filters it, and the handlers to run. This example from the reference runs a lint script whenever Claude writes or edits a file:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "/path/to/lint-check.sh"
}
]
}
]
}
}Three rhythms
The reference names three rhythms:
- Once per session:
SessionStartandSessionEnd. - Once per turn:
UserPromptSubmit,StopandStopFailure. - On every tool call:
PreToolUseandPostToolUse.
The rhythm tells you the cost. A slow hook on every tool call slows down every step Claude takes. A slow SessionStart hook costs you once.
Six events to know first
SessionStart
- Fires
- When a session begins or resumes. The matcher tells how it started:
startup,resume,clear,compactorfork. - Can block
- No. Exit code 2 only shows your stderr to you.
- Output
- Plain text on stdout, or additionalContext. Claude gets it at the start of the conversation, before the first prompt.
- Use it for
- The current branch, open issues, a short briefing from earlier sessions. With the
compactmatcher it puts critical context back after compaction: what survives /compact.
Only command and mcp_tool handlers run here. Claude's first response waits for these hooks, so keep them fast.
UserPromptSubmit
- Fires
- When a prompt is submitted, before Claude processes it. Also on turns Claude Code starts by itself, such as a scheduled task or a
/loopiteration. It has no matcher. - Can block
- Yes. Exit code 2 or a block decision rejects the prompt. It never reaches Claude.
- Output
- Plain text on stdout, or additionalContext. Claude gets it alongside the prompt. The hook cannot replace the prompt.
- Use it for
- Notes that match this prompt. Checks on what a prompt may contain.
Command, HTTP and MCP tool handlers get 30 seconds by default. At the limit Claude Code discards the output, and the prompt goes on without it. Full guide with a working hook.
PreToolUse
- Fires
- After Claude creates the tool parameters, before the call runs. The matcher filters on the tool name, for example
Bash,Edit|Writeormcp__.*. - Can block
- Yes.
permissionDecisioncan beallow,deny,askordefer. Exit code 2 works like deny. - Output
updatedInputreplaces the tool's arguments.additionalContextlands next to the tool result.- Use it for
- Stop destructive commands. Keep edits out of folders that must stay untouched.
A command hook that times out does not block the call. Set "onFailure": "block" if it should. Files you attach with @ in a prompt reach Claude without a tool call, so this hook never sees them.
PostToolUse
- Fires
- Right after a tool call succeeds. A failed call fires
PostToolUseFailureinstead. - Can block
- No, the tool already ran. Exit code 2 shows your stderr to Claude. A block decision adds your reason next to the result.
- Output
updatedToolOutputreplaces the result Claude sees.additionalContextlands next to it.- Use it for
- Run a linter after each edit. Tell Claude a file is generated.
Stop
- Fires
- When Claude finishes responding. A user interrupt does not fire it. An API error fires StopFailure instead.
- Can block
- Yes: Claude keeps working. A block decision needs a
reason, which Claude reads as the reason to continue. - Output
additionalContextalso continues the turn, labelled as feedback instead of an error.- Use it for
- Check that the tests ran before Claude stops. Record a fix from the last answer.
The input carries last_assistant_message, Claude's final text, and stop_hook_active, which is true when a stop hook already continued the turn. After eight continuations in a row, Claude Code ends the turn anyway.
SessionEnd
- Fires
- When a session ends. The matcher tells why, for example
clear,logoutorother. - Can block
- No.
- Output
- Nothing for Claude. The session is over.
- Use it for
- Clean up, write logs, save state.
All SessionEnd hooks share a budget of 1.5 seconds. A longer timeout in your settings raises it, up to 60 seconds.
The other events
The reference lists more events for special cases. Here they are by topic, each with the moment it fires.
Tools and permissions
- PermissionRequest
- A tool call needs a permission decision. Decide with the decision object; exit code 2 has no effect here.
- PermissionDenied
- Auto mode denied a tool call. The hook can tell the model it may retry.
- PostToolUseFailure
- A tool call failed. Exit code 2 shows your stderr to Claude.
- PostToolBatch
- A batch of parallel tool calls resolved, before the next model call. Can stop the loop.
Prompts and turns
- UserPromptExpansion
- A command you typed expands into a prompt. Can block the expansion.
- StopFailure
- The turn ended on an API error, such as a rate limit. For logs and alerts; output is ignored.
- MessageDisplay
- Assistant text is displayed. Changes only what you see on screen.
Subagents, tasks and teams
- SubagentStart
- A subagent is spawned. Can add context for it.
- SubagentStop
- A subagent finishes. Can keep it working.
- TaskCreated
- A task is being created. Can roll it back.
- TaskCompleted
- A task is being marked as completed. Can prevent that.
- TeammateIdle
- An agent team teammate is about to go idle. Can keep it working.
Session, context and model
- Setup
- Claude Code starts with
--init-only, or with--initor--maintenancein-pmode. - InstructionsLoaded
- A CLAUDE.md or .claude/rules/*.md file is loaded into context.
- PreCompact
- Before context compaction. Can block it.
- PostCompact
- After compaction completes.
- PreModelSwitch
- Before a model switch you or a client requested. Can block it.
- PostModelSwitch
- After the session's model changed. Can add context.
Files, folders and settings
- CwdChanged
- The working directory changes, for example after a cd.
- DirectoryAdded
- A working directory is added during the session.
- FileChanged
- A watched file changes on disk, whatever wrote it.
- ConfigChange
- A configuration file changes during the session. Can block the change.
- WorktreeCreate
- A worktree is being created. Replaces the default git behavior.
- WorktreeRemove
- A worktree that a WorktreeCreate hook created is being removed.
Notifications and MCP
- Notification
- Claude Code sends a notification, for example when it needs your input.
- Elicitation
- An MCP server asks for user input during a tool call.
- ElicitationResult
- You answered an MCP request, before the answer goes back to the server.
How a hook answers
The exit code decides what happens next:
- 0: success. Claude Code reads the JSON you printed. On
SessionStart,UserPromptSubmit,UserPromptExpansionandPostModelSwitch, plain text on stdout becomes context for Claude. On most other events it goes to the debug log. - 2: a blocking error. On events that can block, Claude Code stops the action and uses your stderr as the reason.
- Any other code: a non-blocking error. The action goes ahead and you see a notice. This includes exit code 1, so a policy hook must exit with 2.
To add context, print one JSON object with hookSpecificOutput.additionalContext and nothing else on stdout. Where Claude reads it depends on the event:
- SessionStart, SubagentStart
- At the start of the conversation, before the first prompt.
- UserPromptSubmit, UserPromptExpansion
- Alongside the submitted prompt.
- PreToolUse, PostToolUse, PostToolUseFailure, PostToolBatch
- Next to the tool result.
- Stop, SubagentStop
- At the end of the turn. The conversation continues so Claude can act on it.
- PostModelSwitch
- With the next request after the switch.
Claude Code wraps the text in a system reminder. Above 10,000 characters it saves the text to a file and passes Claude the path and a preview. Write facts, such as "This repo uses bun test". Text that reads like a system command can trigger Claude's prompt-injection defenses.
Command, HTTP and MCP tool handlers get 600 seconds by default. UserPromptSubmit, PreModelSwitch and PostModelSwitch get 30, MessageDisplay gets 10. Set timeout on the handler to change it.
Where hooks live
The file you put a hook in decides who runs it:
- ~/.claude/settings.json
- All your projects, on your machine only.
- .claude/settings.json
- One project. You can commit it, so your team runs it too.
- .claude/settings.local.json
- One project, for you alone.
- Managed policy settings
- The whole organization, set by an admin.
- Plugin hooks/hooks.json
- While the plugin is enabled.
- Skill frontmatter
- For the rest of the session, once the skill is invoked.
- Subagent frontmatter
- While that subagent runs.
Hooks from all levels add up. All hooks that match an event run in parallel. The same handler in two settings files runs once.
Before you add one
Command hooks run with your full user permissions. Read every hook before you add it, including the ones a repository brings along.
In an interactive session, Claude Code holds back hooks from settings files until you accept the workspace trust dialog for the folder. A -p or SDK session treats the folder as trusted. There, hooks committed in a repository's .claude/settings.json run right away. Before you script claude -p over a repository you did not write, check its .claude/ folder, or turn hooks off for that run:
claude -p "..." \
--settings '{"disableAllHooks": true}'To watch your hooks run, start Claude Code with claude --debug and read ~/.claude/debug/<session-id>.txt.
Hooks that carry experience
Each session starts without what the last one figured out. Three events let you carry that experience forward:
SessionStartbriefs the new session: what changed, what to watch out for.UserPromptSubmitadds the notes that match this prompt, right before Claude reads it.Stopreadslast_assistant_messageand can record a fix while it is fresh.
The notes only help when they are written well. How to write a lesson your coding agent can use shows the format with real examples.
cachly ships all three hooks. It turns your fixes, decisions and git history into lessons, and adds the matching ones to each prompt. Its servers are in the EU. What leaves your machine, and where it goes.
/plugin marketplace add cachly-dev/cachly-mcp
/plugin install cachly-brain@cachlyThen turn on auto-update once: /plugin → Marketplaces → cachly → Enable auto-update. Claude Code leaves it off for marketplaces outside Anthropic's own, and the hooks update only with the plugin.
The same hooks in Cursor
Cursor has its own hooks in .cursor/hooks.json. It also runs Claude Code hooks from .claude/settings.json when the setting "Include Third-Party Plugins, Skills, and Other Configs" is on, which is the default. There, UserPromptSubmit becomes beforeSubmitPrompt.
In Cursor, beforeSubmitPrompt answers with two fields: continue and user_message. It lets the prompt through or blocks it. Context goes in through these events:
- sessionStart
- additional_context joins the conversation's initial system context. Cursor runs this hook fire-and-forget.
- postToolUse
- additional_context joins the conversation after the tool result.
- postToolUseFailure
- additional_context joins the conversation after the failed tool result.
So cachly works in two steps in Cursor. beforeSubmitPrompt picks the lessons that match the prompt and keeps them. The first tool call of that turn hands them to the agent through postToolUse. sessionStart adds the session briefing. cachly's setup writes this file when the project has a .cursor folder:
{
"version": 1,
"hooks": {
"sessionStart": [
{
"command": "node .cursor/hooks/cachly-ambient-cursor.mjs sessionStart",
"timeout": 30
}
],
"beforeSubmitPrompt": [
{
"command": "node .cursor/hooks/cachly-ambient-cursor.mjs beforeSubmitPrompt",
"timeout": 10
}
],
"postToolUse": [
{
"command": "node .cursor/hooks/cachly-ambient-cursor.mjs postToolUse",
"timeout": 5
}
]
}
}Project hooks run from the project root, in trusted workspaces. The Hooks tab in Customize and the Hooks output channel show each run.
The same hooks in VS Code and Copilot CLI
VS Code reads hook files from .github/hooks/*.json in the workspace. GitHub Copilot CLI and the Copilot cloud agent read the same folder. The files use Copilot's format: a numeric version and event names in lower camel case.
In VS Code's own agent ("Local"), sessionStart and userPromptSubmitted both take hookSpecificOutput.additionalContext. For the prompt event, the reference lists only the common output; VS Code's source reads the field there since February 2026. Hooks run while chat.useHooks is on, which is the default, in a trusted workspace.
Copilot CLI drops the output of userPromptSubmitted. It takes context at sessionStart, and at postToolUse it appends it to the tool result. So there, as in Cursor, the lessons for a prompt arrive with the first tool call of the turn. cachly's setup writes this file when the project has a .vscode folder:
{
"version": 1,
"hooks": {
"sessionStart": [
{
"type": "command",
"command": "node .github/hooks/cachly-ambient-copilot.mjs sessionStart",
"cwd": ".",
"timeoutSec": 30
}
],
"userPromptSubmitted": [
{
"type": "command",
"command": "node .github/hooks/cachly-ambient-copilot.mjs userPromptSubmitted",
"cwd": ".",
"timeoutSec": 10
}
],
"postToolUse": [
{
"type": "command",
"command": "node .github/hooks/cachly-ambient-copilot.mjs postToolUse",
"cwd": ".",
"timeoutSec": 5
}
]
}
}The Output panel shows each run in the "GitHub Copilot Chat Hooks" channel.
The same hooks in Codex CLI
Codex reads project hooks from .codex/hooks.json, in the same shape as Claude Code: groups of hooks with type, command and timeout. At SessionStart and UserPromptSubmit, hookSpecificOutput.additionalContext is added as extra developer context.
Project hooks load once you trust the project's .codex/ folder. Each new or changed hook also waits for your review: type /hooks in the CLI.
Codex runs hook commands in the session's working directory, which can be a subfolder. So the command names the script by its full path, and setup fills in your project's path. It writes the file when it finds a ~/.codex folder:
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "node \"/path/to/project/.codex/hooks/cachly-ambient-codex.mjs\" SessionStart",
"timeout": 30
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "node \"/path/to/project/.codex/hooks/cachly-ambient-codex.mjs\" UserPromptSubmit",
"timeout": 10
}
]
}
]
}
}For the cachly tools, setup and init --editor codex also write the MCP server into the project's .codex/config.toml as [mcp_servers.cachly]. Codex loads it once you trust the folder, like the hooks.
The same hooks in Gemini CLI
Gemini CLI reads hooks from the hooks field of .gemini/settings.json. Its timeouts are in milliseconds.
Context from SessionStart becomes the first turn of the history. BeforeAgent fires after you send a prompt and before the agent starts planning; its hookSpecificOutput.additionalContext is appended to the prompt for this turn only. cachly's setup adds these entries when it finds a ~/.gemini folder, and leaves the rest of the file as it is:
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"name": "cachly-briefing",
"type": "command",
"command": "node .gemini/hooks/cachly-ambient-gemini.mjs SessionStart",
"timeout": 30000
}
]
}
],
"BeforeAgent": [
{
"hooks": [
{
"name": "cachly-recall",
"type": "command",
"command": "node .gemini/hooks/cachly-ambient-gemini.mjs BeforeAgent",
"timeout": 10000
}
]
}
]
}
}For the cachly tools, the same file gets the MCP server as mcpServers.cachly. Gemini starts it once you trust the folder. A file with comments stays as it is; then setup prints the gemini mcp add -s project line instead.
Set it up in one command
Run npx @cachly-dev/mcp-server@latest autopilot and it sets up all of this for you. Get a free Brain to connect it.
Sources
- Claude Code docs: Hooks reference (events, matchers, exit codes, context, timeouts, locations, trust)
- Claude Code docs: Automate actions with hooks
- Cursor docs: Hooks (events, answers, locations, trust)
- Cursor docs: Third Party Hooks (Claude Code hooks in Cursor)
- VS Code docs: Hooks and hooks reference (locations, formats, settings, output)
- GitHub docs: Copilot hooks reference (Copilot CLI and cloud agent)
- OpenAI docs: Codex hooks (events, context, trust, /hooks)
- Gemini CLI docs: Hooks reference (events, context, timeouts)
Checked against the hooks reference on .
More: UserPromptSubmit hook guide · Lessons learned for coding agents · All docs