Agent Wealth HubFree public resources
中文 EN العربية

Back to catalog / Agent safety

Block risky commands with a PreToolUse hook

Match command input before tool execution and return deny through hookSpecificOutput.

Goal

Add a deterministic pre-execution policy check to the agent tool loop.

Steps

  1. Define an async hook receiving input_data, tool_use_id, context and inspect only the targeted tool fields. [hooks]
  2. Register with ClaudeAgentOptions(hooks={"PreToolUse":[HookMatcher(matcher="Bash", hooks=[...])]}) and match the intended tool. [hooks]
  3. Return hookEventName="PreToolUse", permissionDecision="deny", and a reason; test blocked and permitted examples. [hooks]

How to verify

The blocked command does not run and returns a denial reason; safe commands still follow permission handling.

Troubleshooting

If the rule misses, verify event, matcher, and return shape; avoid relying only on fragile substring matching.

Permissions

Prerequisites

Permissions

Limitations

A hook is one policy layer; it does not replace CLI permissions, isolation, or human approval.

Pinned upstream source

https://github.com/anthropics/claude-agent-sdk-python/blob/b6e9d12fe1cc98dde988ab7b7713c1feeee50c6c/examples/hooks.py

Repository
anthropics/claude-agent-sdk-python
File path
examples/hooks.py
Pinned commit
b6e9d12fe1cc98dde988ab7b7713c1feeee50c6c
Source checked
2026-10-14 · Reviewed against the pinned upstream source

Repository metrics

These values describe the upstream repository, not popularity or likes for an individual skill or playbook.

Stars
Not collected
Forks
Not collected
Observed at
Not collected

No metrics snapshot is available yet.

License: MIT

Main topic

Make Agent behavior safer and easier to verify

Related resources