Lesson 44.2 · 2 of 4 · 7 min read · Reviewed 24 Nov 2026
PreToolUse: block or modify a call
By the end, you can
- Write a PreToolUse hook that denies a dangerous call.
- Explain allow, deny and ask decisions and when to edit a tool's input.
PreToolUsePreToolUse hook: A hook that runs before a tool call and can allow, deny or ask for approval. is the most useful hookHook: Code that runs automatically at a lifecycle event, such as before or after a tool call, to check, block or log it. because it fires before side effects.
In the Agent SDK
A hook is a function. It gets the tool name and input, and returns a decision:
const blockProdDb = async (input) => {
if (input.tool_name === 'Bash' && /prod-db/.test(input.tool_input.command)) {
return { hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'deny',
permissionDecisionReason: 'Production database is off limits. Use the staging copy.',
} };
}
return {}; // no opinion: normal permissions apply
};
// options: { hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [blockProdDb] }] } }
In Claude Code
A command hook is any script. Claude CodeClaude Code: Anthropic’s agentic coding tool that works in your terminal, IDE and CI, reading and editing code and running commands. sends the event as JSON on stdin. Exit 0 lets the call go ahead; exit 2 blocks it and whatever you wrote to stderr is shown to Claude. The matcher in settings.json picks which tools the hook watches.
The three decisions
- allow skips the permission prompt. Use it for calls you’ve already checked are safe.
- deny blocks the call. Always give a reason, because the model uses it to pick a better path.
- ask sends the call to a person for approval (see 45.2).
Editing instead of blocking
Sometimes the fix is small: add --dry-run, point a path at the sandboxSandbox: An isolated environment that limits what code or an agent can reach, such as files, network or credentials., or strip a secret. A PreToolUse hook can return changed input, so the call goes ahead safely without a round trip to the model.
Key points
- PreToolUse runs before the tool, so it is the place to stop a bad call before anything happens.
- A hook can return allow, deny or ask, with a reason the model sees.
- In Claude Code a command hook reads JSON on stdin; exit code 2 blocks the call and sends stderr back to Claude.
Block and rewrite risky shell calls
Write a PreToolUse hook that denies, asks about or safely rewrites tool calls before they run.
You will have: A hook function and a printed table showing what happened to five tool calls.
Steps
- Run the starter: every call runs, including the production delete.
- Deny any Bash command that mentions prod-db, with a reason that tells the model what to do instead.
- Rewrite deploy calls to add --dry-run so they go ahead safely.
- Return ask for git push so a person approves it.
- Leave non-Bash tools and safe commands to normal permissions.
Done when
- The prod-db command is BLOCKED and its reason mentions staging.
- The deploy call shows REWRITE with --dry-run.
- git push shows ASK; pytest and the README read still RUN.
Open in the Playground No API key needed.
Starter code (Python)
# A PreToolUse hook sees every call before it runs. It can allow, deny, ask, or rewrite the input.
CALLS = [
{"tool": "Bash", "command": "pytest -q"},
{"tool": "Bash", "command": "psql prod-db -c 'DELETE FROM orders'"},
{"tool": "Bash", "command": "./deploy.sh staging"},
{"tool": "Read", "path": "README.md"},
{"tool": "Bash", "command": "git push origin main"},
]
def pre_tool_use(call):
"""Return {"decision": "allow" | "deny" | "ask" | "default", "reason": ..., "command": ...}."""
# TODO: deny any Bash command that mentions prod-db, with a reason that points to staging
# TODO: rewrite ./deploy.sh calls to add --dry-run (decision allow plus the new "command")
# TODO: ask a person before any git push
return {"decision": "default"}
def run(call):
out = pre_tool_use(dict(call))
target = call.get("command", call.get("path"))
d = out.get("decision", "default")
if d == "deny":
return f"BLOCKED {target} (model sees: {out.get('reason')})"
if d == "ask":
return f"ASK {target} (waiting for a person)"
if "command" in out and out["command"] != target:
return f"REWRITE {out['command']}"
return f"RUN {target}"
for c in CALLS:
print(run(c))
Show a solution
# A PreToolUse hook sees every call before it runs. It can allow, deny, ask, or rewrite the input.
CALLS = [
{"tool": "Bash", "command": "pytest -q"},
{"tool": "Bash", "command": "psql prod-db -c 'DELETE FROM orders'"},
{"tool": "Bash", "command": "./deploy.sh staging"},
{"tool": "Read", "path": "README.md"},
{"tool": "Bash", "command": "git push origin main"},
]
def pre_tool_use(call):
"""Return {"decision": "allow" | "deny" | "ask" | "default", "reason": ..., "command": ...}."""
if call["tool"] != "Bash":
return {"decision": "default"}
cmd = call["command"]
if "prod-db" in cmd:
return {"decision": "deny", "reason": "Production is off limits. Use staging-db instead."}
if cmd.startswith("./deploy.sh") and "--dry-run" not in cmd:
return {"decision": "allow", "command": cmd + " --dry-run"}
if cmd.startswith("git push"):
return {"decision": "ask", "reason": "Pushes are visible to the whole team."}
return {"decision": "default"}
def run(call):
out = pre_tool_use(dict(call))
target = call.get("command", call.get("path"))
d = out.get("decision", "default")
if d == "deny":
return f"BLOCKED {target} (model sees: {out.get('reason')})"
if d == "ask":
return f"ASK {target} (waiting for a person)"
if "command" in out and out["command"] != target:
return f"REWRITE {out['command']}"
return f"RUN {target}"
for c in CALLS:
print(run(c))
Do it Add a PreToolUse guard to the support agent in the Playground. No API key needed.