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 🛡 Build defense in depth with prompt injection countermeasures, credential proxies, and least privilege. Secure Deployment provides isolation techniques, credential proxy patterns, and network/filesystem controls for safe production agent operation. 📌 Title: Deploying AI Agents Securely 🔗 URL: 🧩 Overview Combines sandbox-runtime / Docker / gVisor / Firecracker isolation, credential proxy patterns, and network/filesystem controls for multi-layered defense. 🛠 How to use it Choose isolation by threat level: sandbox-runtime for single developer/CI, gVisor/Firecracker for multi-tenant or untrusted content. Inject credentials via Envoy / mitmproxy / LiteLLM proxies outside the agent boundary. 🏗 Practical usage - Credential proxy pattern: inject API keys at a proxy outside the agent boundary. The agent calls APIs without ever seeing credentials. Route via `ANTHROPIC_BASE_URL`. - Least privilege: mount only required directories as read-only, exclude `.env` / `~/.aws/credentials` / `*.pem`, use `--network none` + Unix socket proxy. - In cloud environments, use private subnets + cloud firewalls to block all outbound except through the proxy, which enforces allow-lists, injects credentials, and logs all traffic. 💡 Use cases 🔐 Credential management outside agent boundaries 🌐 Network restrictions preventing unauthorized data exfiltration 🏢 Strong isolation for multi-tenant environments ⚠️ Watch out Untrusted content (READMEs, web pages, user input) may contain prompt injection attempts. Network controls are your last line of defense — always configure them. #ClaudeAgentSDK# #AI#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Control exactly which filesystem settings your SDK agent loads with the setting_sources option. Selectively enable CLAUDE.md, skills, hooks, and settings.json — or disable them all for multi-tenant isolation. 📌 Title: Selective Settings Loading with setting_sources 🔗 URL: 🧩 Overview The `setting_sources` option (TypeScript: `settingSources`) controls which filesystem-based settings the SDK loads. There are three sources: `"project"` loads settings.json, hooks, CLAUDE.md, and skills from `/.claude/`; `"user"` loads user-level settings from `~/.claude/`; `"local"` loads `.claude/settings.local.json` and `CLAUDE.local.md`. Omitting the option defaults to all three (`["user", "project", "local"]`). Passing an empty array `[]` disables all filesystem settings. Managed policies and `~/.claude.json` are always loaded regardless. 🛠 Usage Pass a list to `setting_sources` to enable only the sources you need. ```python from claude_agent_sdk import query, ClaudeAgentOptions # Load project and user settings async for message in query( prompt="Help me refactor the auth module", options=ClaudeAgentOptions( setting_sources=["user", "project"], # Enable CLAUDE.md, skills, hooks allowed_tools=["Read", "Edit", "Bash"], ), ): pass # Disable all filesystem settings (programmatic config only) async for message in query( prompt="Analyze this code", options=ClaudeAgentOptions( setting_sources=[], # No filesystem settings loaded ), ): pass ``` 🏗 Integration into Production Systems - For multi-tenant environments, combine `setting_sources=[]` with `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` to prevent settings leakage between tenants - CLAUDE.md requires `"project"` in setting_sources to load — it won't load without it - Each source loads from specific locations: - `"project"`: `/.claude/` for settings.json and hooks; `` and parent dirs for CLAUDE.md and rules - `"user"`: `~/.claude/` for user settings, CLAUDE.md, and rules - `"local"`: `/.claude/settings.local.json` and parent dirs for CLAUDE.local.md 💡 Use Cases 🔒 Secure multi-tenant: run each tenant in isolated filesystem with `setting_sources=[]` to block cross-tenant config 🏗 CI/CD pipelines: enable only `"project"` to load repo-specific CLAUDE.md and skills 👤 Developer customization: include `"user"` to allow personal `~/.claude/CLAUDE.md` preferences ⚠️ Caveats - Some inputs are not controlled by setting_sources: managed policies, `~/.claude.json`, auto memory (`~/.claude/projects/`), MCP connectors - To disable auto memory, set `autoMemoryEnabled: false` in settings or `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in env - When you set setting_sources explicitly, all three defaults are disabled — list every source you need ✨ Proper setting_sources configuration gives you precise control over agent settings, enabling safe and predictable behavior across environments. #ClaudeAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 You don't have to write your system prompt from scratch. The claude_code preset with append lets you keep all built-in safety and tool guidance while adding your own instructions on top. Plus, excludeDynamicSections enables cross-machine prompt cache sharing for fleet deployments. 📌 Title: System Prompt Preset + Append Pattern 🔗 URL: 🧩 Overview The Claude Agent SDK offers three starting points for system prompts: (1) minimal default (when `systemPrompt` is unset — covers tool calling only), (2) `claude_code` preset (the full Claude Code CLI prompt), and (3) custom string (complete control). The most powerful pattern is the `claude_code` preset combined with `append`: it preserves the preset's tool usage instructions, security and safety rules, and coding conventions, while letting you add custom instructions at the end. Importantly, CLAUDE.md content is injected into the conversation, not the system prompt, so it works with any system prompt configuration. 🛠 Usage Pass a dict to `system_prompt` with the preset and append fields. Optionally enable `exclude_dynamic_sections` for cache sharing. ```python from claude_agent_sdk import query, ClaudeAgentOptions # Preset + append: keep all defaults, add custom instructions async for message in query( prompt="Help me write a Python function to calculate fibonacci numbers", options=ClaudeAgentOptions( system_prompt={ "type": "preset", "preset": "claude_code", "append": "Always include detailed docstrings and type hints in Python code.", } ), ): pass # process messages # Enable cross-session cache sharing async for message in query( prompt="Triage the open issues in this repo", options=ClaudeAgentOptions( system_prompt={ "type": "preset", "preset": "claude_code", "append": "You operate Acme's internal triage workflow.", "exclude_dynamic_sections": True, # Move env context to user message }, ), ): pass ``` 🏗 Integration into Production Systems - Use `claude_code` preset + `append` as the default for coding agents, eliminating the need to reimplement security rules and tool guidance - Set `exclude_dynamic_sections: True` to move working directory, OS, and shell info from the system prompt to the user message, enabling prompt cache sharing across machines - CLAUDE.md loads automatically when `setting_sources` includes `"project"`, functioning independently of the system prompt choice 💡 Use Cases 🏢 Internal coding standards: maintain preset safety while appending company-specific conventions 🌐 Fleet cost reduction: share prompt cache across all machines with excludeDynamicSections 🤖 Specialized agents: use custom string for non-coding agents (data analysis, support bots) where the coding preset is irrelevant ⚠️ Caveats - Custom string prompts require you to provide your own tool guidance and safety instructions - `excludeDynamicSections` moves environment context to the user message, which carries marginally less weight than system prompt placement - The SDK default (no `systemPrompt`) differs from the CLI default; explicitly set the preset when migrating from `claude -p` ✨ The preset + append pattern is the lowest-risk way to customize agent behavior without breaking safe defaults. #ClaudeAgentSDK# #AIAgent#
Show more
# Practical ways to use the Claude Agent SDK 📊 Visualize all agent activity in Datadog, Grafana, or Langfuse with OpenTelemetry. OpenTelemetry Observability exports agent traces, metrics, and logs via OTLP to external monitoring tools. 📌 Title: Observability with OpenTelemetry 🔗 URL: 🧩 Overview Enable with `CLAUDE_CODE_ENABLE_TELEMETRY=1` to export traces, metrics, and logs via OTLP to Honeycomb, Datadog, Grafana, Langfuse, and more. W3C trace context propagation automatically links agent traces to your application traces. 🛠 How to use it ```bash export CLAUDE_CODE_ENABLE_TELEMETRY=1 export CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1 export OTEL_EXPORTER_OTLP_ENDPOINT=https://your-collector:4318 ``` 🏗 Practical usage - Monitor "which tools were called, how long each took, how many tokens were used, and where failures occurred" in a single Datadog dashboard. - Get `claude_code.interaction` / `llm_request` / `tool` / `hook` spans with enhanced telemetry to visualize entire sub-agent delegation chains in one trace. - Inject ` / ` via `OTEL_RESOURCE_ATTRIBUTES` to build per-user audit trails and forward to SIEM. 💡 Use cases 🔍 Detailed trace analysis of agent execution 👥 Per-user audit trails 🚨 Bottleneck identification during failures ⚠️ Watch out The `console` exporter conflicts with the SDK's message channel — don't use it. For short-lived processes, shorten `OTEL_*_EXPORT_INTERVAL` to prevent missed flushes. #ClaudeAgentSDK# #AI#
Show more
# Practical ways to use the Claude Agent SDK 💰 Track agent costs per step and per model to optimize your budget. Cost and Usage Tracking uses `total_cost_usd` and `modelUsage` to monitor token consumption and costs in real time. 📌 Title: Cost and Usage Tracking 🔗 URL: 🧩 Overview ` gives cumulative estimated cost per call. `modelUsage` breaks down tokens by model. Prompt caching optimization can significantly reduce costs. 🛠 How to use it Read `total_cost_usd` from `ResultMessage`. Deduplicate using `AssistantMessage` IDs for accurate per-step accounting. 🏗 Practical usage - Monitor `total_cost_usd` per `query()` call and trigger alerts when thresholds are exceeded. - Use `modelUsage` to break down costs between sub-agent Haiku and main Opus usage, visualizing where costs concentrate. - Set `ENABLE_PROMPT_CACHING_1H=1` to extend TTL from 5 minutes to 1 hour, preventing cache misses across many short sessions. - Accumulate `total_cost_usd` across multiple `query()` calls for session-level cost management. 💡 Use cases 📊 Per-step cost visualization dashboard 🔔 Automatic budget threshold alerts ⚡ Prompt cache optimization for cost reduction ⚠️ Watch out `total_cost_usd` is an approximate estimate. Use the Usage and Cost API / Console for authoritative billing. The SDK doesn't provide session totals — accumulate on the app side. #ClaudeAgentSDK# #AI#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Want to give each subagent its own skills, MCP servers, and memory? AgentDefinition has you covered with rich per-agent configuration! Claude Agent SDK's AgentDefinition supports skills, memory, mcpServers, and many more fields for comprehensive per-agent customization. 📌 Title: Per-Agent Configuration: skills / memory / mcpServers 🔗 URL: 🧩 Overview `AgentDefinition` includes numerous optional fields beyond the required `description` and `prompt`. Use `skills` to preload domain-specific knowledge, `memory` to set the memory source (`user`, `project`, or `local`), and `mcpServers` to connect MCP servers by name or inline config. Additional fields include `tools`, `disallowedTools`, `model` (aliases like `sonnet`/`opus`/`haiku`/`inherit` or a full model ID), `effort`, `permissionMode`, `maxTurns`, `background`, and `initialPrompt` for comprehensive behavior control. 🛠 How to Use ```python # Python - fully configured agent definition from claude_agent_sdk import AgentDefinition agent = AgentDefinition( description="Database migration specialist", prompt="You are a DB migration expert. Propose safe migration strategies.", tools=["Read", "Grep", "Glob", "Bash"], disallowed_tools=["Bash(rm *)"], # Block specific operations model="opus", # Use high-quality model skills=["db-migration"], # Preload skills memory="project", # Use project memory mcpServers=["postgres-server"], # Connect MCP servers effort="high", # Higher reasoning level max_turns=20, # Limit maximum turns permission_mode="acceptEdits", # Auto-approve edits background=False, # Run in foreground ) ``` ```typescript // TypeScript const agent: AgentDefinition = { description: "Database migration specialist", prompt: "You are a DB migration expert. Propose safe migration strategies.", tools: ["Read", "Grep", "Glob", "Bash"], disallowedTools: ["Bash(rm *)"], model: "opus", skills: ["db-migration"], memory: "project", mcpServers: ["postgres-server"], effort: "high", maxTurns: 20, permissionMode: "acceptEdits", background: false, }; ``` 🏗 Integration into Production Systems - Use `skills` to preload domain-specific knowledge for specialized agents (unlisted skills remain invocable via the Skill tool) - Set appropriate `memory` scope to control context sharing between agents - Manage database and external service connections via `mcpServers` by name or inline configuration - Use `maxTurns` for cost control and runaway prevention; set `effort` to match task importance - Enable `background: true` for non-blocking execution to improve parallel task efficiency 💡 Use Cases 🗄 Database migration agents with MCP server connections for direct DB access 📚 Expert agents with domain-specific skills preloaded at startup ⚡ High-speed workflows with background agents running parallel analyses ⚠️ Caveats - Omitting `tools` inherits all tools from the parent; specify explicitly if you want restrictions - Subagent `permissionMode` is forcibly inherited when the parent uses `bypassPermissions`, `acceptEdits`, or `auto` and cannot be overridden - Skills listed in `skills` are preloaded at startup, but unlisted skills can still be invoked via the Skill tool - In the Python SDK, field names use camelCase to match the wire format ✨ With AgentDefinition's rich configuration fields, you can build purpose-built specialist agents instead of generic ones. Tailor every aspect to the task at hand! #ClaudeAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Need different agent configurations based on runtime conditions? Factory functions let you dynamically generate agent definitions! Claude Agent SDK supports the factory function pattern to create customized AgentDefinitions on the fly, adapting prompts, models, and tools to runtime context. 📌 Title: Dynamic Agent Definitions (Factory Functions) 🔗 URL: 🧩 Overview By creating factory functions that return `AgentDefinition`, you can dynamically generate agents customized to runtime conditions such as security level, user permissions, or environment. Agents are created at query time, so each request can use different configurations. For example, a strict security review can use the `opus` model while a routine review uses `sonnet`, all from the same factory function. 🛠 How to Use ```python # Python - generate agents based on security level from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition def create_security_agent(security_level: str) -> AgentDefinition: is_strict = security_level == "strict" return AgentDefinition( description="Security code reviewer", prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...", tools=["Read", "Grep", "Glob"], model="opus" if is_strict else "sonnet", # Switch model by importance ) # Call factory at query time async for message in query( prompt="Review this PR for security issues", options=ClaudeAgentOptions( allowed_tools=["Read", "Grep", "Glob", "Agent"], agents={ "security-reviewer": create_security_agent("strict") }, ), ): if hasattr(message, "result"): print(message.result) ``` ```typescript // TypeScript function createSecurityAgent(level: "basic" | "strict"): AgentDefinition { const isStrict = level === "strict"; return { description: "Security code reviewer", prompt: `You are a ${isStrict ? "strict" : "balanced"} security reviewer...`, tools: ["Read", "Grep", "Glob"], model: isStrict ? "opus" : "sonnet", }; } for await (const message of query({ prompt: "Review this PR for security issues", options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], agents: { "security-reviewer": createSecurityAgent("strict") } } })) { if ("result" in message) console.log(message.result); } ``` 🏗 Integration into Production Systems - Assign different models and tool sets based on user permission levels or subscription plans - Read conditions from environment variables or config files to generate environment-appropriate agents - Switch `model` based on task importance to optimize the cost-quality tradeoff - Combine multiple factory functions to dynamically compose diverse agent teams 💡 Use Cases 🔐 Use opus for critical security reviews, sonnet for routine reviews 👥 Multi-tenant systems that dynamically adjust available tools based on user permissions 🌐 Generate agents with localized prompts based on region or language settings ⚠️ Caveats - Factory functions are called synchronously at query time, so avoid heavy processing inside them - Generated agents follow the same constraints as regular AgentDefinitions (e.g., subagents cannot spawn subagents) - Since configurations are generated dynamically, log which configuration was used for easier debugging ✨ The factory function pattern lets one codebase serve diverse use cases with tailored agents. Instead of hardcoding conditionals, delegate to factories! #ClaudeAgentSDK# #AIAgent#
Show more
# Practical ways to use the Claude Agent SDK ⏪ Track all file changes made by the agent and rewind to any safe state at any time. File Checkpointing tracks changes made via Write/Edit and lets you restore to any point using `rewind_files()`. 📌 Title: Rewinding File Changes with Checkpointing 🔗 URL: 🧩 Overview Enable with `enable_file_checkpointing=True`. Each turn's changes are tracked and assigned a checkpoint UUID. `rewind_files(checkpoint_id)` restores file state to that point. 🛠 How to use it Enable with `enable_file_checkpointing=True`. Each `UserMessage.uuid` in the stream serves as a checkpoint ID. Restore with `rewind_files(checkpoint_id)` (or `--rewind-files` flag in CLI). 🏗 Practical usage - Keep the latest checkpoint UUID before risky operations and instantly rewind to the last safe state on verification failure. - Store per-turn UUIDs in an array for selective rollback: "Keep the turn 1 refactor but revert the turn 2 test additions." - Build an interactive approval flow that asks users "Rewind these changes?" after document comment additions. 💡 Use cases 🛡 Instant rollback to safe state on verification failure 🎯 Selective rollback of specific turns 🔄 Faster trial-and-error cycles ⚠️ Watch out Changes via Bash (`echo >`, `sed -i`), directory operations, and remote files are NOT tracked. Conversation history is not rewound — only files. #ClaudeAgentSDK# #AI#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Want to pause a subagent and pick up where it left off later? Resume keeps the full conversation history intact! Claude Agent SDK lets you resume subagents by capturing their session ID and agent ID, retaining all previous tool calls, results, and reasoning. 📌 Title: Subagent Resume 🔗 URL: 🧩 Overview When a subagent completes, the Agent tool result includes `agentId: `. By saving this `agentId` along with the `session_id`, you can resume the same session using the `resume` option and a prompt like `"Resume agent "`. The resumed subagent retains its full conversation history, including all previous tool calls, results, and reasoning. Note that built-in `Explore` and `Plan` agents are one-shot and do not emit `agentId`, so they cannot be resumed. 🛠 How to Use ```python # Python - resuming a subagent import re from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition, ToolResultBlock AGENTS = { "endpoint-finder": AgentDefinition( description="Locates and catalogs API endpoints", prompt="Find and document API endpoints", tools=["Read", "Grep", "Glob"], ) } # First run: execute subagent and capture IDs agent_id = None session_id = None async for message in query( prompt="Use the endpoint-finder agent to find all API endpoints", options=ClaudeAgentOptions( allowed_tools=["Read", "Grep", "Glob", "Agent"], agents=AGENTS, ), ): if hasattr(message, "session_id"): session_id = message.session_id for block in getattr(message, "content", None) or []: if isinstance(block, ToolResultBlock): text = str(block.content) if match := "agentId:\s*([\w-]+)", text): agent_id = # Second run: resume the same session with a follow-up if agent_id and session_id: async for message in query( prompt=f"Resume agent {agent_id} and list the top 3 most complex endpoints", options=ClaudeAgentOptions( allowed_tools=["Read", "Grep", "Glob", "Agent"], agents=AGENTS, resume=session_id, # Resume the same session ), ): if hasattr(message, "result"): print(message.result) ``` 🏗 Integration into Production Systems - Break long analysis tasks into phases, review intermediate results, then resume for follow-up - Persist `session_id` and `agentId` to a database for resumption at any later time - Use custom agents or `general-purpose` (Explore/Plan cannot be resumed) - Pass the same agent definition in the `agents` parameter when resuming 💡 Use Cases 🔄 Conduct phased investigations of large codebases, reviewing results at each stage 💬 Interactive workflows with follow-up questions on subagent analysis results 📊 Run detailed follow-up analysis with a narrowed scope after initial exploration ⚠️ Caveats - Resuming requires the same `session_id`; new `query()` calls start fresh sessions by default - Built-in `Explore` and `Plan` agents are one-shot and do not output `agentId`, so they cannot be resumed - Subagent transcripts are automatically cleaned up based on `cleanupPeriodDays` (default: 30 days) - Main conversation compaction does not affect subagent transcripts ✨ With resume, subagents become ongoing analysis partners rather than one-shot throwaway tools. Use it for iterative, multi-phase investigations! #ClaudeAgentSDK# #AIAgent#
Show more
# 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#
Show more