Events
| Event | When it fires | Example |
|---|---|---|
PreToolUse | before a tool call | block a dangerous command |
PostToolUse | after a tool call | format the changed file |
UserPromptSubmit | when you send a prompt | add context, validate the prompt |
Stop | when the agent finishes a reply | notify that the task is done |
Notification | when the agent waits for you | a message that permission is needed |
SessionStart | at session start | load fresh context |
Example: auto-format after edits
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "npx prettier --write \"$CLAUDE_PROJECT_DIR\"/src" }]
}
]
}
}
Hooks live in the same settings.json files as permissions. The /hooks command helps you view and configure them in a session.
Guardrails: blocking commands
A PreToolUse hook receives the tool call as JSON on standard input. The script can inspect it and, if it is dangerous, exit with code 2: the call is blocked and the stderr message is shown to the agent as the reason.
# .claude/hooks/block-secrets.sh input=$(cat) if echo "$input" | grep -q '\.env'; then echo "Access to .env is forbidden" >&2 exit 2 fi
Hook ideas
- Formatting and linting after every file change.
- Forbidding edits to generated files or migrations.
- Running fast tests when the agent finishes.
- A Telegram or Slack message when the agent waits for permission.
- A log of every agent command for audit.
Be careful
- A hook runs with your permissions. Review scripts, especially other people’s.
- A slow hook slows every agent step. Keep them fast.
- After changing hooks, test them on a simple task.
10 ready-made recipes are in the article "Claude Code Hooks".
Today's task
Add a PostToolUse hook with your project’s formatter and a Notification hook with a sound or system notification.