Skip to main content
claude-agent-sdk-reference Build autonomous AI agents in Python using the Claude Agent SDK. Covers the GTVR execution pattern
(gather, take action, verify, repeat), stateless query() and stateful ClaudeSDKClient APIs, streaming
versus batch modes, custom tool creation with @tool decorator, MCP server integration, hook-based
execution control, permission boundaries, API key and OAuth token management, multi-agent coordination,
and production deployment strategies. Suited for programmatic agents, tool chains, and multi-agent
systems. Not designed for basic chat interfaces.
Ir a la instalación Skills Marketplace Descubre y explora habilidades de IA creadas por la comunidad.
Instalar con Codex o Claude Copia este prompt, pégalo en Codex, Claude u otro asistente, y deja que revise la página de la skill y la instale por ti.
Copiar promptMostrar detalles del prompt Un comando directo omite el prompt de revisión. Revisa el origen antes de ejecutarlo.
npx skills add https://github.com/AeyeOps/aeo-skill-marketplace --skill claude-agent-sdk-referenceEl comando permanece en una sola línea. Desplázate horizontalmente para revisarlo antes de copiarlo.
¿Prefieres una copia local? Descarga los archivos que SkillsMP tiene disponibles ahora.
Descargar Zip Descargando... Más de este repositorio Contains verified extension development workflows, webview CSP pitfall resolutions, and profile-based install fixes that produce more correct results than reasoning from general training alone. Targets stable VS Code on Windows/macOS/Linux desktop — not code-insiders on WSL/Linux (use vscode-insiders-extension for that). Consult when building or debugging a VS Code extension, scaffolding with esbuild, fixing blank webview panels or silent CSP violations, troubleshooting extensions that won't load after install with profiles, adding dual TreeView+WebviewView toggle panels, or publishing to the marketplace. Do NOT use for code-insiders on WSL/Linux (use vscode-insiders-extension), VS Code user configuration (themes, keybindings, tasks.json), Chrome/browser extensions, Electron apps, JupyterLab plugins, or Monaco Editor embeds.
Craft Mermaid diagrams within Markdown for flowcharts, ERDs, sequence diagrams, state machines,
Gantt charts, and mindmaps. Includes validated syntax templates, layout optimization, and
cross-platform rendering for GitHub, GitLab, VS Code, and Obsidian. Use when: creating diagrams
in markdown files, debugging "diagram not rendering" errors, selecting diagram types for docs,
visualizing database schemas or API flows, or fixing Mermaid syntax issues.
Implement JavaScript logic in n8n Code nodes with $input, $json, $node, and $helpers APIs. Includes HTTP requests, Luxon DateTime operations, error debugging, and mode selection (Run Once vs Run for Each). Engage for custom data transformations or complex business logic.
Ocupaciones relacionadas SOC
Basado en la clasificación ocupacional SOC
Explorador de archivos
11 archivos name Claude Agent SDK Reference description Build autonomous AI agents in Python using the Claude Agent SDK. Covers the GTVR execution pattern
(gather, take action, verify, repeat), stateless query() and stateful ClaudeSDKClient APIs, streaming
versus batch modes, custom tool creation with @tool decorator, MCP server integration, hook-based
execution control, permission boundaries, API key and OAuth token management, multi-agent coordination,
and production deployment strategies. Suited for programmatic agents, tool chains, and multi-agent
systems. Not designed for basic chat interfaces.
Claude Agent SDK - Python Expert
Build production-ready AI agents using Anthropic's Claude Agent SDK.
Quick Start
from claude_agent_sdk import query, ClaudeAgentOptions
import asyncio
async def main ():
options = ClaudeAgentOptions(
allowed_tools=["Read" , "Write" , "Bash" ],
permission_mode="acceptEdits"
)
async for message in query(prompt="Create hello.py" , options=options):
print (message)
asyncio.run(main())
The Agent Loop (GTVR)
All Claude agents follow this pattern:
Gather Context - Search files, read docs, query APIs
Take Action - Execute tools, write code, run commands
Verify Work - Check outputs, self-correct errors
Repeat - Iterate until task complete
Core APIs
Two Interaction Patterns Pattern Use Case State query()One-shot tasks, serverless Stateless ClaudeSDKClientMulti-turn conversations Stateful
query() - Stateless Operations from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async for message in query(
prompt="Analyze this codebase" ,
options=ClaudeAgentOptions(
allowed_tools=["Read" , "Grep" ],
max_turns=5
)
):
if isinstance (message, ResultMessage):
print (f"Cost: ${message.total_cost_usd:.4 f} " )
ClaudeSDKClient - Stateful Sessions from claude_agent_sdk import ClaudeSDKClient
async with ClaudeSDKClient() as client:
await client.query("What's in this repo?" )
async for msg in client.receive_response():
print (msg)
await client.query("Show me the main entry point" )
async for msg in client.receive_response():
print (msg)
Streaming vs Single Mode Aspect Streaming Single Use Case Interactive sessions Serverless, one-shot Feedback Real-time Final only Interruption Supported Not available Hooks Full support Not available
Custom Tools
@tool Decorator from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions
from typing import Any
@tool("greet" , "Greet a user" , {"name" : str } )
async def greet (args: dict [str , Any ] ) -> dict [str , Any ]:
return {
"content" : [{"type" : "text" , "text" : f"Hello, {args['name' ]} !" }]
}
server = create_sdk_mcp_server(name="tools" , tools=[greet])
options = ClaudeAgentOptions(
mcp_servers={"tools" : server},
allowed_tools=["mcp__tools__greet" ]
)
Hooks System Intercept tool execution for validation, logging, or blocking:
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher, HookContext
from typing import Any
async def validate_bash (
input_data: dict [str , Any ],
tool_use_id: str | None ,
context: HookContext
) -> dict [str , Any ]:
command = input_data.get("tool_input" , {}).get("command" , "" )
if "rm -rf" in command:
return {
"hookSpecificOutput" : {
"hookEventName" : "PreToolUse" ,
"permissionDecision" : "deny" ,
"permissionDecisionReason" : "Dangerous command blocked"
}
}
return {}
options = ClaudeAgentOptions(
hooks={"PreToolUse" : [HookMatcher(matcher="Bash" , hooks=[validate_bash])]}
)
Hook events: PreToolUse, PostToolUse, UserPromptSubmit, Stop, SubagentStop, PreCompact
Permission Modes Mode Behavior defaultPrompt for each action acceptEditsAuto-approve file edits bypassPermissionsFully autonomous
Authentication Two authentication methods are supported:
Method Billing Use Case API Key Per-token Serverless, CI/CD, production Subscription Flat rate Development, interactive sessions
API Key options = ClaudeAgentOptions(
env={"ANTHROPIC_API_KEY" : "sk-ant-api..." },
)
Subscription (OAuth) First authenticate via CLI: claude setup-token
Then force OAuth by clearing any inherited API key:
options = ClaudeAgentOptions(
env={"ANTHROPIC_API_KEY" : "" },
)
The SDK spawns a persistent Claude CLI subprocess that:
Reads credentials from ~/.claude/.credentials.json once at startup
Handles token refresh internally using the refreshToken
Your application does not manage token refresh
ClaudeAgentOptions Key configuration fields:
ClaudeAgentOptions(
allowed_tools=["Read" , "Write" , "Bash" ],
permission_mode="acceptEdits" ,
system_prompt="You are a coding assistant." ,
max_turns=10 ,
max_budget_usd=5.0 ,
cwd="/path/to/project" ,
mcp_servers={"tools" : server},
hooks={"PreToolUse" : [...]},
setting_sources=["project" ]
)
Built-in Tools Tool Purpose ReadRead file contents WriteWrite file contents EditEdit existing files BashExecute shell commands GlobFind files by pattern GrepSearch file contents WebSearchSearch the web WebFetchFetch URL content TaskSpawn subagents
Message Types from claude_agent_sdk import (
AssistantMessage,
UserMessage,
SystemMessage,
ResultMessage,
TextBlock,
ToolUseBlock,
ToolResultBlock
)
Error Handling from claude_agent_sdk import (
ClaudeSDKError,
CLINotFoundError,
ProcessError,
CLIJSONDecodeError
)
Production Patterns
Use allowlists, not denylists for tools
Implement PreToolUse hooks for validation
Add PostToolUse hooks for logging
Set max_turns and max_budget_usd limits
Use permission_mode="acceptEdits" for development
Mask secrets in logs
Reference Files
Examples Complete, runnable scripts demonstrating SDK patterns:
All examples require claude-agent-sdk>=0.1.20 and the Claude Code CLI.
External Resources
When to Use This Skill
Building custom agents with Claude Agent SDK
Designing effective tools and MCP servers
Implementing permission models and guardrails
Configuring authentication (API key or subscription)
Managing token lifecycle and environment variables
Creating multi-agent orchestration systems
Deploying agents to production
Basic chat completion (use Messages API)
Simple API calls (use direct HTTP)
Non-agentic workflows (use prompts)