Fail-Closed PreToolUse Hooks for Read-Only AI Agents in Python
Enforcing deterministic path and tool boundaries before execution using Python stdlib instead of prompt instructions.
System prompts are not a security boundary when an agent processes untrusted input such as external emails, scraped pages, or third-party repositories. Prompt injection can override text rules, and naive shell command allowlists break easily (ls && ..., rg --pre, git -c).
Fail-closed hook pattern
For a read-only worker that only emits a report file, a PreToolUse hook reads the tool call as JSON on stdin, explicitly permits only Read and bounded Write targets via os.path.realpath, and denies Bash, Edit, unknown tools, and any uncaught exception:
import json, os, sys
ALLOWED_ROOT = os.path.realpath("/workspace/reports")
BLOCKED_NAMES = {"agents.md", "claude.md", "readme.md"}
def deny(reason: str) -> int:
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": reason,
}}))
return 0
def main() -> int:
payload = json.load(sys.stdin)
tool, args = payload.get("tool_name"), payload.get("tool_input") or {}
if tool == "Read":
return 0
if tool == "Write":
real = os.path.realpath(str(args.get("file_path", "")))
if not real.startswith(ALLOWED_ROOT + os.sep):
return deny("write outside /workspace/reports")
rel = os.path.relpath(real, ALLOWED_ROOT)
if os.path.basename(real).lower() in BLOCKED_NAMES or any(p.startswith(".") for p in rel.split(os.sep)):
return deny("protected instruction file or hidden path")
return 0
return deny(f"tool {tool!r} denied by default")
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as exc:
sys.exit(deny(f"hook error: {type(exc).__name__}"))
Resolving symlinks with os.path.realpath blocks ../ traversal, an explicit default-deny return stops unlisted tools (Bash, Edit, MCP writers), and catching every exception keeps the gate closed on malformed payloads.