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

Search results for ClaudeAgentSDK
ClaudeAgentSDK community
One keyword maps to one global community path.
Create community
People
Not Found
Tweets including ClaudeAgentSDK
# Practical ways to use the Claude Agent SDK 🤖 Delegate specialized tasks to sub-agents and keep your main context lean. Sub-agents delegate specific subtasks to specialized agents, enabling parallel and expert processing without polluting the main agent's context. 📌 Title: Sub-agents in the SDK 🔗 URL: 🧩 Overview Define specialized agents via the `agents` parameter. The main agent calls them through the `Agent` tool. Each sub-agent gets its own prompt, tool restrictions, and model settings. Results return as summaries to the main agent. 🛠 How to use it Define sub-agents in the `agents` parameter using `AgentDefinition` with `description`, `prompt`, `tools`, and `model`. Include `"Agent"` in `allowed_tools` to auto-approve sub-agent invocations. Each sub-agent gets its own tool restrictions, prompt, and model settings. 🏗 Practical usage - Delegate large file exploration to a `research-assistant` sub-agent, returning only summaries to the parent. Keeps main context lean. - Run `style-checker` / `security-scanner` / `test-coverage` concurrently, reducing code review time from minutes to seconds. - Give a `database-migration` sub-agent SQL best practices and rollback strategies in its prompt for expert handling. - Use factory functions to dynamically select `model: "opus"` vs `sonnet` based on runtime conditions. 💡 Use cases 🔍 Delegating large-scale file exploration ⚡ Parallel code review (style/security/coverage) 🎯 Expert task splitting across specialized agents ⚠️ Watch out Sub-agents cannot spawn their own sub-agents (one level only). For large-scale orchestration, use the `Workflow` tool (TS v0.3.149+). Capture `agentId` and `session_id` for follow-up via `resume`. #ClaudeAgentSDK# #AI#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Need to change permissions mid-session? You can dynamically switch permission modes during streaming! Claude Agent SDK lets you call `set_permission_mode()` to instantly change the permission mode while a session is running. 📌 Title: Dynamic Permission Mode Changes During Streaming 🔗 URL: 🧩 Overview Using `set_permission_mode()` (Python) or `setPermissionMode()` (TypeScript), you can change the permission mode in real-time during an active session. The new mode takes effect immediately for all subsequent tool requests. This enables progressive trust workflows where you start restrictive and loosen permissions as confidence builds, for example switching from `default` to `acceptEdits` after reviewing Claude's initial approach. 🛠 How to Use ```python # Python - progressively relaxing permissions import asyncio from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions async def main(): async with ClaudeSDKClient( options=ClaudeAgentOptions( permission_mode="default", # Start in default mode ) ) as client: await client.query("Refactor this code") # After reviewing the approach, allow edits await client.set_permission_mode("acceptEdits") async for message in client.receive_response(): if hasattr(message, "result"): print(message.result) ``` ```typescript // TypeScript const q = query({ prompt: "Refactor this code", options: { permissionMode: "default" } }); // After reviewing the approach, allow edits await q.setPermissionMode("acceptEdits"); for await (const message of q) { if ("result" in message) console.log(message.result); } ``` 🏗 Integration into Production Systems - Implement "plan, review, then acceptEdits" workflows for safe step-by-step automation - Build interactive apps that progressively expand permissions based on user trust and task progress - Use as a "fallback" pattern to tighten permissions when errors are detected - Integrate with monitoring systems to automatically switch to restrictive modes on anomaly detection 💡 Use Cases 🔐 Interactive workflows that grant edit permissions only after code review approval 📈 Progressive automation that expands permissions as the task advances 🛡 Defensive agents that instantly switch to restrictive mode upon detecting anomalies ⚠️ Caveats - The new mode takes effect immediately, so be careful about the timing of the switch - Mode changes are only effective within the current session - Switching to `bypassPermissions` or `auto` mode will be inherited by subagents ✨ Dynamic permission changes enable "start safe, flex as needed." Build progressive trust workflows to get the best of both safety and productivity! #ClaudeAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Want Claude to plan changes without touching your code? Plan mode restricts the agent to read-only exploration! Claude Agent SDK's plan mode lets Claude analyze your codebase and propose changes using only read-only tools, never editing source files. 📌 Title: Plan Mode (Read-Only Execution Only) 🔗 URL: 🧩 Overview Setting `permission_mode="plan"` restricts Claude to read-only tools such as Read, Grep, Glob, and read-only shell commands. Edit, Write, and write-mode Bash operations are blocked. Claude may use `AskUserQuestion` to clarify requirements before finalizing the plan. This mode is ideal for code review, architecture analysis, and change proposals where you want insights without side effects. 🛠 How to Use ```python # Python - plan mode for code review import asyncio from claude_agent_sdk import query, ClaudeAgentOptions async def main(): async for message in query( prompt="Analyze security issues in the auth module and propose a fix plan", options=ClaudeAgentOptions( permission_mode="plan", # Read-only analysis ), ): if hasattr(message, "result"): print(message.result) ``` ```typescript // TypeScript for await (const message of query({ prompt: "Analyze security issues in the auth module and propose a fix plan", options: { permissionMode: "plan" // Read-only analysis } })) { if ("result" in message) console.log(message.result); } ``` 🏗 Integration into Production Systems - Use for automated PR reviews that surface issues and suggestions without modifying code - Safely explore and understand new codebases during onboarding or investigation phases - Implement a "plan then execute" workflow: review the plan, then switch to `acceptEdits` mode - Combine with `set_permission_mode()` to transition from planning to execution after human approval 💡 Use Cases 📋 Generate change proposals in code reviews, leaving actual modifications to human judgment 🔍 Safely analyze architecture of large codebases without risk of accidental changes 📝 Build refactoring plans for team consensus before execution ⚠️ Caveats - Read-only shell commands may still execute - `AskUserQuestion` may be triggered, so for fully unattended operation, dontAsk mode is more appropriate - To act on the plan, you need a new session or a dynamic permission mode change ✨ "Plan first, execute second" is a fundamental engineering practice. Use plan mode to safely analyze, then commit to changes only after you're confident in the approach! #ClaudeAgentSDK# #AIAgent#
Show more
# Practical ways to use the Claude Agent SDK 🔌 Connect Playwright, databases, GitHub, and more to your agent via MCP for unlimited capabilities. MCP (External Tool Connections) connects external MCP servers (browsers, databases, APIs) to your agent via the Model Context Protocol. 📌 Title: Connecting External Tools with MCP 🔗 URL: 🧩 Overview Specify external MCP servers in `mcp_servers` via stdio / HTTP / SSE transports. Control tool access with `allowedTools` and inject credentials via `env` or `headers`. 🛠 How to use it Specify MCP servers in `mcp_servers` via stdio, HTTP, or SSE transports. For example, Playwright uses `{"command": "npx", "args": ["@playwright/mcp@latest"]}`, and Postgres injects credentials via `"env": {"DATABASE_URL": "..."}`. Control access with `allowed_tools=["mcp__postgres__query"]`. 🏗 Practical usage - Connect Playwright MCP and run "Open and describe what you see" for E2E testing or web scraping agents. - Connect a Postgres MCP server and ask "Daily signups for last week" — Claude auto-detects schema, generates SQL, and executes. Lock down with `allowedTools: ["mcp__postgres__query"]`. - Build GitHub Issue triage and auto-response bots with the GitHub MCP server. - Verify connection status at startup via `system/init` message's `mcp_servers[].status`. 💡 Use cases 🌐 Browser automation with Playwright 🗄 Natural language database queries 📋 Automated GitHub Issue triage ⚠️ Watch out `permissionMode: "acceptEdits"` does NOT auto-approve MCP tools. Use `allowedTools` wildcards (`mcp__github__*`) to safely whitelist specific servers. Default connection timeout is 60 seconds. #ClaudeAgentSDK# #AI#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Permission evaluation is a 5-stage pipeline. Understanding what happens where makes security design dramatically clearer. Hooks, deny rules, permission mode, allow rules, and callback -- evaluated strictly in order. 📌 Title: 5-Stage Permission Evaluation Order 🔗 URL: 🧩 Overview Claude Agent SDK tool permissions are evaluated in a 5-stage pipeline: (1) Hooks: PreToolUse hooks run first and can deny. However, returning "allow" does NOT skip subsequent evaluation stages. (2) Deny rules: checks disallowed_tools. Bare tool names (e.g., "Bash") remove the tool definition from context entirely. Scoped rules (e.g., "Bash(rm *)") block even in bypassPermissions mode. (3) Permission mode: bypassPermissions approves everything reaching this stage. acceptEdits approves file operations. (4) Allow rules: matched allowed_tools entries are approved. (5) canUseTool callback: called for anything not resolved above. Priority order: deny > defer > ask > allow. 🛠 How to Use ```python import asyncio from claude_agent_sdk import ( ClaudeSDKClient, ClaudeAgentOptions, HookMatcher, ) # Stage 1: Hook to block dangerous operations async def block_dangerous_commands(input_data, tool_use_id, context): if input_data.get("tool_name") == "Bash": command = input_data["tool_input"].get("command", "") if "rm -rf" in command: return { "hookSpecificOutput": { "hookEventName": input_data["hook_event_name"], "permissionDecision": "deny", "permissionDecisionReason": "rm -rf is prohibited", } } return {} async def main(): options = ClaudeAgentOptions( # Stage 1: Hooks hooks={ "PreToolUse": [ HookMatcher(matcher="Bash", hooks=[block_dangerous_commands]) ], }, # Stage 2: Deny rules (bare name = removed from context entirely) disallowed_tools=["WebFetch"], # Stage 3: Permission mode permission_mode="acceptEdits", # Auto-approve file operations # Stage 4: Allow rules allowed_tools=["Read", "Glob", "Grep", "Edit", "Write"], ) # Stage 5: canUseTool is configured separately via query() or ClaudeSDKClient async with ClaudeSDKClient(options=options) as client: await client.query("Improve the code") async for message in client.receive_response(): print(message) ``` Lockdown configuration example: ```python # Principle of least privilege: only allowed tools, everything else denied options = ClaudeAgentOptions( allowed_tools=["Read", "Glob", "Grep"], permission_mode="dontAsk", # Deny unapproved tools without prompting ) ``` 🏗 Integration into Production Systems - allowed_tools does NOT constrain bypassPermissions. Even with only "Read" in allowed_tools, bypassPermissions approves all tools - Use disallowed_tools to completely block specific tools (effective even in bypassPermissions) - For least privilege, combine allowed_tools with permission_mode="dontAsk" - A hook returning "allow" means "this hook is OK with it" -- it does not override subsequent deny rules or mode evaluation 💡 Use Cases 🔒 Least-privilege agent: allow only Read/Glob/Grep with dontAsk to deny everything else 🛡 Progressive trust: start in default mode, escalate to acceptEdits after review 🚫 Eliminate dangerous ops: remove Bash entirely via disallowed_tools, or scope-block with Bash(rm *) 🔍 Audited approvals: log all requests via hooks while auto-deciding via rules ⚠️ Caveats - Tools not in allowed_tools are "unresolved," not "denied" -- they proceed to the next stage - Bare tool names in disallowed_tools remove the tool definition from context; the agent won't even know the tool exists - bypassPermissions is inherited by subagents, which may have different system prompts -- use with caution - When multiple hooks register for the same event, the most restrictive decision wins ✨ Master the 5-stage permission pipeline for robust security design! #ClaudeAgentSDK# #AIAgent#
Show more
# Practical ways to use the Claude Agent SDK 🔧 Define your internal APIs, databases, and domain logic with `@tool` and let Claude call them. Custom Tools lets you define your own functions as in-process MCP servers using the `@tool` decorator, making them callable by Claude during conversations. 📌 Title: Providing Custom Tools to Claude 🔗 URL: 🧩 Overview Define tools with `@tool` (Python) / `tool()` (TypeScript) specifying name, description, schema, and handler. Wrap with `create_sdk_mcp_server` and pass to `mcp_servers`. Annotate side-effect-free tools with `readOnlyHint: true` for parallel execution. 🛠 How to use it Define tools with `@tool` (Python) / `tool()` (TypeScript) specifying name, description, schema, and handler. Wrap with `create_sdk_mcp_server` and pass to `mcp_servers={"weather": server}`. Tools are exposed to Claude as `mcp__weather__get_temperature`. 🏗 Practical usage - Define internal APIs (customer info, inventory, order status) as `@tool` and build agents that respond to natural language queries. - Add `readOnlyHint: true` to read-only tools for parallel execution and lower latency. - Catch exceptions in handlers and return `is_error=True` so the agent loop continues and Claude retries or tries alternatives. - Return chart images via `image` blocks (base64) for Claude to analyze visually. 💡 Use cases 🏢 Natural language access to internal APIs 📊 Chart generation + image analysis pipeline 🔄 Fault-tolerant autonomous retry ⚠️ Watch out Uncaught exceptions in handlers crash the entire `query()`. Always handle errors. Use `tools: ["Read","Grep"]` to restrict which built-in tools are available. #ClaudeAgentSDK# #AI#
Show more
# Practical ways to use the Claude Agent SDK 📦 Get typed JSON output from agents and bind it directly to your UI components. Structured Output uses `output_format` to receive agent results as typed data conforming to a JSON schema, validated with Zod or Pydantic. 📌 Title: Getting Structured Output from Agents 🔗 URL: 🧩 Overview Specify a JSON schema in `output_format` and the agent returns structured JSON instead of free text. Type-safe validation is available via Zod (TypeScript) / Pydantic (Python). 🛠 How to use it Set `output_format={"type": "json_schema", "schema": your_schema}` in your options. Generate schemas with Pydantic's `.model_json_schema()` or Zod's `z.toJSONSchema()`. Results appear in `ResultMessage.structured_output`. 🏗 Practical usage - In a recipe app, get web search results as `{name, prep_time_minutes, ingredients[], steps[]}` and bind directly to UI components. - Build a TODO extraction agent that runs Grep + Bash(git blame) autonomously and returns `{todos[{text, file, line, author?, date?}], total_count}`. - Receive feature implementation plans as `{summary, steps[{description, complexity}], risks[]}` for automatic project management tool integration. 💡 Use cases 🎨 Direct data binding to UI components 📊 Structured analysis report generation 🔧 Automatic data ingestion into project management tools ⚠️ Watch out Structured output is incompatible with streaming. JSON results only appear in the final `ResultMessage.structured_output`. Handle `error_max_structured_output_retries` by retrying with simpler prompts or falling back to unstructured output. #ClaudeAgentSDK# #AI#
Show more
# 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
# Practical ways to use the Claude Agent SDK ✅ Request user approval before dangerous operations with 6 flexible response patterns. Approval and User Input uses the `canUseTool` callback to intercept dangerous operations and `AskUserQuestion` for requirements gathering. 📌 Title: Handling Approvals and User Input 🔗 URL: 🧩 Overview `canUseTool` intercepts each tool call with 6 response patterns: approve, approve with modifications, approve and remember, deny, suggest alternative, or full redirect. `AskUserQuestion` lets Claude present multiple-choice questions to users. 🛠 How to use it Define a `canUseTool` callback that returns `PermissionResultAllow` or `PermissionResultDeny` based on tool name and arguments. 🏗 Practical usage - Build an interactive approval UI that detects file deletions or Bash execution and prompts y/n. You can approve with modifications like "scope all Bash commands to /tmp/sandbox". - Use "approve and remember" with `updated_permissions` to persist rules in `.claude/settings.local.json`. - Combine `AskUserQuestion` with `plan` mode to gather requirements before making changes: "Which tech stack for the mobile app?" with multiple choice options. 💡 Use cases 🛡 Interactive approval UI for dangerous operations 📋 Multi-choice requirements gathering 🔐 Persistent approval rule learning ⚠️ Watch out AskUserQuestion is not available in sub-agents. Questions are limited to 1-4, choices to 2-4. In Python, `can_use_tool` requires streaming mode plus a dummy PreToolUse hook. #ClaudeAgentSDK# #AI#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Let AI modify your files with confidence -- you can always roll back. File checkpointing automatically tracks changes made by Write/Edit/NotebookEdit and lets you rewind to any point in time. 📌 Title: File Checkpointing and Rollback 🔗 URL: 🧩 Overview File checkpointing tracks file modifications during agent sessions. When you set enable_file_checkpointing=True, the SDK creates backups before any Write, Edit, or NotebookEdit tool modifies a file. Each UserMessage's UUID serves as a checkpoint, and you can call rewind_files() with that UUID to restore files to that point. Created files get deleted, and modified files are restored to their original content. 🛠 How to Use ```python import asyncio from claude_agent_sdk import ( ClaudeSDKClient, ClaudeAgentOptions, UserMessage, ResultMessage, ) async def main(): # Step 1: Enable checkpointing options = ClaudeAgentOptions( enable_file_checkpointing=True, permission_mode="acceptEdits", extra_args={"replay-user-messages": None}, # Required for UUIDs ) checkpoint_id = None session_id = None async with ClaudeSDKClient(options) as client: await client.query("Refactor the authentication module") # Step 2: Capture checkpoint UUID from UserMessage async for message in client.receive_response(): if isinstance(message, UserMessage) and message.uuid and not checkpoint_id: checkpoint_id = message.uuid if isinstance(message, ResultMessage) and not session_id: session_id = message.session_id # Step 3: Resume session and rollback if checkpoint_id and session_id: async with ClaudeSDKClient( ClaudeAgentOptions( enable_file_checkpointing=True, resume=session_id ) ) as client: await client.query("") # Empty prompt to open connection async for message in client.receive_response(): await client.rewind_files(checkpoint_id) break print(f"Rewound to checkpoint: {checkpoint_id}") ``` 🏗 Integration into Production Systems - extra_args={"replay-user-messages": None} is required; without it, UUIDs won't appear in the stream - To rollback, resume the session, send an empty prompt, then call rewind_files() - Persist checkpoint UUIDs and session IDs to enable rollback after process restarts - Combine with permission_mode="acceptEdits" to auto-approve file changes while maintaining rollback safety 💡 Use Cases 🔧 Safe refactoring: try changes and instantly rollback if issues arise 🧪 Experimental code generation: validate AI output and revert if quality is low 📝 Auto-generated documentation: review results and undo unwanted changes ⚠️ Caveats - Changes via Bash commands (echo > file.txt, sed -i, etc.) are NOT tracked - Only file content is tracked; directory creation/move/deletion is not undone - Conversation history is not rolled back -- only files are restored - Checkpoints are tied to the session that created them ✨ Develop fearlessly with "undo-able" AI -- let the agent code with confidence! #ClaudeAgentSDK# #AIAgent#
Show more