Task statement 7.3 · Security and safety

7.3 · Claude Hooks

In Shelfwise, the course example, the service's one tool only reads stock, but the engineers' Claude Code sessions run shell commands in the repository, where a push to main would skip the pull request every change must pass. The guardrail that stops such a destructive action before it runs is a hook.

Why it's tested

The tempting place for a guard is a PermissionRequest hook, because stopping a command feels like a permission decision. That event runs only when a call would need a permission prompt, so a command that an allow rule or the permission mode already approved never reaches it. Exit code 2 is not honoured there either. A PostToolUse hook fails the other way, because it runs after the tool has returned.

KnowledgeHow a hook blocks a tool call

Claude Code reads hooks from settings files. Each names an event, a matcher that filters by tool name, such as Bash or Edit|Write, and a handler, usually a shell command. PreToolUse (1.2) passes the handler JSON on stdin with tool_name and tool_input, such as the full command. The handler blocks the call by exiting with code 2 (Claude Code then shows its stderr to Claude as the reason), or by exiting 0 and printing JSON with permissionDecision: "deny" and a permissionDecisionReason. Claude reads the reason, so it can take another route instead of retrying:

  1. Claude asks to run git push origin main, which has not run yet.
  2. PreToolUse starts, and the matcher Bash selects python hooks/guard_bash.py.
  3. The script reads the command from stdin and finds a push to main.
  4. It writes a reason to stderr and exits 2, so the call is blocked before any permission rule.
  5. Claude reads the reason and pushes a branch for a pull request instead.

Interactive · one Bash call, four things the hook can return

One Bash call read from top to bottom. Claude calls Bash with git push origin main, which has not run yet. PreToolUse starts and the matcher Bash runs hooks/guard_bash.py, which reads the command on stdin. On exit 2 or a JSON deny, the path turns left to Blocked: the call never runs and the reason goes to Claude. On exit 0, exit 1 or a JSON allow, the path continues down to the permission rules and mode, where deny and ask rules are still checked, and then to the outcome: the command runs or prompts, and here an engineer's allow rule, Bash git push, approves it. Claude calls Bash git push origin main · NOT RUN YET PRETOOLUSE · MATCHER Bash hooks/guard_bash.py READS THE COMMAND ON STDIN EXIT 2 · JSON DENY Blocked CALL NEVER RUNS REASON GOES TO CLAUDE EXIT 0 · EXIT 1 · JSON ALLOW Permission rules and mode DENY AND ASK RULES STILL CHECKED JSON ALLOW SKIPS ONLY THE PROMPT Runs, or prompts HERE: THE ENGINEER'S ALLOW RULE Bash(git push *) APPROVES IT Time runs downward. No rule here denies the push, so only the hook can stop it.

Choose what guard_bash.py returns for git push origin main.

Exit 2: Claude Code blocks the call before any permission rule is read, and Claude gets the script's stderr as the reason. The push never runs, although the engineer's allow rule would have approved it.

JSON deny: the script exits 0 and prints permissionDecision "deny" with a permissionDecisionReason. The call is blocked the same way, and Claude reads the reason.

Exit 1: a non-blocking error. The transcript shows a hook error notice, the call goes on to the permission rules, and the allow rule Bash(git push *) approves the push. This was the draft guard's bug.

JSON allow: the hook skips only the permission prompt. Deny and ask rules are still checked, and none matches this push, so it runs. A guard returns allow only for calls it means to approve.

Green: the call stops before it runs. Amber: the push goes ahead, after exit 1 or a JSON allow alike.

Any other exit code without valid JSON is a non-blocking error: the transcript shows a hook error notice and the call continues through the normal permission flow. Exit 0 with no output is no decision, not approval. A JSON "ask" forces a prompt and "allow" skips it, but deny and ask rules are evaluated whatever the hook returns. So a hook can tighten permissions but never loosen them, and its block holds in every mode, bypassPermissions included.

KnowledgeClaude Code hooks and Agent SDK hooks

Both layers share the core events, such as PreToolUse, and the same decision fields, but they live in different places. Claude Code hooks come from any settings level, plugins and managed settings, and the levels merge rather than replace each other. Matching hooks run in parallel, and if their PreToolUse decisions differ, deny beats defer, ask and allow. An administrator can set allowManagedHooksOnly in managed settings to block user, project, local and plugin hooks. Agent SDK hooks are HookMatcher callbacks in the agent's options (1.2), run in your own process. For a guardrail, the difference that matters is the timeout:

Settings files

Claude Code hooks

A shell command, HTTP endpoint or MCP tool, with a timeout per handler.

Timed out: no decision, so the call continues.

Agent options

Agent SDK hooks

A callback in ClaudeAgentOptions.hooks, with a timeout per HookMatcher.

Timed out: the call does not run, and Claude is told the hook did not respond.

KnowledgeWhat a hook cannot do

