Skip to content
mentoor

Topic 3 of 6 · 6 min read

Blocking risky tool calls with pre-tool hooks

Goal: Write the logic of a pre-tool hook that blocks edits to protected paths and destructive commands, and find the input that slips past a weak pattern.

A pre-tool hook is a gate: it reads what the agent is about to do and says yes or no in code, so a rule that must hold does not rely on the model's good behaviour.

Check yourself · 1 of 3

Why is a pre-tool hook stronger than a line in AGENTS.md saying "never edit .env"?

Choose one answer

Why it matters

Telling an agent "never edit .env" or "do not run rm -rf" works most of the time. Models can drop an instruction in a long session or reason their way around it. A PreToolUse hook does not negotiate. If the path or command matches, the call is refused. That is why protected files, migrations, production configs and destructive commands belong in hooks, not just in prose.

How to do it

  1. Register the hook on PreToolUse with a matcher: Edit|Write for files, Bash for commands.
  2. Read tool_input from standard input. For files it holds file_path. For commands it holds command.
  3. Normalise before you compare. Resolve the path to an absolute one, so ./src/../.env and .env are the same.
  4. Match against a deny list of paths and patterns.
  5. To block, exit with code 2 and write the reason to standard error. The reason goes back to the model, so say what to do instead: ".env is protected; ask the user to change it."

Before and after

Weak: a hook that blocks a command only when it contains the exact text rm -rf /. The agent runs rm -rf ./ from the home folder, or rm -r -f /, or find / -delete. All slip through.

Better: split the command into words, treat any rm with recursive and force flags as dangerous whatever the order, and allow it only when the target is inside a short list of safe folders such as ./build and ./node_modules. For anything unclear on a risky command: block and explain.

For paths, the weak version checks .env. The better one resolves the path and also blocks .env.local, .env.production and config/secrets.yml.

What goes wrong

  • A pattern that is too narrow. Test it with variants: different flag order, extra spaces, sudo, a command inside bash -c "...", a path with ...
  • A pattern that is too broad, such as blocking any command containing rm, so the agent cannot even run npm run format. People then disable the hook.
  • Relying on the hook as the only safeguard. A shell command can write a file in many ways. Keep the hook as one layer, next to permission rules and a sandbox.
  • A hook that crashes. Check what your harness does on a script error, and make the safe path the default.

Examples

Protect secrets and lockfiles

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

data = json.load(sys.stdin)
path = os.path.realpath(data.get("tool_input", {}).get("file_path", ""))
name = os.path.basename(path)

if name.startswith(".env") or name == "package-lock.json":
    print(f"{name} is protected. Ask the user to change it.", file=sys.stderr)
    sys.exit(2)

realpath removes .. tricks. The message tells the agent what to do next.

A pattern that slips

A hook blocks commands matching rm -rf. The agent runs rm -fr build ../ and rm --recursive --force ~/proj. Neither contains the literal text. Fix: split the command into words and check the flags as a set, whatever their order or spelling.

Key points

  • A pre-tool hook decides in code, so a rule that must always hold should live there and not only in a memory file.
  • Normalise paths and parse commands before matching, so .., flag order and spacing do not bypass the rule.
  • On a block, exit 2 and explain what to do instead, so the agent can change course.
  • Test a deny rule with variants that should be blocked and variants that should pass.
  • A hook is one layer; combine it with permission rules and sandboxing.

Common mistakes

  • Matching one exact string and calling the rule done.
  • Comparing the raw path without resolving .. or symlinks.
  • Making the rule so broad that people turn the hook off.
  • Treating one hook as complete protection against a shell that can do anything.

Check yourself · 2 of 3

A hook blocks commands containing the exact text rm -rf. Which command slips past it?

Choose one answer

Check yourself · 3 of 3

What should a blocking hook do when it denies a call?

Choose one answer

Practice items, not counted towards your mastery.

Start here