# Useful but Little-Known Features of Claude Agent SDK
🌍 Watch, block, or modify agent behavior -- all through hooks.
Rich hook events let you intercept everything from tool calls to subagent completion at any point.
📌 Title: Rich Hook Events
🔗 URL:
🧩 Overview
The Claude Agent SDK hook system lets you register callback functions at key points in agent execution. Events available in both Python and TypeScript include: PreToolUse (before tool call), PostToolUse (after tool execution), PostToolUseFailure (on tool failure), UserPromptSubmit (prompt submission), Stop (execution stop), SubagentStart/Stop (subagent lifecycle), PreCompact (before conversation compaction), PermissionRequest (permission dialog), and Notification (status messages). Callbacks run in the app process, not in the context window.
🛠 How to Use
```python
import asyncio
from claude_agent_sdk import (
ClaudeSDKClient,
ClaudeAgentOptions,
HookMatcher,
AssistantMessage,
ResultMessage,
)
# Hook to block writes to .env files
async def protect_env_files(input_data, tool_use_id, context):
file_path = input_data["tool_input"].get("file_path", "")
file_name = file_path.split("/")[-1]
if file_name == ".env":
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": "deny",
"permissionDecisionReason": "Cannot modify .env files",
}
}
return {}
# Hook to log all tool calls
async def audit_logger(input_data, tool_use_id, context):
print(f"[AUDIT] Tool: {input_data['tool_name']}, ID: {tool_use_id}")
return {}
async def main():
options = ClaudeAgentOptions(
hooks={
"PreToolUse": [
HookMatcher(matcher="Write|Edit", hooks=[protect_env_files]),
HookMatcher(hooks=[audit_logger]),
],
}
)
async with ClaudeSDKClient(options=options) as client:
await client.query("Update the configuration files")
async for message in client.receive_response():
if isinstance(message, (AssistantMessage, ResultMessage)):
print(message)
```
🏗 Integration into Production Systems
- Return permissionDecision in hookSpecificOutput to allow/deny/ask/defer tool calls
- Multiple hooks on the same event run in parallel; the most restrictive decision wins (deny > defer > ask > allow)
- Use additionalContext in PostToolUse hooks to append info to tool results
- Return async_=True for fire-and-forget side effects (logging, metrics) without blocking the agent
💡 Use Cases
🛡 Security: block access to sensitive files/directories with PreToolUse
📊 Audit logging: record every tool call with PostToolUse
🔔 Notification integration: forward status updates to external services (Slack, etc.) via Notification hooks
🔄 Input transformation: redirect file paths to sandbox using updatedInput in PreToolUse
⚠️ Caveats
- Hooks run in the app process; implement error handling to prevent unhandled exceptions from interrupting the agent
- Returning "allow" from a PreToolUse hook does NOT skip subsequent deny rules or permission mode evaluation
- Matchers only match tool names, not file paths. Check tool_input inside the callback for path filtering
- Default hook timeout is 60 seconds
✨ Hold the reins of your agent for safe and transparent automation!
#
ClaudeAgentSDK# #
AIAgent#