Workflow recipe
Set up guardrail hooks for your coding agent
Block dangerous commands in Claude Code with PreToolUse hooks and deny rules, so the agent cannot force-push, wipe files or edit secrets. Test them first.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
To block dangerous commands in Claude Code, decide what to block outright and what to ask about, write a PreToolUse hook that checks each shell command and another that guards sensitive files, and register both in .claude/settings.json with deny rules. Test them with commands that should be refused, then commit them so every session gets the same rules.
Coding agents ask permission before running commands, and after the fiftieth harmless npm test people stop reading the prompts. Sooner or later someone approves git reset --hard on a branch with an afternoon of uncommitted work, or switches to a mode that skips prompts altogether.
Hooks put a few hard rules underneath the prompts. A PreToolUse hook runs before every tool call, sees the exact command or file path, and can deny it, ask a person, or let normal permissions decide. The rules live in the repository, so everyone on the team and every session gets them. This recipe sets up two hooks and a set of deny rules in Claude Code, tests them, and explains what they do not protect against.
EditorAbout 10 min
1. Decide what to block and what to ask about
Write the list down before writing code. Keep it short: every rule you add is a rule someone will want to bypass on a bad day.
| Decision | Examples | Why |
|---|---|---|
| Deny | rm -rf, git push --force, git reset --hard, git clean -f, git branch -D, curl ... | sh, DROP TABLE, terraform destroy |
Hard or impossible to undo |
| Deny edits | .env files, keys, .github/workflows/, the hook files themselves |
Secrets and the guardrails should only change by hand |
| Ask | git push, npm publish, sudo |
Fine when intended, costly when not |
Everything else goes through the normal permission prompts. A hook that returns no decision changes nothing.
EditorAbout 15 min
2. Write the command guard
Create .claude/hooks/guard-bash.sh. Claude Code sends the hook the tool call as JSON on standard input; the script reads tool_input.command, checks it against the lists and prints a decision.
#!/usr/bin/env bash
# PreToolUse hook for Bash: deny destructive commands, ask before risky ones.
set -euo pipefail
COMMAND=$(jq -r '.tool_input.command // ""')
decide() { # $1 = deny|ask, $2 = reason shown to Claude and logged
printf '%s\t%s\t%s\n' "$(date -u +%FT%TZ)" "$1" "$COMMAND" >> "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/guard.log"
jq -n --arg d "$1" --arg r "$2" \
'{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: $d, permissionDecisionReason: $r}}'
exit 0
}
# Never allowed from the agent.
DENY_PATTERNS=(
'rm[[:space:]]+(-[a-zA-Z]*[rR][a-zA-Z]*[fF]|-[a-zA-Z]*[fF][a-zA-Z]*[rR])'
'git[[:space:]]+push[^|;&]*(--force|[[:space:]]-f([[:space:]]|$)|--mirror|--delete)'
'git[[:space:]]+reset[[:space:]]+--hard'
'git[[:space:]]+clean[[:space:]]+-[a-zA-Z]*f'
'git[[:space:]]+branch[[:space:]]+-D'
'git[[:space:]]+(checkout|restore)[[:space:]]+(--[[:space:]]+)?\.([[:space:]]|$)'
'(curl|wget)[^|]*\|[[:space:]]*(sudo[[:space:]]+)?(ba|z)?sh'
'([Dd][Rr][Oo][Pp]|[Tt][Rr][Uu][Nn][Cc][Aa][Tt][Ee])[[:space:]]+([Tt][Aa][Bb][Ll][Ee]|[Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee]|[Ss][Cc][Hh][Ee][Mm][Aa])'
'terraform[[:space:]]+(destroy|apply[^|;&]*-auto-approve)'
'kubectl[[:space:]]+delete'
)
# Allowed, but a person confirms first.
ASK_PATTERNS=(
'git[[:space:]]+push'
'(npm|pnpm|yarn)[[:space:]]+publish'
'(^|[[:space:]])sudo[[:space:]]'
)
for p in "${DENY_PATTERNS[@]}"; do
if grep -qE -- "$p" <<<"$COMMAND"; then
decide deny "Blocked by the project guardrail: destructive command. Explain why it is needed and ask the user to run it."
fi
done
for p in "${ASK_PATTERNS[@]}"; do
if grep -qE -- "$p" <<<"$COMMAND"; then
decide ask "Guardrail: confirm before running this command."
fi
done
exit 0 # no decision: normal permission rules applyThe reason text goes back to Claude, so write it as an instruction: explain, and let the user run it. Without that, agents tend to try the same thing a different way. Add .claude/hooks/guard.log to .gitignore.
EditorAbout 10 min
3. Write the file guard
Create .claude/hooks/guard-files.sh for the Edit and Write tools, which send the target path as tool_input.file_path:
#!/usr/bin/env bash
# PreToolUse hook for Edit and Write: keep the agent out of secrets and CI config.
set -euo pipefail
FILE=$(jq -r '.tool_input.file_path // ""')
case "$FILE" in
*.env|*.env.*|*/secrets/*|*.pem|*.key)
REASON="Secrets files are off limits to the agent." ;;
*/.github/workflows/*|*/.claude/settings.json|*/.claude/hooks/*)
REASON="CI workflows and agent guardrails are changed by people only. Describe the change instead." ;;
*)
exit 0 ;;
esac
jq -n --arg r "$REASON" \
'{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}'Protecting the hook files and settings.json matters: an agent that can edit its own guardrails can remove them while “fixing” something else.
Make both scripts executable:
chmod +x .claude/hooks/guard-bash.sh .claude/hooks/guard-files.shEditorAbout 10 min
4. Register the hooks and add deny rules
Add both hooks to the project settings file, .claude/settings.json, which is committed and shared with the team. Add permission rules alongside them: deny rules cover reading secrets, which the file guard above does not, and they keep working if a hook script breaks.
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)",
"Bash(git push --force *)",
"Bash(git reset --hard *)"
],
"ask": [
"Bash(git push *)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-bash.sh", "args": [] }
]
},
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-files.sh", "args": [] }
]
}
]
}
}${CLAUDE_PROJECT_DIR} resolves to the project root, so the hooks work from any subdirectory. The empty args array runs the script directly without a shell, which Claude Code’s documentation recommends for hooks that use a path placeholder. A deny rule always wins over an allow rule, wherever the allow rule comes from.
TerminalAbout 10 min
5. Test the guards before trusting them
Hooks fail open: a script with a syntax error or a missing jq is reported as a hook error and the tool call goes ahead. So test them directly, the same way Claude Code calls them:
for cmd in "rm -rf build/" "git push --force origin main" "git push origin feature" "npm test"; do
out=$(jq -n --arg c "$cmd" '{tool_name: "Bash", tool_input: {command: $c}}' | .claude/hooks/guard-bash.sh)
printf '%-32s %s\n' "$cmd" "$(jq -r '.hookSpecificOutput.permissionDecision' <<<"${out:-null}")"
doneYou should see deny, deny, ask and null (no decision) for npm test. Then test inside Claude Code with a harmless prompt:
The reset and the .env edit should be blocked with your reason text, and the push should ask for confirmation. Check .claude/hooks/guard.log for the entries. Save the shell test as .claude/hooks/test-guards.sh and run it whenever you change a pattern.
GitHubAbout 5 min
6. Commit, explain and review together
Commit .claude/settings.json and the scripts in one pull request, with the table from step 1 in the description so reviewers can see the intent. Add a short note to AGENTS.md or CLAUDE.md so the agent knows the rules exist and why, which reduces attempts to route around them.
For a faster start, the git-guardrails-claude-code skill sets up a similar hook for the main destructive Git commands. Compare its patterns with your list before adopting it.
Check it worked
Verification checklist
0 of 6 done
When it goes wrong
If nothing is blocked, check the hook loaded: run /hooks in Claude Code to see registered hooks. Then check the script runs on its own (step 5), that jq is installed, and that the file is executable.
If everything is blocked, a pattern is too broad. rm -rf patterns catch rm -rf node_modules too; decide whether that is acceptable or add an allow case before the deny loop.
If the agent keeps finding a way around a rule, for example writing a script that runs the blocked command, that is the limit of pattern matching. Tighten permissions (deny the script runner or require approval for new scripts), and treat hooks as a seatbelt rather than a lock.
Variations
In Codex, hooks use the same shape: put the PreToolUse entry for Bash in .codex/hooks.json in a trusted project and review it with /hooks, since Codex runs a new or changed hook only after you trust it. Codex accepts permissionDecision: "deny", but it does not yet support "ask": it marks the hook run as failed and lets the command continue. Use deny-only rules there, and rely on Codex’s own approval settings for the “ask” cases.
To format or lint after each edit, add a PostToolUse hook on Edit|Write that runs your formatter on tool_input.file_path. It is the same mechanism pointed at a different job.
For a team-wide baseline, administrators can set hooks and permission rules in managed settings, which users cannot override. Keep project hooks for rules specific to one repository.
The same hook mechanism can enforce a way of working, not only block commands: test-driven development with a coding agent makes test files read-only while the agent writes the code that passes them.
Related coding agent safety guides
Claude Code hooks explains every hook event, not only PreToolUse, and coding agent permissions and sandboxing covers the layer underneath. The hooks glossary entry has the short definition. Guardrails matter most when the agent works unattended, as in fixing failing CI with an agent. The rolling out coding agents to a team path includes this recipe, and more are in the AI workflow examples hub.
Outcome and tools
- Outcome
- Your repository has committed hooks and permission rules that block destructive commands and edits to secrets, ask before pushing, log every decision, and pass a test you can re-run.
- For
- Developers, Team leads
- Variants for
- Claude Code, Codex
- Tools
- Agent Skills
Related
- Hooks
User-defined commands that run automatically at set points in a coding agent's lifecycle, such as before a tool call or when a session ends.
- Least privilege
Granting an agent or tool only the permissions and data access its task requires, and nothing more, so a mistake does less damage.
- Refactor in parallel with git worktrees and two agents
Use git worktrees to run Claude Code and Codex in parallel on the same refactor from one written plan, compare tests, diff size and readability, then merge one.
- Your first session with Claude Code
Install it, run it in a real repository, approve its first changes, commit a reviewed edit and learn the commands you will use daily.
- Rolling out coding agents to a team
Roll out coding agents to a team: shared instruction files, permissions and hooks, spec-first work, agent review in CI and vetted Agent Skills for everyone.