All articles

Claude Code hooks: examples that block, with tests

In short. A PreToolUse hook can inspect a selected tool call before it runs. The example below uses exit 2 to stop a matching command. Empty successful output leaves the normal permission checks in place; failure behaviour also depends on configuration and platform. Test the rule, its gaps and its failure path.

Engineering drawing of a task card stopped at an inspection gate before a tool head: a metaphor for a PreToolUse check.
Illustrative mechanism: a configured PreToolUse check examines a matching tool call before execution. It is not a complete security boundary.

Claude Code hooks are commands that run at specific times: before a tool runs, after it runs, when you submit a prompt, or when the session ends. They turn “the agent shouldn’t do this” into a real check. In this article: Claude Code hooks examples that actually block, how to test each one, and the mistakes behind most “hook error” searches.

Everything below follows the official hooks reference and the permissions documentation, both checked again on 27 October 2026. We use hooks every day in our studio; one of ours is a Stop hook that warns when a session’s token use gets too high.

Where are Claude Code hooks configured?

Hooks live in settings files, and entries from several files are merged, not replaced:

File Applies to Shared
~/.claude/settings.json all your projects no
.claude/settings.json one project yes, can be committed
.claude/settings.local.json one project no

Plugins, skills and subagents can bring their own hooks too, and an organisation can set hooks in managed settings.

A hook entry has three parts: the event, a matcher group, and the handlers:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3",
            "args": [
              "${CLAUDE_PROJECT_DIR}/.claude/hooks/block_rm.py"
            ],
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

CLAUDE_PROJECT_DIR is the project’s root folder where the session started. On Windows, call Python the way your system expects.

How do you write a PreToolUse hook that blocks a risky command?

A PreToolUse hook receives the planned tool call as JSON on standard input and blocks it by exiting with code 2. The JSON holds tool_name, tool_input and a few session fields; for Bash, tool_input.command is the command text.

#!/usr/bin/env python3
import json, re, sys

data = json.load(sys.stdin)
cmd = data.get("tool_input", {}).get("command", "")

if re.search(r"\brm\s+-\w*(rf|fr)\w*\b", cmd):
    print("Blocked: recursive force delete. Ask the user to run it.", file=sys.stderr)
    sys.exit(2)
sys.exit(0)

For this example, exit 2 stops the matched call. Exit 0 without a decision is not blanket permission; normal permission checks still apply. Do not interpret an exception or a timeout as a deliberate allow.

A text pattern catches the common form of a command, not every form: this one stops rm -rf and rm -fr, but rm -r -f with separate flags gets through. That’s why each rule needs tests, and why permission rules and the sandbox exist alongside hooks.

If you prefer structured output, a hook can exit 0 and print JSON with hookSpecificOutput, where hookEventName is PreToolUse and permissionDecision is allow, deny, ask, or defer, with a permissionDecisionReason.

How does the PreToolUse matcher work?

The matcher filters by the tool name, and the rules are short:

  • Bash, or a list like Edit|Write: exact names.
  • Anything with other characters is a regular expression, unanchored: ^Notebook, mcp__memory__.*.
  • MCP tools are named mcp__<server>__<tool>. A matcher of mcp__memory alone matches nothing; you need mcp__memory__.*.
  • *, an empty string, or no matcher means every tool.

There’s also an if field that uses permission-rule syntax, like Bash(git *). It holds a single rule, with no && or ||, and the documentation calls it best-effort: for a hard allow or deny, use the permission system.

Two drawn test tracks for the same rule, one with a stopped card and cross, the other with a passed card and checkmark.
Test both outcomes: a call the rule should stop and an ordinary call it should not reject. This is a drawn metaphor, not a live test result.

How do you test a hook before you trust it?

Feed the hook the same JSON Claude Code would send and check the exit code: one call that must be blocked and one that must pass. A hook you never tested is a hook you hope works.

echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}' | python3 .claude/hooks/block_rm.py; echo "exit $?"   # expect 2
echo '{"tool_name":"Bash","tool_input":{"command":"ls build"}}'    | python3 .claude/hooks/block_rm.py; echo "exit $?"   # expect 0

Our rule for every hook: the test file always holds one action to stop and one to let through. The second test catches another common failure: a pattern so broad it blocks normal work. Add a third case for the form you know the rule misses, such as rm -r -f, so the gap is written down instead of forgotten.

Why does a PreToolUse hook not stop anything?

Outcome Meaning for PreToolUse
Exit 0, empty output No decision; normal permission checks continue
Exit 2 Rejects this tool call; stderr explains why
Exit 0, valid JSON deny Rejects the tool call
Other error or timeout Depends on onFailure, installed version and shell; test the failure path
onFailure: block (supported versions) A failed handler blocks this event; not a blanket rule for all hook events

Claude Code hooks reference.

Hooks, permission rules and skills: which one does what?

