Hooks and Permissions
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
This lesson covers the two mechanisms that make Claude Code safe to leave running: permissions, which decide what it may do without asking, and hooks, which let you run your own code at fixed points and block actions. Together they're how you turn "please don't" into "can't". We tested every script in this lesson, including against the real Pint formatter and the real claude doctor.
What you'll learn
- The permission modes and how to switch between them.
- The syntax of allow, ask and deny rules, and which one wins.
- What hooks are, where they run, and how a script blocks or allows an action.
- Four hooks that protect a Laravel project, with tests.
Before you start
Part one: permissions
Modes
A permission mode sets what Claude can do without asking you. Press Shift+Tab to cycle modes, or set defaultMode in settings. The ones you'll use:
- Manual (
default): asks before file edits and shell commands, apart from read-only ones.
- Accept edits (
acceptEdits): accepts file edits and common filesystem commands such as mkdir, mv and cp in your working directory.
- Plan (
plan): Claude reads and explores but doesn't edit your source files.
- Auto (
auto): runs without routine prompts; a background classifier checks actions and blocks risky ones. Anthropic's docs say that, from Claude Code v2.1.283, interactive terminal and VS Code sessions start in auto mode. It blocks things like curl | bash, production deploys, force pushes over others' work and sensitive data sent to external endpoints.
- dontAsk: auto-denies anything that would prompt, so an unattended session keeps working inside rules you set.
bypassPermissions: skips prompts. Anthropic's warning is explicit: use it only in isolated environments such as containers or VMs, because it also skips prompts for protected paths such as .git and .claude.
An organisation can prevent the last two with permissions.disableBypassPermissionsMode and permissions.disableAutoMode in managed settings.
Rules
Rules use the form Tool or Tool(specifier), and live in the permissions block of a settings file under allow, ask or deny:
| Rule | Meaning |
Bash | Every shell command. As a deny rule, it removes the tool from Claude's context entirely. |
Bash(npm run build) | Exactly that command. |
Bash(vendor/bin/pest *) | Any command starting that way; * matches any text. |
Read(./.env) | Reading that file. |
WebFetch(domain:example.com) | Requests to one domain. |
The evaluation order is fixed: deny, then ask, then allow, and the first match wins. Specificity doesn't change that, so a broad deny can't have a narrow exception carved out by an allow rule. The same holds across scopes: if user settings allow something and project settings deny it, it's denied. A rule denied at any level can't be allowed at another.
Claude Code understands shell structure. A rule like Bash(safe-cmd *) won't approve safe-cmd && other-cmd, because every part of a compound command must be allowed, and a deny rule fires if any part matches, even inside $(...) or a for loop. A few wrappers such as timeout, time and nice are stripped before matching. Runners like npx, docker exec and devbox run are not stripped, so Bash(devbox run *) would also match devbox run rm -rf .; write the full command you mean.
Use /permissions to see every rule and which file it came from. Remember the workspace trust rule from lesson 5.3: committed allow rules wait for each person to trust the folder, while deny and ask apply at once.
This is the example project's permissions block:
"permissions": {
"allow": [
"Bash(vendor/bin/pest *)",
"Bash(vendor/bin/pint *)",
"Bash(npm run types:check)",
"Bash(php artisan route:list *)",
"Bash(git status)",
"Bash(git diff *)"
],
"ask": [
"Bash(git push *)",
"Bash(php artisan migrate *)"
],
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./storage/*.key)",
"Bash(php artisan db:wipe *)",
"Bash(rm -rf *)"
]
}
Anthropic's best-practices page notes that deny rules hold in every mode, including auto and bypassPermissions, which is why secrets belong there. It also lists the edges: a Read rule catches cat .env because Claude Code recognises common file-reading commands, but not a script that opens the file; a WebFetch deny does nothing about curl to the same domain unless the sandbox is on. For an operating-system-level limit use /sandbox, which confines shell commands on macOS, Linux and WSL 2 and picks up your Read and WebFetch(domain:...) rules.
Part two: hooks
What they are
Hooks are shell commands (or HTTP calls, or small model checks) that Claude Code runs at specific points in its lifecycle. They give you deterministic control: certain things always happen. Anthropic's guide lists more than thirty events, and the ones you'll use most are:
PreToolUse: before a tool runs. It can block it.
PostToolUse: after a tool succeeds. It can't undo the action; it can format, log or warn.
UserPromptSubmit: when you submit a prompt, before Claude sees it.
SessionStart: when a session starts or resumes.
Stop: when Claude finishes responding. It can send Claude back to work.
Notification: when Claude needs your attention.
The installed version of Claude Code lists 33 event names; our linter's list matches it exactly (we compared them programmatically). A misspelled name such as PreTool is skipped, and claude doctor says so: Unknown hook event "PreTool" was ignored.
How a hook talks to Claude Code
Claude Code passes event data as JSON on the script's standard input. A PreToolUse hook for a Bash command receives something like this:
{
"session_id": "abc123",
"cwd": "/Users/sarah/myproject",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": { "command": "npm test" }
}
The script answers with its exit code:
- Exit 0: no objection. For
PreToolUse this does not approve the call; the normal permission flow still applies.
- Exit 2: block. Whatever the script writes to stderr is sent to Claude as the reason, so it can adjust.
- Any other code, with no valid JSON: the action proceeds, on most events.
For more control, exit 0 and print JSON, for example {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}}. Choose one style per hook: exit 2 with a message, or exit 0 with JSON.
Two properties make hooks the right tool for hard rules. A PreToolUse hook fires before any permission-mode check, so a "deny" holds even in bypassPermissions. And a hook that returns "allow" cannot override your deny rules.
Where to configure them
In the hooks block of a settings file: ~/.claude/settings.json (all your projects), .claude/settings.json (this project, shareable), .claude/settings.local.json (you only), managed settings (organisation-wide), a plugin's hooks/hooks.json, or in the frontmatter of a skill or subagent. A matcher narrows a hook to certain tools, such as "Edit|Write". Run /hooks to browse what's configured. "disableAllHooks": true turns them off. Hook timeouts default to ten minutes for command hooks (30 seconds for UserPromptSubmit), and edits to hook settings apply without a restart.
Four hooks for a Laravel project
All four are in the example project, wired up like this:
"hooks": {
"PreToolUse": [
{ "matcher": "Bash",
"hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-bash.sh" }] },
{ "matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }] }
],
"PostToolUse": [
{ "matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-php.sh" }] }
],
"Stop": [
{ "hooks": [{ "type": "command", "command": "vendor/bin/pint --test --dirty 1>&2 || exit 2" }] }
]
}
Scripts must be executable (chmod +x), and $CLAUDE_PROJECT_DIR makes the path work whatever the working directory is. The scripts use jq to read the input JSON, so install it first.
1. Block destructive commands
#!/bin/bash
# PreToolUse hook for the Bash tool. Reads the hook JSON on stdin and blocks a few commands with exit code 2.
# The message on stderr goes back to Claude so it can pick a safer approach.
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
block() {
echo "Blocked: $1 Ask the user to run it themselves if it is really needed." >&2
exit 2
}
# Commands that destroy a whole database. Matches php artisan, sail artisan and ./vendor/bin/sail artisan.
if echo "$COMMAND" | grep -Eq 'artisan[[:space:]]+(migrate:(fresh|refresh|reset)|db:wipe)'; then
block "this command can erase the database."
fi
# Rewriting shared history.
if echo "$COMMAND" | grep -Eq 'git[[:space:]]+push[[:space:]].*(--force|-f)([[:space:]]|$)'; then
block "force-pushing can overwrite other people's work."
fi
# Running a downloaded script without reading it.
if echo "$COMMAND" | grep -Eq '(curl|wget)[^|]*\|[[:space:]]*(sudo[[:space:]]+)?(ba|z)?sh'; then
block "piping a download straight into a shell."
fi
exit 0
It blocks migrate:fresh, migrate:refresh, migrate:reset and db:wipe (including through sail artisan and with an environment variable in front), force pushes, and piping a download into a shell. Why a hook and not just a deny rule? A deny rule matches command text patterns; this script matches the intent across variants, and the message tells Claude what to do instead. We ran it against 16 commands: eight dangerous ones were blocked with exit code 2, and eight safe ones, including git push --force-with-lease, php artisan migrate and curl -s https://example.com/api, passed with exit 0.
It isn't airtight, and nothing like this is. A command built dynamically in a script would slip through. A hook is a guard rail, not a sandbox. Combine it with deny rules, and with /sandbox for real isolation.
2. Protect files that have their own tools
#!/bin/bash
# PreToolUse hook for Edit and Write. Blocks changes to files that should only change through their own tools.
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}" # normalise Windows separators
BASE="${FILE_PATH##*/}" # the file name without its folder
deny() {
echo "Blocked: $FILE_PATH is protected ($1). Change it with composer or npm, or ask the user." >&2
exit 2
}
# Exact file names. A substring match on ".env" would also block ".env.example", which people do edit.
case "$BASE" in
.env.example) ;; # documentation file, safe to edit
.env|.env.*) deny "environment secrets" ;;
composer.lock|package-lock.json) deny "lock file" ;;
esac
# Whole folders.
case "$FILE_PATH" in
*/.git/*|.git/*) deny "git internals" ;;
*/vendor/*|vendor/*) deny "installed dependencies" ;;
esac
exit 0
Our first version of this script, adapted from a common pattern, used substring matching on .env. Testing showed it also blocked .env.example, a file people legitimately edit, so the script now compares the exact file name and treats .env.example as the one exception. We tested nine protected paths (including a Windows-style path and vendor/) and six allowed ones, such as app/Actions/CreateOrder.php, docs/vendor-guide.md and composer.json. Note that it guards the Edit and Write tools; Claude could still change a file with a shell command, so pair it with an Edit deny rule if that matters.
3. Format after every edit
#!/bin/bash
# PostToolUse hook for Edit and Write. Formats the file that was just changed. Never blocks.
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
[ -z "$FILE" ] && exit 0
case "$FILE" in
*.php)
"$CLAUDE_PROJECT_DIR/vendor/bin/pint" "$FILE" >/dev/null 2>&1 ;;
*.ts|*.tsx|*.js|*.jsx|*.css)
(cd "$CLAUDE_PROJECT_DIR" && npx prettier --write --ignore-unknown "$FILE" >/dev/null 2>&1) ;;
esac
exit 0 # a formatter hiccup must not stop the session
This one never blocks: it always exits 0, so a formatter hiccup can't stop a session. Tested with a deliberately badly formatted PHP file and the project's real Pint, it rewrote function foo( $a,$b ){return $a+$b;} into properly formatted code, ignored a .txt file, and tolerated input with no file path. For files Claude changes through the shell instead, use a FileChanged hook.
4. Don't let Claude stop on failing style checks
The Stop hook runs whenever Claude finishes responding. With vendor/bin/pint --test --dirty 1>&2 || exit 2, a style failure makes the script exit 2, the Pint output goes to stderr as Claude's feedback, and Claude is sent back to fix it. We tested it in a throwaway git repository using the real Pint: with an unformatted new file the command exited 2, and with a clean tree it exited 0. This is the "enforce the check" pattern from Anthropic's best-practices page, which uses a TypeScript typecheck as its example. Be aware Stop hooks fire on every finished response, not only at the end of a task, and there's a cap on how many times a Stop hook can send Claude back, so keep the check fast.
Checking your configuration
Run /hooks to see what's registered and claude doctor for validation. Running the real claude doctor on the example project accepted all of this configuration; it reported only the missing environment variable for the MCP server. On a copy with PreTool and a hook type of shell, it flagged both. The lesson 5.11 linter checks the same things plus whether each script exists and is executable.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A developer asks Claude to "get the tests passing". Claude finds that the test suite can't connect to its database and decides the quickest fix is to refresh the migrations. Auto mode's classifier makes a judgment call on each action, and a destructive artisan command against a development database is not something you should count on it to catch. With the guard hook installed, the command is blocked with the message "this command can erase the database. Ask the user to run it themselves if it is really needed." Claude reports back that it needs the developer to decide, which is the right outcome. The rule that "Claude must never do this" was never a sentence in CLAUDE.md. It's an exit code.
Mistakes to avoid
- Writing a "never do X" rule in
CLAUDE.md and trusting it.
- Forgetting
chmod +x on a hook script.
- A hook that prints to stdout when you meant stderr, so Claude never sees the reason.
- Mixing exit 2 and JSON output in one hook.
- A slow
Stop hook that runs on every response.
- Trusting hooks as a security boundary. They're guard rails; use the sandbox for isolation.
- Forty hooks. Anthropic's advice is to keep the enforced set small, because each one fires wrongly sometimes and someone has to maintain it.
Security notes
Hooks execute arbitrary commands with your permissions, which is the point and also the risk. A hook defined in a repository runs on your machine, so review .claude/settings.json before trusting a cloned project. Never put secrets in hook commands. Treat managed settings as the only place for a policy that individuals mustn't override. And remember that bypassPermissions skips permission prompts, so use it only inside a throwaway container.
Cost and speed
Hooks that run on every tool call add latency, so keep them quick, and use matchers so they only fire for the tools they care about. They add no model tokens unless they print output that Claude reads, such as a blocking message.
Key takeaways
- Permissions decide what runs without asking: modes, plus allow, ask and deny rules evaluated deny first.
- Deny rules and
PreToolUse hooks hold in every mode; use them for rules that can't have exceptions.
- A hook reads JSON on stdin; exit 0 means no objection, exit 2 blocks and sends stderr to Claude.
- Test every hook with real inputs, including the near-misses, and treat hooks as guard rails, not a sandbox.
Lesson recap: the path a tool call takes, and which controls never bend.
Quick quiz
- In what order are allow, ask and deny rules evaluated?
- Which exit code makes a
PreToolUse hook block a tool call, and where does the reason go?
- Does exit 0 from a
PreToolUse hook approve the tool call?
- Why put a secret-protecting rule in
deny instead of CLAUDE.md?
- Why did the protect-files hook compare exact file names instead of using a substring match?
Answers and explanations
- Deny first, then ask, then allow. The first match wins, so an allow rule can't carve an exception out of a deny.
- Exit code 2. The message written to stderr is sent back to Claude as feedback.
- No. Exit 0 means "no objection"; the normal permission flow still decides.
- Deny rules are enforced by Claude Code in every permission mode.
CLAUDE.md is only context that Claude may not follow.
- A substring match on
.env also blocked .env.example, which developers legitimately edit.
Official references and further reading
Related tutorials