A hook is a guardrail on what Claude tries, not a sandbox around what a command can reach. It sees only the call's text, so a check for the string git push misses git -C . push origin main. Command hooks also run with your full user permissions, outside the Bash sandbox. In a -p or Agent SDK session the folder counts as trusted, so a repository's committed hooks run without the trust dialog. For a repository you did not write, start with --bare, which reads no hooks from the project, or pass --settings '{"disableAllHooks": true}' rather than user settings, which the project's settings can override. 7.2 covers layering a hook with other controls.

SkillWorked example: the guard that printed "Blocked" and let the push run

The engineers committed a guard so that no Claude Code session pushes to main. One engineer's ~/.claude/settings.json allows Bash(git push *), so branch pushes need no prompt. They tested the guard in a scratch clone whose remote was a local bare repository:

"PreToolUse": [{"matcher": "Bash",
  "hooks": [{"type": "command", "command": "python hooks/guard_bash.py"}]}]
# draft, on "git push origin main": print("Blocked", file=sys.stderr); sys.exit(1)
PreToolUse hook error: Failed with non-blocking status code: Blocked → push ran
# fix: sys.exit(2) # stderr: "Push to main blocked. Push a branch for a pull request."
call blocked; Claude pushes a branch instead

The cause was the exit code. Exit 1 is a non-blocking error, so Claude Code showed a notice and passed the call on, and the engineer's allow rule approved it. Exit 2 blocks before the rules are read, and Claude takes the stderr line as its reason. The service needs no such guard, because tools=[] gives Claude no Bash there. A guard in the service would be an Agent SDK callback, because setting_sources=[] never loads the settings file.

More precise than the guide. The docs have no feature named "Claude Hooks" (as of 2026-10-05). They document Claude Code hooks, set in settings files, and Agent SDK hooks, passed as callbacks, with shared events such as PreToolUse and the same decision format. Exam answer: Claude Hooks means either layer, code that runs at a lifecycle event such as PreToolUse and can block a tool call before it runs.

Ask one question: must this action be stopped every time, before it runs, whatever Claude or the permission mode decides? Yes → a PreToolUse hook in the layer that runs the tool, blocking with exit 2 or a JSON deny and a reason. No, a person should judge each case → an ask rule or a can_use_tool approval (8.1).
Takeaway
  • A Claude Code PreToolUse hook blocks only with exit code 2 or JSON permissionDecision: "deny"; exit 1 lets the call go ahead.
  • A hook tightens permissions but cannot loosen them: its deny holds in bypassPermissions, and its allow still meets deny and ask rules.
  • A hook reads the call's text and runs with your permissions, so it is a guardrail, not a sandbox.

check yourself

0 / 3 answered

An engineer's Claude Code settings allow Bash(terraform *) without a prompt. A PreToolUse command hook, matcher Bash and timeout 15, checks each command against the wiki's change-freeze calendar and denies terraform destroy in a freeze. While the wiki was down, terraform destroy ran in a freeze. The debug log shows the hook cancelled at 15 seconds, then the command starting.What is the most likely root cause?

Select one.

A data team's TypeScript Agent SDK agent maintains a warehouse through one MCP tool, mcp__wh__run_sql, which it also uses for SELECT queries. Operators sometimes switch long unattended runs to bypassPermissions. Security requires that no DROP or TRUNCATE statement ever runs, in any permission mode, and that Claude learns why so it can report the request.Which approach best meets the security requirement while keeping SELECT queries working?

Select one.

An open-source project runs claude -p in CI to review each contributor's pull request, on the pull request's own checkout. A pull request could add a hook to .claude/settings.json, and hooks run with the job's own permissions. The maintainers want no hook from a pull request to run, whatever that pull request's settings files say.Which TWO changes most directly meet the maintainers' requirement?

Select two.

sources

  1. Claude Code Docs, "Hooks reference": events, matcher patterns, hook locations, merging, decision precedence and allowManagedHooksOnly; exit code 2 blocks PreToolUse and its stderr becomes the reason; other exit codes are non-blocking errors; PermissionRequest ignores exit 2; PreToolUse permissionDecision, with deny and ask rules "still evaluated regardless"; timeouts by hook family; full user permissions; workspace trust in -p and SDK sessions; disableAllHooks. Checked 2026-10-05.
  2. Claude Code Docs, "Automate actions with hooks": blocking edits to protected files with exit 2; PostToolUse cannot undo actions; PreToolUse hooks run before any permission-mode check and a deny holds in bypassPermissions; hooks "can tighten restrictions but not loosen them". Checked 2026-10-05.
  3. Claude Code Docs, "Configure permissions": a blocking hook takes precedence over allow rules; what a Bash rule does not match (git -C . push origin main); --bare and --settings for repositories you did not write. Checked 2026-10-05.
  4. Claude Code Docs, "Intercept and control agent behavior with hooks" and "Configure permissions": HookMatcher callbacks and their timeout; a timed-out PreToolUse callback means the tool call does not run; hooks run first, and a hook allow does not skip deny and ask rules. Checked 2026-10-05.
  5. Claude Code Docs, "Configure the sandboxed Bash tool": the sandbox covers shell commands only, and hooks run outside it with full access. Checked 2026-10-05.
  6. The guard, hooks/guard_bash.py, the engineer's allow rule and the scratch-clone test are this course's additions to Shelfwise.