Register and share your invite link to earn from video plays and referrals.

cv usk
@cv_usk
AI / Software Research Notes AI Agent, LLMOps, MLOps, Software Architecture ๆŠ•็จฟใฏๅ€‹ไบบใฎๆ„่ฆ‹ใงใ™ใ€‚
Joined May 2026
258 Following    220 Followers
# 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#
Show more