AgentSkillsCN

Claude Agent SDK Reference

利用Claude Agent SDK以Python构建自主AI代理。此技能涵盖GTVR执行模式(收集、行动、验证、重复)、无状态的query()与有状态的ClaudeSDKClient API、流式处理与批量处理模式的切换、通过@tool装饰器自定义工具、MCP服务器集成、基于钩子的执行控制、权限边界、API密钥与OAuth令牌管理、多代理协作,以及生产部署策略。此技能特别适合程序化代理、工具链,以及多代理系统,但并不适用于基础聊天界面的开发。

SKILL.md
--- frontmatter
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

python
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:

  1. Gather Context - Search files, read docs, query APIs
  2. Take Action - Execute tools, write code, run commands
  3. Verify Work - Check outputs, self-correct errors
  4. Repeat - Iterate until task complete

For detailed patterns: See architecture-patterns.md

Core APIs

Two Interaction Patterns

PatternUse CaseState
query()One-shot tasks, serverlessStateless
ClaudeSDKClientMulti-turn conversationsStateful

query() - Stateless Operations

python
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:.4f}")

ClaudeSDKClient - Stateful Sessions

python
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)

    # Follow-up with preserved context
    await client.query("Show me the main entry point")
    async for msg in client.receive_response():
        print(msg)

For complete API reference: See python-sdk.md

Streaming vs Single Mode

AspectStreamingSingle
Use CaseInteractive sessionsServerless, one-shot
FeedbackReal-timeFinal only
InterruptionSupportedNot available
HooksFull supportNot available

For patterns and examples: See streaming.md

Custom Tools

@tool Decorator

python
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"]
)

For tool design and MCP integration: See tools-mcp.md

Hooks System

Intercept tool execution for validation, logging, or blocking:

python
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

ModeBehavior
defaultPrompt for each action
acceptEditsAuto-approve file edits
bypassPermissionsFully autonomous

Authentication

Two authentication methods are supported:

MethodBillingUse Case
API KeyPer-tokenServerless, CI/CD, production
SubscriptionFlat rateDevelopment, interactive sessions

API Key

python
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:

python
options = ClaudeAgentOptions(
    env={"ANTHROPIC_API_KEY": ""},  # Empty string forces OAuth
)

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

For complete auth patterns and token lifecycle: See authentication.md

ClaudeAgentOptions

Key configuration fields:

python
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"]  # Load CLAUDE.md
)

Built-in Tools

ToolPurpose
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

python
from claude_agent_sdk import (
    AssistantMessage,  # Claude's response
    UserMessage,       # User input
    SystemMessage,     # System events
    ResultMessage,     # Completion with cost
    TextBlock,         # Text content
    ToolUseBlock,      # Tool invocation
    ToolResultBlock    # Tool output
)

Error Handling

python
from claude_agent_sdk import (
    ClaudeSDKError,     # Base exception
    CLINotFoundError,   # SDK not installed
    ProcessError,       # Process failure
    CLIJSONDecodeError  # Parse error
)

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

For deployment checklist: See architecture-patterns.md

Reference Files

Examples

Complete, runnable scripts demonstrating SDK patterns:

ExamplePurposeKey Patterns
basic_query.pySimplest working agentquery(), message handling, error handling
custom_tools.pyCustom MCP tools@tool decorator, create_sdk_mcp_server
stateful_client.pyProduction patternsClaudeSDKClient, hooks, multi-turn
extended_thinking.pyExtended thinkingThinkingBlock, max_thinking_tokens
streaming_events.pyReal-time streamingStreamEvent, include_partial_messages

All examples require claude-agent-sdk>=0.1.20 and the Claude Code CLI.

External Resources

When to Use This Skill

Use for:

  • 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

Not for:

  • Basic chat completion (use Messages API)
  • Simple API calls (use direct HTTP)
  • Non-agentic workflows (use prompts)