Claude Code Setup Playbook — 3 · Hooks
CP — 04

Step 3. Add a hook for rules a deny list can't express

Builds on step 2. Deny rules match text. Some rules need logic: "block merges, but only on protected branches", or "block SQL that changes the schema, but allow SELECT".

Read time2 min
SectionClaude Code Setup Playbook
01 — 3 · hooks

What to do

Why: a hook is a script. It gets the tool call as JSON on stdin and can refuse it with a message the agent reads and acts on.

Do this:

  1. Pick the one or two mistakes that have cost you the most. Start with those.
  2. Write a small script for each. Exit code 2 blocks the call, and whatever you print to stderr goes back to the agent.
  3. Register it in .claude/settings.json. Hooks work only when registered there, in settings.local.json, in a plugin, or in skill or subagent frontmatter.
  4. Keep the timeout short. A slow hook gets disabled.
02 — 3 · hooks

Example

Example. Block direct schema changes through psql and point to migrations instead.

.claude/hooks/block-ddl.js:

js
let raw = "";
process.stdin.on("data", (chunk) => (raw += chunk));
process.stdin.on("end", () => {
  const command = JSON.parse(raw).tool_input?.command ?? "";
  const touchesDb = /\bpsql\b/i.test(command);
  const changesSchema = /\b(ALTER|CREATE|DROP)\s+(TABLE|INDEX|TYPE)\b/i.test(command);

  if (touchesDb && changesSchema) {
    console.error(
      "Blocked: schema changes must go through migrations. " +
      "Edit the schema file, then run `npm run db:generate`."
    );
    process.exit(2);
  }
});

Register it in .claude/settings.json:

json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "node .claude/hooks/block-ddl.js", "timeout": 5 }
        ]
      }
    ]
  }
}
03 — 3 · hooks

Check it works

Check in two stages. First, test the script alone:

bash
echo '{"tool_input":{"command":"psql $DB -c \"DROP TABLE users\""}}' | node .claude/hooks/block-ddl.js
echo $?   # expect 2, with the message on screen

Then test it through the real agent. Ask Claude to run that command and confirm it gets refused. Run /hooks to see what is registered. A hook that exists as a file but isn't registered does nothing, and nobody notices.

Other events worth knowing:

  • PostToolUse runs after a call. Good for recording evidence or running a formatter.
  • UserPromptSubmit runs when you send a prompt.
  • Stop runs when the agent tries to finish. Step 8 uses it.

Watch out:

  • Regex rules produce false positives. The example above would also block an echo that mentions DROP TABLE. Decide how much that matters.
  • Decide what happens when the hook crashes. Failing open is fine for style checks and wrong for security checks.
  • Don't spawn a package manager on every call. node script.js is faster than npm run script.