Sub topic 5
Scoping a Hook with Matchers
This chapter assumes you can read and write JSON, write a short Python script, and use a shell. It also assumes you know that an agent calls tools such as a shell command runner or a file editor. Earlier chapters covered the hook contract: the agent sends an event as JSON on stdin, and the hook answers with an exit code and a message. Here you will learn how to run a hook only for the tool calls it cares about.
Why scope a hook
A hook with no scope runs before every tool call. That includes reads of harmless files, searches, and web fetches. Each run costs time, and each run is another chance for a bug to block something that should have been allowed.
A command-checking hook only makes sense for shell commands. If it receives a file-write event, it may not find a command field, and a fail-closed hook would then block a legitimate edit. Scoping avoids that mismatch. You decide which tools a hook sees, and the agent skips the hook for every other tool.
Scoping gives you three benefits:
- Speed. A hook that never starts costs nothing.
- Fewer false blocks. A shell check never sees file edits.
- Clarity. Reading the configuration tells you which rule guards which tool.
What a matcher is
A matcher is a filter in the agent's hook configuration. It names the tools a hook applies to. The agent compares the matcher with the tool name of each proposed call. If they match, it runs the hook. If not, it moves on.
The exact syntax differs between agents, so check the documentation for yours. Two common forms are:
- An exact tool name, such as
shellorBash. - A pattern that can match several names, such as
write|edit, or a wildcard such as*for all tools.
The configuration below shows the general shape. The field names are illustrative. Your agent's file will use its own keys.
{
"hooks": {
"preToolUse": [
{
"matcher": "shell",
"command": "python3 guard_shell.py"
},
{
"matcher": "write|edit",
"command": "python3 guard_paths.py"
}
]
}
}In this setup, guard_shell.py sees only shell calls, and guard_paths.py sees only file writes and edits.
Matching on tool names
Tool names vary by agent. One agent calls its command tool Bash, another calls it shell, and another uses execute_bash. File tools may be named Write, Edit, fs_write, or something else. Before you write a matcher, find the real names. Two ways to do this:
- Read the agent's documentation for its list of built-in tools.
- Add a temporary hook with a broad matcher that logs the
tool_namefield of every event, then run a short session.
Matching is often case-sensitive. A matcher of bash may not match Bash. If a hook never seems to run, a wrong tool name or case is the first thing to check.
Tools provided by external servers, such as MCP servers, usually have longer names that include a server prefix. A matcher meant for one of those tools needs the full name, or a pattern that covers the prefix. Check how your agent writes these names before you rely on a pattern.
Two layers of scoping
The matcher is the first filter, and it is coarse: it looks at the tool name only. The hook script is the second filter, and it can look at anything in the event.
Use both. The matcher keeps irrelevant calls away from the script. The script then makes a fine-grained decision about the calls that reach it. A script can also verify the tool name itself, so it stays correct if someone later changes the configuration.
#!/usr/bin/env python3
import json
import sys
EXPECTED_TOOLS = {"shell"}
try:
event = json.load(sys.stdin)
tool_name = event["tool_name"]
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the tool call, so it was not allowed.", file=sys.stderr)
sys.exit(2)
if tool_name not in EXPECTED_TOOLS:
# The matcher should have kept this call away. Allow it, because
# this script has no rule for other tools.
sys.exit(0)
if "git push" in command and "--force" in command:
print("Blocked: force pushes are not allowed. Use a normal push.", file=sys.stderr)
sys.exit(2)
sys.exit(0)Notice the order. The script parses the event with a fail-closed try block first. It then checks the tool name. A call for an unexpected tool gets exit code 0, because this script has no rule for it and another hook or permission layer should handle it. That is a deliberate choice, and it differs from failing closed on unreadable input.
Choosing between one hook and several
You can write one hook with a broad matcher and branch inside the script, or write several hooks with narrow matchers.
| Approach | Strengths | Weaknesses |
|---|---|---|
| One broad hook that branches on tool name | One file, shared helpers, one log | Starts for every call, grows large, one bug affects all tools |
| Several narrow hooks, one per tool | Small scripts, easy to test, failures stay local | More configuration, repeated parsing code |
For most projects, narrow hooks are easier to maintain. Put shared code, such as the event parser and the path normalizer, in a small module that each script imports.
Common mistakes with matchers
A matcher that is too narrow
You write shell, but the agent has a second tool that also runs commands, such as a background task runner or a code interpreter that can call subprocess. The hook never sees those calls. List every tool that can run commands or change files, and cover each one. This is a coverage gap, and it is one of the main ways a guard silently stops guarding.
A matcher that is too wide
A wildcard sends every tool to a script that expects a command field. With fail-closed parsing, the script blocks each call that lacks one, including harmless reads. The agent then appears broken. Either narrow the matcher or have the script allow tools it has no rule for, as in the example above.
Pattern syntax surprises
Some agents treat the matcher as a regular expression and others treat it as a glob. In a regular expression, write can match any name that contains write, which includes names you did not intend. Anchor the pattern if your agent supports it, for example ^(write|edit)$. Test the pattern against real tool names.
Assuming the matcher is security
The matcher decides when a hook runs. It does not decide whether an action is safe. If a tool is renamed in an update, or a new tool is added, your matcher may stop covering it. Review the tool list when you upgrade the agent.
Verifying your matchers
Test the script as shown in the testing chapter, by piping sample events into it. Also test the matcher, which the script test cannot cover. Start a session with the real agent, ask it to perform one action per tool, and confirm that the right hook ran each time. A temporary log line at the top of each script makes this easy.
echo '{"tool_name":"shell","tool_input":{"command":"git push --force"}}' | python3 guard_shell.py
echo "exit code: $?"
echo '{"tool_name":"read","tool_input":{"path":"README.md"}}' | python3 guard_shell.py
echo "exit code: $?"The first command should end with exit code 2. The second sends an event for a tool the script does not guard, and it should end with exit code 0 because the script has no rule for it. Because the script validates the fields it needs, the second event would fail closed if the script ran the command lookup before checking the tool name. That ordering matters, so check it in your own scripts.
Wait: in the script shown earlier, the lookup of command happens inside the try block before the tool-name check. The second event above has no command field, so that version exits with code 2. To allow unguarded tools, move the tool-name check before the field lookup:
#!/usr/bin/env python3
import json
import sys
try:
event = json.load(sys.stdin)
tool_name = event["tool_name"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the tool call, so it was not allowed.", file=sys.stderr)
sys.exit(2)
if tool_name != "shell":
sys.exit(0)
try:
command = event["tool_input"]["command"]
except (KeyError, TypeError):
print("Blocked: shell call had no command field.", file=sys.stderr)
sys.exit(2)
if "git push" in command and "--force" in command:
print("Blocked: force pushes are not allowed. Use a normal push.", file=sys.stderr)
sys.exit(2)
sys.exit(0)This version fails closed for a shell call that is malformed, and it allows other tools. Both behaviors are intended.
Summary of the decisions
- Use a matcher to send each tool to the hook built for it.
- Confirm real tool names and their case, including prefixed names from external servers.
- Let the script re-check the tool name and decide what to do with tools it does not own.
- Fail closed on malformed input for tools the script does guard.
- Audit coverage when the agent or its tool list changes.
Exercise
A hook has the matcher "*" and its script reads event["tool_input"]["command"] inside a fail-closed try block. After you install it, the agent can no longer read files. Why does this happen, and what are two ways to fix it?
Show answer
File-read events have no "command" field, so the lookup raises KeyError and the fail-closed block exits with code 2 for every read. Fix it by narrowing the matcher to the shell tool (for example "shell"), or by checking tool_name first and exiting 0 for tools the script does not guard, while still failing closed on malformed shell events.
Exercise
Your matcher is "shell", but the agent also has a tool named "run_background" that executes commands. What is the risk, and how would you find out which tool names the agent uses?
Show answer
Commands run through "runbackground" never reach your hook, so dangerous commands pass unchecked. To find the names, read the agent's tool documentation, or install a temporary logging-only hook with a broad matcher and record the toolname of each event during a test session. Then extend the matcher, for example to "shell|run_background".