Permission rules decide what is allowed, hooks add your own logic before a call, and skills only guide the agent.

  • Permission rules (allow, ask, deny in settings.json) are checked in that order: deny, then ask, then allow. A deny rule is applied even when a PreToolUse hook returns allow, and a matching ask rule still prompts.
  • A blocking hook (exit 2) stops the call before the permission prompt.
  • Skills are instructions and resources the agent loads when needed. They guide; they do not enforce. Our article on agents and skills explains the difference.

For confidential folders, start with deny rules like Read(./secrets/**). Know their limit: they cover the built-in file tools and commands like cat, head, and tail, but not grep -r run from the folder, or a script that opens files itself. A PreToolUse hook can inspect the full command text for those cases, and for enforcement at the operating-system level the documentation points to the sandbox.

Which hook events are worth using first?

Start with the few that solve a daily problem, and leave the rest of the reference for later. The reference lists more than thirty events; four cover most small setups:

  • PreToolUse runs before a tool call and can block it. This is the one for risky commands, protected files and unwanted network calls.
  • PostToolUse runs after a tool call. It suits checks on the result, such as running a formatter or a quick test after a file is edited.
  • UserPromptSubmit runs when you send a prompt, which makes it the place to add context or refuse a prompt before the model sees it.
  • Stop runs when Claude finishes answering. Ours uses it as a gauge: it warns us when a session has used too many tokens, so we start a fresh one instead of paying for a long history.

Add one hook at a time and test it before the next. A pile of untested hooks is harder to debug than a missing one: you stop knowing which of them changed the result.

When are hooks not enough?

This regular expression checks a command string, not what the command will do. It misses alternate forms and may reject quoted examples. It does not protect every filesystem or network path. A script error or timeout is not a policy decision: test onFailure with your installed version and shell, including Windows differences.

For stronger protection, combine appropriate permissions, isolation and restricted credentials. Review the hook code before enabling it, and test only harmless commands in a disposable workspace. The article tests the Python decision script, not a live Claude Code installation.

How can we help with Claude Code hooks?

If your agent setup grew fast and you’re not sure which rules actually hold, we map the agents, write the hook rules with tests from 150 € and show the test run, not just the config. Our article on MCP server setup covers the other side, the tools your agent can reach. You can see how our own system is put together on the work page. Describe your setup in a few lines: we reply in writing within 48 hours with a proposal and a price.

What this example actually tests

These checks send command strings to the Python script as JSON. They do not execute those commands or install a hook. They check the script’s exit code, not integration with Claude Code, its permission system or a sandbox.

Test rm -rf and rm -fr as blocked, and ls or git status as not rejected by this script. Also test the known gap rm -r -f and the false positive echo “rm -rf”. A crash on invalid JSON is a failure, not an intentional policy decision. Record expected and actual outcomes.

Check the installed Claude Code version and shell before relying on failure behaviour, especially Windows without Git Bash. The official reference describes onFailure and platform-specific exceptions. Test the actual configuration in a disposable folder, not on production data.

Questions

Why does my PreToolUse hook not block anything?

Check the matcher, output and failure settings. Exit 2 can block PreToolUse; a valid JSON deny can also block. Empty exit 0 leaves normal permission checks. Errors and timeouts depend on onFailure and the platform.

Do I need hooks if I already have permission deny rules?

For simple rules, deny rules come first: they are checked even when a hook returns allow. Hooks are for logic a pattern cannot express, such as inspecting the whole command text before it runs.

Do Read deny rules stop cat and grep in Bash?

They cover the built-in file tools and file commands Claude Code recognises in Bash, such as cat, head and tail. They do not cover a command that reads files without naming them, like grep -r from the folder, or a script that opens files itself. For that, the documentation points to the sandbox.

Where do Claude Code hooks live?

In settings files: ~/.claude/settings.json for all your projects, .claude/settings.json for one project and your team, or .claude/settings.local.json for you only. Entries from several files are merged.

Contact

One person reads this inbox — the same person who builds what you order.

Describe your task

Tell us what you have and what result you need — even a single small task. No brief required: within 48 hours you get a plan and a price in writing, a question, or an honest “not a fit”.

Include the situation, files or links, deadline, language, privacy limits and budget boundary if you have one.

File (optional)
No file chosen

A brief, a photo, a spreadsheet — whatever explains the task faster than words. Up to 8 MB, stored with our hosting provider. Please don't send sensitive personal or medical documents through the site.

Sending creates no order and no payment. We reply within 48 hours. Prefer email? contact@castel.studio

Talk to us

Prefer a call or a messenger? Write or call — the studio's founder answers.

Connect on LinkedIn

Prefer a freelance platform?

Order the same work there, with the platform's secure payment.

A one-person AI studio in Nice. Whoever answers your message is the one who does the work — no account managers in between. Files are processed on our own machine, not in someone else's cloud.

Nice 06100, France · Open in maps →

SIREN 103 115 705