# Practical ways to use the Claude Agent SDK
๐ช Intercept every agent action with hooks for auditing, control, and notifications.
Hooks execute custom code at lifecycle events like `PreToolUse`, `PostToolUse`, `Stop`, and `Notification` to validate, log, block, or transform agent behavior.
๐ Title: Intercepting and Controlling Agent Behavior with Hooks
๐ URL:
๐งฉ Overview
Hooks are SDK callbacks that fire before/after tool execution, on stop, notifications, etc. `HookMatcher` targets specific tools by pattern. `permissionDecision` controls allow/deny. Hooks run outside the context window โ zero token cost.
๐ How to use it
In the `hooks` option, use event names (`PreToolUse` / `PostToolUse` / `Notification` etc.) as keys with `HookMatcher` specifying matcher patterns (`"Edit|Write"`, `"^mcp__"` etc.) and callback functions. Callbacks return `permissionDecision` (`allow` / `deny`) or `updatedInput` to control tool execution.
๐ Practical usage
- Block `.env` writes or `/etc` operations in `PreToolUse` with `deny`, injecting a `systemMessage` to explain why to Claude.
- Log all file changes in `PostToolUse` to an audit file for compliance.
- Rewrite Write's `file_path` in `PreToolUse` to redirect all writes to `/sandbox` (`updatedInput` + `allow`).
- Forward permission requests and idle states to Slack or PagerDuty via `Notification` hooks.
๐ก Use cases
๐ก Automatic blocking of dangerous operations
๐ Audit logging of all file changes
๐จ Event forwarding to external notification services
๐ Sandbox redirection for write operations
โ ๏ธ Watch out
Multiple hooks run in parallel with priority: `deny > defer > ask > allow`. Use `async_: True` for non-blocking async processing. `SessionStart` / `SessionEnd` are TypeScript only.
#
ClaudeAgentSDK# #
AI#