ysskrishna logoysskrishna

Chapter 8 of 9 · 3 min

Hooks: deterministic guardrails

Run your own command before or after the agent acts. Block dangerous commands, format every edit, and notify yourself when a long task stops.

Prompts are probabilistic. Hooks are not. A hook is a command the host runs at a fixed point in the agent loop, with details about what is happening passed in as JSON. Your command can allow the action, block it with a reason, or do something extra, such as formatting a file.

Use hooks for rules that must hold every time. If you would be upset when the agent breaks a rule "just once", that rule belongs in a hook.

Claude Code hook events

EventFiresTypical use
PreToolUseBefore a tool runsBlock risky shell commands or protected file writes
PostToolUseAfter a tool succeedsFormat or lint the file that was just edited
UserPromptSubmitWhen you send a promptAdd context, or reject prompts containing secrets
NotificationWhen Claude Code wants your attentionDesktop notification
Stop / SubagentStopWhen the agent or a subagent finishesRun tests, send a "done" ping
SessionStartWhen a session startsLoad project context
PreCompactBefore context is compactedSave notes

Hooks are configured in settings files: ~/.claude/settings.json (user), .claude/settings.json (project, committed) or .claude/settings.local.json (project, not committed). Run /hooks in Claude Code to view and edit them.

How a hook decides

Claude Code sends JSON on the hook's stdin, including tool_name and tool_input for tool events. Your command's exit code decides what happens:

  • Exit 0: allow. Output may be shown in the transcript.
  • Exit 2: block. Whatever you print to stderr is fed back to the model as the reason, so it can adapt.
  • Other non-zero: a hook error, shown to you; the action continues.

For finer control a hook can print a JSON decision on stdout instead.

Example 1: block force-pushes and recursive deletes

.claude/hooks/guard-bash.sh:

#!/usr/bin/env bash
# Reads the PreToolUse payload and blocks two dangerous patterns.
cmd=$(jq -r '.tool_input.command // ""')
if echo "$cmd" | grep -Eq 'git push .*(--force|-f)( |$)'; then
  echo "Force-push is blocked by a project hook. Push normally or ask the user." >&2
  exit 2
fi
if echo "$cmd" | grep -Eq 'rm -rf (/|~|\.)( |$)'; then
  echo "Recursive delete of a root, home or repo folder is blocked." >&2
  exit 2
fi
exit 0

.claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/guard-bash.sh" }
        ]
      }
    ]
  }
}

matcher selects which tool the hook applies to. Bash matches shell commands; Edit|Write would match file edits.

Example 2: format every edited file

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "jq -r '.tool_input.file_path' | xargs -I{} npx prettier --write {}" }
        ]
      }
    ]
  }
}

The agent no longer needs "remember to run prettier" in any prompt or skill. It happens every time.

Step by step: install and test the guard

  1. Save guard-bash.sh, then chmod +x .claude/hooks/guard-bash.sh. Install jq if you do not have it.
  2. Add the PreToolUse block to .claude/settings.json.
  3. Start a new Claude Code session and run /hooks to confirm it is registered.
  4. Ask: "Force-push this branch."
  5. Expected: the Bash call is blocked and the agent reports the reason from your stderr message. Then ask for a normal git status and confirm it still runs.

Hooks in Cursor

Cursor has its own hooks, configured in a hooks.json (project .cursor/hooks.json or user ~/.cursor/hooks.json), with events such as before a shell command, before an MCP call, after a file edit, and when the agent stops. Your script reads JSON on stdin and replies with JSON (for example, to deny a command).

The design rules are the same in both hosts.

Rules for good hooks

  • Fast. Hooks run on every matching event. Keep them under a second.
  • Specific error messages. On block, say what was blocked and what to do instead. The model reads it.
  • Fail safe. If your script cannot parse its input, decide deliberately whether to allow or block.
  • Committed and reviewed. Project hooks run code on every teammate's machine. Review them like any other script.

Quick check

  1. Which exit code blocks the action in Claude Code, and where does the reason go?Exit code 2. Text printed to stderr is fed back to the model.

  2. You want lint to run after every edit. Which event?PostToolUse with a matcher for the edit/write tools.

  3. Why is "never push to main" better as a hook than in a skill?A hook enforces it every time; a skill only asks the model to comply.

Continue exploring

Productnpm+3Thinking Methods

Thinking Methods

17 well-known thinking methods your AI coding assistant can actually run.
Agent Skills
AI Apps & Assistants
Bash
Gemini
BlogCover image for 17 Thinking Skills for AI Agents: Pre-Mortem, Five Whys, Six Hats and More

17 Thinking Skills for AI Agents: Pre-Mortem, Five Whys, Six Hats and More

AI Apps & Assistants
Agent Skills
4 min read
ToolCover image for AI Token Counter

AI Token Counter

AI token counter with model pricing and context-window comparison in your browser.

Chat & AI
AI Apps & Assistants
+1
Productskills.sh+1Claude Code Subagents for Cursor

Claude Code Subagents for Cursor

Your Cursor subagents can finally run on the model you picked in each agent file.
Chat & AI
Agent Skills
AI Apps & Assistants
Bash
CourseCover image for Prompt Engineering for Coding Agents

Prompt Engineering for Coding Agents

Write prompts that coding agents act on: clear goals, the right context, output contracts, examples, structured thinking, shorter answers and a tiny eval set.

Agent Skills
Chat & AI

8 chapters · 21 min

BlogCover image for How to Install Caveman in Cursor and Claude Code

How to Install Caveman in Cursor and Claude Code

AI Apps & Assistants
Agent Skills
+1
3 min read