Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示詞最佳實踐
    上下文管理
    上下文視窗壓縮上下文編輯
    功能
    提示詞快取延伸思考自適應思考思考力度串流訊息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實作工具使用細粒度工具串流Bash 工具程式碼執行工具程式化工具呼叫電腦使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐企業級 Skills透過 API 使用 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽版)Python SDK遷移指南
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞產生器使用提示詞範本提示詞改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 Claude 角色(系統提示詞)串聯複雜提示詞長上下文技巧延伸思考技巧
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    強化防護機制
    減少幻覺提高輸出一致性防範越獄攻擊串流拒絕減少提示詞洩漏讓 Claude 保持角色
    管理與監控
    Admin API 概覽資料駐留工作區用量與成本 APIClaude Code Analytics API零資料保留
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    Agent SDK

    Agent SDK 參考文件 - Python

    Python Agent SDK 的完整 API 參考文件,包含所有函式、型別和類別。

    Was this page helpful?

    • 在 query() 和 ClaudeSDKClient 之間選擇
    • 何時使用 query()(每次建立新工作階段)
    • 何時使用 ClaudeSDKClient(持續對話)
    • query()
    • tool()
    • create_sdk_mcp_server()
    • ClaudeSDKClient
    • SdkMcpTool
    • ClaudeAgentOptions
    • OutputFormat
    • SystemPromptPreset
    • SettingSource
    • AgentDefinition
    • PermissionMode
    • CanUseTool
    • ToolPermissionContext
    • PermissionResult
    • PermissionResultAllow
    • PermissionResultDeny
    • PermissionUpdate
    • SdkBeta
    • McpSdkServerConfig
    • McpServerConfig
    • SdkPluginConfig
    • Message
    • UserMessage
    • AssistantMessage
    • SystemMessage
    • ResultMessage
    • StreamEvent
    • ContentBlock
    • TextBlock
    • ThinkingBlock
    • ToolUseBlock
    • ToolResultBlock
    • ClaudeSDKError
    • CLINotFoundError
    • CLIConnectionError
    • ProcessError
    • CLIJSONDecodeError
    • Hook 型別
    • HookEvent
    • HookCallback
    • HookContext
    • HookMatcher
    • HookInput
    • BaseHookInput
    • PreToolUseHookInput
    • PostToolUseHookInput
    • UserPromptSubmitHookInput
    • StopHookInput
    • SubagentStopHookInput
    • PreCompactHookInput
    • HookJSONOutput
    • Hook 使用範例
    • Task
    • AskUserQuestion
    • Bash
    • Edit
    • Read
    • Write
    • Glob
    • Grep
    • NotebookEdit
    • WebFetch
    • WebSearch
    • TodoWrite
    • BashOutput
    • KillBash
    • ExitPlanMode
    • ListMcpResources
    • ReadMcpResource
    • 使用 ClaudeSDKClient 的進階功能
    • 使用 Hook 進行行為修改
    • 基本檔案操作(使用 query)
    • 使用 ClaudeSDKClient 的自訂工具
    • SandboxSettings
    • SandboxNetworkConfig
    • SandboxIgnoreViolations

    安裝

    pip install claude-agent-sdk

    在 query() 和 ClaudeSDKClient 之間選擇

    Python SDK 提供兩種與 Claude Code 互動的方式:

    快速比較

    功能query()ClaudeSDKClient
    工作階段每次建立新的工作階段重複使用相同的工作階段
    對話單次交換在相同上下文中進行多次交換
    連線自動管理手動控制
    串流輸入✅ 支援✅ 支援
    中斷❌ 不支援✅ 支援
    Hooks❌ 不支援✅ 支援
    自訂工具❌ 不支援✅ 支援
    繼續聊天❌ 每次建立新工作階段✅ 維持對話
    使用情境一次性任務持續對話

    何時使用 query()(每次建立新工作階段)

    最適合:

    • 不需要對話歷史的一次性問題
    • 不需要先前交換上下文的獨立任務
    • 簡單的自動化腳本
    • 當您希望每次都重新開始時

    何時使用 ClaudeSDKClient(持續對話)

    最適合:

    • 繼續對話 - 當您需要 Claude 記住上下文時
    • 後續問題 - 基於先前回應進行延伸
    • 互動式應用程式 - 聊天介面、REPL
    • 回應驅動邏輯 - 當下一步動作取決於 Claude 的回應時
    • 工作階段控制 - 明確管理對話生命週期

    函式

    query()

    為每次與 Claude Code 的互動建立新的工作階段。回傳一個非同步迭代器,在訊息到達時逐一產生訊息。每次呼叫 query() 都會重新開始,不保留先前互動的記憶。

    async def query(
        *,
        prompt: str | AsyncIterable[dict[str, Any]],
        options: ClaudeAgentOptions | None = None
    ) -> AsyncIterator[Message]

    參數

    參數型別說明
    promptstr | AsyncIterable[dict]輸入提示,可以是字串或用於串流模式的非同步可迭代物件
    optionsClaudeAgentOptions | None選用的配置物件(若為 None 則預設為 ClaudeAgentOptions())

    回傳值

    回傳一個 AsyncIterator[Message],從對話中逐一產生訊息。

    範例 - 使用選項

    
    import asyncio
    from claude_agent_sdk import query, ClaudeAgentOptions
    
    async def main():
        options = ClaudeAgentOptions(
            system_prompt="You are an expert Python developer",
            permission_mode='acceptEdits',
            cwd="/home/user/project"
        )
    
        async for message in query(
            prompt="Create a Python web server",
            options=options
        ):
            print(message)
    
    
    asyncio.run(main())

    tool()

    用於定義具有型別安全的 MCP 工具的裝飾器。

    def tool(
        name: str,
        description: str,
        input_schema: type | dict[str, Any]
    ) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]

    參數

    參數型別說明
    namestr工具的唯一識別碼
    descriptionstr人類可讀的工具功能說明
    input_schematype | dict[str, Any]定義工具輸入參數的結構描述(見下方)

    輸入結構描述選項

    1. 簡單型別對應(推薦):

      {"text": str, "count": int, "enabled": bool}
    2. JSON Schema 格式(用於複雜驗證):

      {
          "type": "object",
          "properties": {
              "text": {"type": "string"},
              "count": {"type": "integer", "minimum": 0}
          },
          "required": ["text"]
      }

    回傳值

    一個裝飾器函式,包裝工具實作並回傳一個 SdkMcpTool 實例。

    範例

    from claude_agent_sdk import tool
    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']}!"
            }]
        }

    create_sdk_mcp_server()

    建立一個在您的 Python 應用程式內執行的程序內 MCP 伺服器。

    def create_sdk_mcp_server(
        name: str,
        version: str = "1.0.0",
        tools: list[SdkMcpTool[Any]] | None = None
    ) -> McpSdkServerConfig

    參數

    參數型別預設值說明
    namestr-伺服器的唯一識別碼
    versionstr"1.0.0"伺服器版本字串
    toolslist[SdkMcpTool[Any]] | NoneNone使用 @tool 裝飾器建立的工具函式列表

    回傳值

    回傳一個 McpSdkServerConfig 物件,可傳遞給 ClaudeAgentOptions.mcp_servers。

    範例

    from claude_agent_sdk import tool, create_sdk_mcp_server
    
    @tool("add", "Add two numbers", {"a": float, "b": float})
    async def add(args):
        return {
            "content": [{
                "type": "text",
                "text": f"Sum: {args['a'] + args['b']}"
            }]
        }
    
    @tool("multiply", "Multiply two numbers", {"a": float, "b": float})
    async def multiply(args):
        return {
            "content": [{
                "type": "text",
                "text": f"Product: {args['a'] * args['b']}"
            }]
        }
    
    calculator = create_sdk_mcp_server(
        name="calculator",
        version="2.0.0",
        tools=[add, multiply]  # Pass decorated functions
    )
    
    # Use with Claude
    options = ClaudeAgentOptions(
        mcp_servers={"calc": calculator},
        allowed_tools=["mcp__calc__add", "mcp__calc__multiply"]
    )

    類別

    ClaudeSDKClient

    在多次交換中維持對話工作階段。 這是 TypeScript SDK 的 query() 函式內部運作方式的 Python 等效實作 - 它建立一個可以繼續對話的客戶端物件。

    主要功能

    • 工作階段連續性:在多次 query() 呼叫之間維持對話上下文
    • 相同對話:Claude 記住工作階段中先前的訊息
    • 中斷支援:可以在執行中途停止 Claude
    • 明確的生命週期:您控制工作階段的開始和結束時間
    • 回應驅動流程:可以對回應做出反應並發送後續訊息
    • 自訂工具與 Hooks:支援自訂工具(使用 @tool 裝飾器建立)和 hooks
    class ClaudeSDKClient:
        def __init__(self, options: ClaudeAgentOptions | None = None)
        async def connect(self, prompt: str | AsyncIterable[dict] | None = None) -> None
        async def query(self, prompt: str | AsyncIterable[dict], session_id: str = "default") -> None
        async def receive_messages(self) -> AsyncIterator[Message]
        async def receive_response(self) -> AsyncIterator[Message]
        async def interrupt(self) -> None
        async def rewind_files(self, user_message_uuid: str) -> None
        async def disconnect(self) -> None

    方法

    方法說明
    __init__(options)使用選用配置初始化客戶端
    connect(prompt)使用選用的初始提示或訊息串流連線到 Claude
    query(prompt, session_id)在串流模式中發送新請求
    receive_messages()以非同步迭代器接收來自 Claude 的所有訊息
    receive_response()接收訊息直到並包含 ResultMessage
    interrupt()發送中斷信號(僅在串流模式中有效)
    rewind_files(user_message_uuid)將檔案還原到指定使用者訊息時的狀態。需要 enable_file_checkpointing=True。請參閱檔案檢查點

    上下文管理器支援

    客戶端可以作為非同步上下文管理器使用,以自動管理連線:

    async with ClaudeSDKClient() as client:
        await client.query("Hello Claude")
        async for message in client.receive_response():
            print(message)

    重要: 在迭代訊息時,避免使用 break 提前退出,因為這可能導致 asyncio 清理問題。相反,讓迭代自然完成,或使用旗標來追蹤您何時找到所需的內容。

    範例 - 繼續對話

    import asyncio
    from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage
    
    async def main():
        async with ClaudeSDKClient() as client:
            # First question
            await client.query("What's the capital of France?")
    
            # Process response
            async for message in client.receive_response():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, TextBlock):
                            print(f"Claude: {block.text}")
    
            # Follow-up question - Claude remembers the previous context
            await client.query("What's the population of that city?")
    
            async for message in client.receive_response():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, TextBlock):
                            print(f"Claude: {block.text}")
    
            # Another follow-up - still in the same conversation
            await client.query("What are some famous landmarks there?")
    
            async for message in client.receive_response():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, TextBlock):
                            print(f"Claude: {block.text}")
    
    asyncio.run(main())

    範例 - 使用 ClaudeSDKClient 進行串流輸入

    import asyncio
    from claude_agent_sdk import ClaudeSDKClient
    
    async def message_stream():
        """Generate messages dynamically."""
        yield {"type": "text", "text": "Analyze the following data:"}
        await asyncio.sleep(0.5)
        yield {"type": "text", "text": "Temperature: 25°C"}
        await asyncio.sleep(0.5)
        yield {"type": "text", "text": "Humidity: 60%"}
        await asyncio.sleep(0.5)
        yield {"type": "text", "text": "What patterns do you see?"}
    
    async def main():
        async with ClaudeSDKClient() as client:
            # Stream input to Claude
            await client.query(message_stream())
    
            # Process response
            async for message in client.receive_response():
                print(message)
    
            # Follow-up in same session
            await client.query("Should we be concerned about these readings?")
    
            async for message in client.receive_response():
                print(message)
    
    asyncio.run(main())

    範例 - 使用中斷

    import asyncio
    from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
    
    async def interruptible_task():
        options = ClaudeAgentOptions(
            allowed_tools=["Bash"],
            permission_mode="acceptEdits"
        )
    
        async with ClaudeSDKClient(options=options) as client:
            # Start a long-running task
            await client.query("Count from 1 to 100 slowly")
    
            # Let it run for a bit
            await asyncio.sleep(2)
    
            # Interrupt the task
            await client.interrupt()
            print("Task interrupted!")
    
            # Send a new command
            await client.query("Just say hello instead")
    
            async for message in client.receive_response():
                # Process the new response
                pass
    
    asyncio.run(interruptible_task())

    範例 - 進階權限控制

    from claude_agent_sdk import (
        ClaudeSDKClient,
        ClaudeAgentOptions
    )
    from claude_agent_sdk.types import PermissionResultAllow, PermissionResultDeny
    
    async def custom_permission_handler(
        tool_name: str,
        input_data: dict,
        context: dict
    ) -> PermissionResultAllow | PermissionResultDeny:
        """Custom logic for tool permissions."""
    
        # Block writes to system directories
        if tool_name == "Write" and input_data.get("file_path", "").startswith("/system/"):
            return PermissionResultDeny(
                message="System directory write not allowed",
                interrupt=True
            )
    
        # Redirect sensitive file operations
        if tool_name in ["Write", "Edit"] and "config" in input_data.get("file_path", ""):
            safe_path = f"./sandbox/{input_data['file_path']}"
            return PermissionResultAllow(
                updated_input={**input_data, "file_path": safe_path}
            )
    
        # Allow everything else
        return PermissionResultAllow(updated_input=input_data)
    
    async def main():
        options = ClaudeAgentOptions(
            can_use_tool=custom_permission_handler,
            allowed_tools=["Read", "Write", "Edit"]
        )
    
        async with ClaudeSDKClient(options=options) as client:
            await client.query("Update the system config file")
    
            async for message in client.receive_response():
                # Will use sandbox path instead
                print(message)
    
    asyncio.run(main())

    型別

    SdkMcpTool

    使用 @tool 裝飾器建立的 SDK MCP 工具定義。

    @dataclass
    class SdkMcpTool(Generic[T]):
        name: str
        description: str
        input_schema: type[T] | dict[str, Any]
        handler: Callable[[T], Awaitable[dict[str, Any]]]
    屬性型別說明
    namestr工具的唯一識別碼
    descriptionstr人類可讀的說明
    input_schematype[T] | dict[str, Any]用於輸入驗證的結構描述
    handlerCallable[[T], Awaitable[dict[str, Any]]]處理工具執行的非同步函式

    ClaudeAgentOptions

    Claude Code 查詢的配置資料類別。

    @dataclass
    class ClaudeAgentOptions:
        tools: list[str] | ToolsPreset | None = None
        allowed_tools: list[str] = field(default_factory=list)
        system_prompt: str | SystemPromptPreset | None = None
        mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
        permission_mode: PermissionMode | None = None
        continue_conversation: bool = False
        resume: str | None = None
        max_turns: int | None = None
        max_budget_usd: float | None = None
        disallowed_tools: list[str] = field(default_factory=list)
        model: str | None = None
        fallback_model: str | None = None
        betas: list[SdkBeta] = field(default_factory=list)
        output_format: OutputFormat | None = None
        permission_prompt_tool_name: str | None = None
        cwd: str | Path | None = None
        cli_path: str | Path | None = None
        settings: str | None = None
        add_dirs: list[str | Path] = field(default_factory=list)
        env: dict[str, str] = field(default_factory=dict)
        extra_args: dict[str, str | None] = field(default_factory=dict)
        max_buffer_size: int | None = None
        debug_stderr: Any = sys.stderr  # Deprecated
        stderr: Callable[[str], None] | None = None
        can_use_tool: CanUseTool | None = None
        hooks: dict[HookEvent, list[HookMatcher]] | None = None
        user: str | None = None
        include_partial_messages: bool = False
        fork_session: bool = False
        agents: dict[str, AgentDefinition] | None = None
        setting_sources: list[SettingSource] | None = None
        max_thinking_tokens: int | None = None
    屬性型別預設值說明
    toolslist[str] | ToolsPreset | NoneNone工具配置。使用 {"type": "preset", "preset": "claude_code"} 來取得 Claude Code 的預設工具
    allowed_toolslist[str][]允許的工具名稱列表
    system_promptstr | SystemPromptPreset | NoneNone系統提示配置。傳入字串作為自訂提示,或使用 {"type": "preset", "preset": "claude_code"} 來取得 Claude Code 的系統提示。加入 以擴展預設值

    OutputFormat

    結構化輸出驗證的配置。

    class OutputFormat(TypedDict):
        type: Literal["json_schema"]
        schema: dict[str, Any]
    欄位必填說明
    type是必須為 "json_schema" 以進行 JSON Schema 驗證
    schema是用於輸出驗證的 JSON Schema 定義

    SystemPromptPreset

    使用 Claude Code 預設系統提示並可選擇附加內容的配置。

    class SystemPromptPreset(TypedDict):
        type: Literal["preset"]
        preset: Literal["claude_code"]
        append: NotRequired[str]
    欄位必填說明
    type是必須為 "preset" 以使用預設系統提示
    preset是必須為 "claude_code" 以使用 Claude Code 的系統提示
    append否附加到預設系統提示的額外指令

    SettingSource

    控制 SDK 從哪些檔案系統配置來源載入設定。

    SettingSource = Literal["user", "project", "local"]
    值說明位置
    "user"全域使用者設定~/.claude/settings.json
    "project"共享專案設定(版本控制).claude/settings.json
    "local"本地專案設定(gitignored).claude/settings.local.json

    預設行為

    當 setting_sources 被省略或為 None 時,SDK 不會載入任何檔案系統設定。這為 SDK 應用程式提供了隔離性。

    為什麼使用 setting_sources?

    載入所有檔案系統設定(舊版行為):

    # Load all settings like SDK v0.0.x did
    from claude_agent_sdk import query, ClaudeAgentOptions
    
    async for message in query(
        prompt="Analyze this code",
        options=ClaudeAgentOptions(
            setting_sources=["user", "project", "local"]  # Load all settings
        )
    ):
        print(message)

    僅載入特定設定來源:

    # Load only project settings, ignore user and local
    async for message in query(
        prompt="Run CI checks",
        options=ClaudeAgentOptions(
            setting_sources=["project"]  # Only .claude/settings.json
        )
    ):
        print(message)

    測試和 CI 環境:

    # Ensure consistent behavior in CI by excluding local settings
    async for message in query(
        prompt="Run tests",
        options=ClaudeAgentOptions(
            setting_sources=["project"],  # Only team-shared settings
            permission_mode="bypassPermissions"
        )
    ):
        print(message)

    僅 SDK 應用程式:

    # Define everything programmatically (default behavior)
    # No filesystem dependencies - setting_sources defaults to None
    async for message in query(
        prompt="Review this PR",
        options=ClaudeAgentOptions(
            # setting_sources=None is the default, no need to specify
            agents={ /* ... */ },
            mcp_servers={ /* ... */ },
            allowed_tools=["Read", "Grep", "Glob"]
        )
    ):
        print(message)

    載入 CLAUDE.md 專案指令:

    # Load project settings to include CLAUDE.md files
    async for message in query(
        prompt="Add a new feature following project conventions",
        options=ClaudeAgentOptions(
            system_prompt={
                "type": "preset",
                "preset": "claude_code"  # Use Claude Code's system prompt
            },
            setting_sources=["project"],  # Required to load CLAUDE.md from project
            allowed_tools=["Read", "Write", "Edit"]
        )
    ):
        print(message)

    設定優先順序

    當載入多個來源時,設定會按以下優先順序合併(從高到低):

    1. 本地設定(.claude/settings.local.json)
    2. 專案設定(.claude/settings.json)
    3. 使用者設定(~/.claude/settings.json)

    程式化選項(如 agents、allowed_tools)始終覆蓋檔案系統設定。

    AgentDefinition

    以程式方式定義的子代理配置。

    @dataclass
    class AgentDefinition:
        description: str
        prompt: str
        tools: list[str] | None = None
        model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
    欄位必填說明
    description是描述何時使用此代理的自然語言說明
    tools否允許的工具名稱陣列。若省略,則繼承所有工具
    prompt是代理的系統提示
    model否此代理的模型覆蓋。若省略,則使用主模型

    PermissionMode

    控制工具執行的權限模式。

    PermissionMode = Literal[
        "default",           # Standard permission behavior
        "acceptEdits",       # Auto-accept file edits
        "plan",              # Planning mode - no execution
        "bypassPermissions"  # Bypass all permission checks (use with caution)
    ]

    CanUseTool

    工具權限回呼函式的型別別名。

    CanUseTool = Callable[
        [str, dict[str, Any], ToolPermissionContext],
        Awaitable[PermissionResult]
    ]

    回呼接收:

    • tool_name:被呼叫的工具名稱
    • input_data:工具的輸入參數
    • context:包含額外資訊的 ToolPermissionContext

    回傳 PermissionResult(PermissionResultAllow 或 PermissionResultDeny)。

    ToolPermissionContext

    傳遞給工具權限回呼的上下文資訊。

    @dataclass
    class ToolPermissionContext:
        signal: Any | None = None  # Future: abort signal support
        suggestions: list[PermissionUpdate] = field(default_factory=list)
    欄位型別說明
    signalAny | None保留供未來中止信號支援使用
    suggestionslist[PermissionUpdate]來自 CLI 的權限更新建議

    PermissionResult

    權限回呼結果的聯合型別。

    PermissionResult = PermissionResultAllow | PermissionResultDeny

    PermissionResultAllow

    表示應允許工具呼叫的結果。

    @dataclass
    class PermissionResultAllow:
        behavior: Literal["allow"] = "allow"
        updated_input: dict[str, Any] | None = None
        updated_permissions: list[PermissionUpdate] | None = None
    欄位型別預設值說明
    behaviorLiteral["allow"]"allow"必須為 "allow"
    updated_inputdict[str, Any] | NoneNone用於替代原始輸入的修改後輸入
    updated_permissionslist[PermissionUpdate] | NoneNone要套用的權限更新

    PermissionResultDeny

    表示應拒絕工具呼叫的結果。

    @dataclass
    class PermissionResultDeny:
        behavior: Literal["deny"] = "deny"
        message: str = ""
        interrupt: bool = False
    欄位型別預設值說明
    behaviorLiteral["deny"]"deny"必須為 "deny"
    messagestr""說明工具被拒絕原因的訊息
    interruptboolFalse是否中斷目前的執行

    PermissionUpdate

    以程式方式更新權限的設定。

    @dataclass
    class PermissionUpdate:
        type: Literal[
            "addRules",
            "replaceRules",
            "removeRules",
            "setMode",
            "addDirectories",
            "removeDirectories",
        ]
        rules: list[PermissionRuleValue] | None = None
        behavior: Literal["allow", "deny", "ask"] | None = None
        mode: PermissionMode | None = None
        directories: list[str] | None = None
        destination: Literal["userSettings", "projectSettings", "localSettings", "session"] | None = None
    欄位型別說明
    typeLiteral[...]權限更新操作的類型
    ruleslist[PermissionRuleValue] | None用於新增/替換/移除操作的規則
    behaviorLiteral["allow", "deny", "ask"] | None基於規則操作的行為
    modePermissionMode | NonesetMode 操作的模式
    directorieslist[str] | None

    SdkBeta

    SDK 測試版功能的字面值型別。

    SdkBeta = Literal["context-1m-2025-08-07"]

    與 ClaudeAgentOptions 中的 betas 欄位一起使用以啟用測試版功能。

    McpSdkServerConfig

    使用 create_sdk_mcp_server() 建立的 SDK MCP 伺服器設定。

    class McpSdkServerConfig(TypedDict):
        type: Literal["sdk"]
        name: str
        instance: Any  # MCP Server instance

    McpServerConfig

    MCP 伺服器設定的聯合型別。

    McpServerConfig = McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig

    McpStdioServerConfig

    class McpStdioServerConfig(TypedDict):
        type: NotRequired[Literal["stdio"]]  # Optional for backwards compatibility
        command: str
        args: NotRequired[list[str]]
        env: NotRequired[dict[str, str]]

    McpSSEServerConfig

    class McpSSEServerConfig(TypedDict):
        type: Literal["sse"]
        url: str
        headers: NotRequired[dict[str, str]]

    McpHttpServerConfig

    class McpHttpServerConfig(TypedDict):
        type: Literal["http"]
        url: str
        headers: NotRequired[dict[str, str]]

    SdkPluginConfig

    在 SDK 中載入外掛程式的設定。

    class SdkPluginConfig(TypedDict):
        type: Literal["local"]
        path: str
    欄位型別說明
    typeLiteral["local"]必須為 "local"(目前僅支援本地外掛程式)
    pathstr外掛程式目錄的絕對或相對路徑

    範例:

    plugins=[
        {"type": "local", "path": "./my-plugin"},
        {"type": "local", "path": "/absolute/path/to/plugin"}
    ]

    有關建立和使用外掛程式的完整資訊,請參閱外掛程式。

    訊息型別

    Message

    所有可能訊息的聯合型別。

    Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage | StreamEvent

    UserMessage

    使用者輸入訊息。

    @dataclass
    class UserMessage:
        content: str | list[ContentBlock]

    AssistantMessage

    包含內容區塊的助理回應訊息。

    @dataclass
    class AssistantMessage:
        content: list[ContentBlock]
        model: str

    SystemMessage

    包含中繼資料的系統訊息。

    @dataclass
    class SystemMessage:
        subtype: str
        data: dict[str, Any]

    ResultMessage

    包含成本和使用量資訊的最終結果訊息。

    @dataclass
    class ResultMessage:
        subtype: str
        duration_ms: int
        duration_api_ms: int
        is_error: bool
        num_turns: int
        session_id: str
        total_cost_usd: float | None = None
        usage: dict[str, Any] | None = None
        result: str | None = None
        structured_output: Any = None

    StreamEvent

    串流期間部分訊息更新的串流事件。僅在 ClaudeAgentOptions 中設定 include_partial_messages=True 時才會接收。

    @dataclass
    class StreamEvent:
        uuid: str
        session_id: str
        event: dict[str, Any]  # The raw Anthropic API stream event
        parent_tool_use_id: str | None = None
    欄位型別說明
    uuidstr此事件的唯一識別碼
    session_idstr工作階段識別碼
    eventdict[str, Any]原始 Anthropic API 串流事件資料
    parent_tool_use_idstr | None如果此事件來自子代理,則為父工具使用 ID

    內容區塊型別

    ContentBlock

    所有內容區塊的聯合型別。

    ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock

    TextBlock

    文字內容區塊。

    @dataclass
    class TextBlock:
        text: str

    ThinkingBlock

    思考內容區塊(適用於具有思考能力的模型)。

    @dataclass
    class ThinkingBlock:
        thinking: str
        signature: str

    ToolUseBlock

    工具使用請求區塊。

    @dataclass
    class ToolUseBlock:
        id: str
        name: str
        input: dict[str, Any]

    ToolResultBlock

    工具執行結果區塊。

    @dataclass
    class ToolResultBlock:
        tool_use_id: str
        content: str | list[dict[str, Any]] | None = None
        is_error: bool | None = None

    錯誤型別

    ClaudeSDKError

    所有 SDK 錯誤的基礎例外類別。

    class ClaudeSDKError(Exception):
        """Base error for Claude SDK."""

    CLINotFoundError

    當 Claude Code CLI 未安裝或找不到時引發。

    class CLINotFoundError(CLIConnectionError):
        def __init__(self, message: str = "Claude Code not found", cli_path: str | None = None):
            """
            Args:
                message: Error message (default: "Claude Code not found")
                cli_path: Optional path to the CLI that was not found
            """

    CLIConnectionError

    當連線至 Claude Code 失敗時引發。

    class CLIConnectionError(ClaudeSDKError):
        """Failed to connect to Claude Code."""

    ProcessError

    當 Claude Code 程序失敗時引發。

    class ProcessError(ClaudeSDKError):
        def __init__(self, message: str, exit_code: int | None = None, stderr: str | None = None):
            self.exit_code = exit_code
            self.stderr = stderr

    CLIJSONDecodeError

    當 JSON 解析失敗時引發。

    class CLIJSONDecodeError(ClaudeSDKError):
        def __init__(self, line: str, original_error: Exception):
            """
            Args:
                line: The line that failed to parse
                original_error: The original JSON decode exception
            """
            self.line = line
            self.original_error = original_error

    Hook 型別

    有關使用 Hook 的完整指南,包括範例和常見模式,請參閱 Hook 指南。

    HookEvent

    支援的 Hook 事件型別。請注意,由於設定限制,Python SDK 不支援 SessionStart、SessionEnd 和 Notification Hook。

    HookEvent = Literal[
        "PreToolUse",      # Called before tool execution
        "PostToolUse",     # Called after tool execution
        "UserPromptSubmit", # Called when user submits a prompt
        "Stop",            # Called when stopping execution
        "SubagentStop",    # Called when a subagent stops
        "PreCompact"       # Called before message compaction
    ]

    HookCallback

    Hook 回呼函式的型別定義。

    HookCallback = Callable[
        [dict[str, Any], str | None, HookContext],
        Awaitable[dict[str, Any]]
    ]

    參數:

    • input_data:Hook 特定的輸入資料(請參閱 Hook 指南)
    • tool_use_id:可選的工具使用識別碼(用於工具相關的 Hook)
    • context:包含額外資訊的 Hook 上下文

    回傳一個可能包含以下內容的字典:

    • decision:"block" 以阻止該動作
    • systemMessage:要新增到記錄中的系統訊息
    • hookSpecificOutput:Hook 特定的輸出資料

    HookContext

    傳遞給 Hook 回呼的上下文資訊。

    @dataclass
    class HookContext:
        signal: Any | None = None  # Future: abort signal support

    HookMatcher

    用於將 Hook 匹配到特定事件或工具的設定。

    @dataclass
    class HookMatcher:
        matcher: str | None = None        # Tool name or pattern to match (e.g., "Bash", "Write|Edit")
        hooks: list[HookCallback] = field(default_factory=list)  # List of callbacks to execute
        timeout: float | None = None        # Timeout in seconds for all hooks in this matcher (default: 60)

    HookInput

    所有 Hook 輸入型別的聯合型別。實際型別取決於 hook_event_name 欄位。

    HookInput = (
        PreToolUseHookInput
        | PostToolUseHookInput
        | UserPromptSubmitHookInput
        | StopHookInput
        | SubagentStopHookInput
        | PreCompactHookInput
    )

    BaseHookInput

    所有 Hook 輸入型別中存在的基礎欄位。

    class BaseHookInput(TypedDict):
        session_id: str
        transcript_path: str
        cwd: str
        permission_mode: NotRequired[str]
    欄位型別說明
    session_idstr目前工作階段識別碼
    transcript_pathstr工作階段記錄檔案的路徑
    cwdstr目前工作目錄
    permission_modestr(可選)目前的權限模式

    PreToolUseHookInput

    PreToolUse Hook 事件的輸入資料。

    class PreToolUseHookInput(BaseHookInput):
        hook_event_name: Literal["PreToolUse"]
        tool_name: str
        tool_input: dict[str, Any]
    欄位型別說明
    hook_event_nameLiteral["PreToolUse"]始終為 "PreToolUse"
    tool_namestr即將執行的工具名稱
    tool_inputdict[str, Any]工具的輸入參數

    PostToolUseHookInput

    PostToolUse Hook 事件的輸入資料。

    class PostToolUseHookInput(BaseHookInput):
        hook_event_name: Literal["PostToolUse"]
        tool_name: str
        tool_input: dict[str, Any]
        tool_response: Any
    欄位型別說明
    hook_event_nameLiteral["PostToolUse"]始終為 "PostToolUse"
    tool_namestr已執行的工具名稱
    tool_inputdict[str, Any]使用的輸入參數
    tool_responseAny工具執行的回應

    UserPromptSubmitHookInput

    UserPromptSubmit Hook 事件的輸入資料。

    class UserPromptSubmitHookInput(BaseHookInput):
        hook_event_name: Literal["UserPromptSubmit"]
        prompt: str
    欄位型別說明
    hook_event_nameLiteral["UserPromptSubmit"]始終為 "UserPromptSubmit"
    promptstr使用者提交的提示

    StopHookInput

    Stop Hook 事件的輸入資料。

    class StopHookInput(BaseHookInput):
        hook_event_name: Literal["Stop"]
        stop_hook_active: bool
    欄位型別說明
    hook_event_nameLiteral["Stop"]始終為 "Stop"
    stop_hook_activebool停止 Hook 是否處於活動狀態

    SubagentStopHookInput

    SubagentStop Hook 事件的輸入資料。

    class SubagentStopHookInput(BaseHookInput):
        hook_event_name: Literal["SubagentStop"]
        stop_hook_active: bool
    欄位型別說明
    hook_event_nameLiteral["SubagentStop"]始終為 "SubagentStop"
    stop_hook_activebool停止 Hook 是否處於活動狀態

    PreCompactHookInput

    PreCompact Hook 事件的輸入資料。

    class PreCompactHookInput(BaseHookInput):
        hook_event_name: Literal["PreCompact"]
        trigger: Literal["manual", "auto"]
        custom_instructions: str | None
    欄位型別說明
    hook_event_nameLiteral["PreCompact"]始終為 "PreCompact"
    triggerLiteral["manual", "auto"]觸發壓縮的原因
    custom_instructionsstr | None壓縮的自訂指令

    HookJSONOutput

    Hook 回呼回傳值的聯合型別。

    HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput

    SyncHookJSONOutput

    包含控制和決策欄位的同步 Hook 輸出。

    class SyncHookJSONOutput(TypedDict):
        # Control fields
        continue_: NotRequired[bool]      # Whether to proceed (default: True)
        suppressOutput: NotRequired[bool] # Hide stdout from transcript
        stopReason: NotRequired[str]      # Message when continue is False
    
        # Decision fields
        decision: NotRequired[Literal["block"]]
        systemMessage: NotRequired[str]   # Warning message for user
        reason: NotRequired[str]          # Feedback for Claude
    
        # Hook-specific output
        hookSpecificOutput: NotRequired[dict[str, Any]]

    在 Python 程式碼中使用 continue_(帶底線)。傳送至 CLI 時會自動轉換為 continue。

    AsyncHookJSONOutput

    延遲 Hook 執行的非同步 Hook 輸出。

    class AsyncHookJSONOutput(TypedDict):
        async_: Literal[True]             # Set to True to defer execution
        asyncTimeout: NotRequired[int]    # Timeout in milliseconds

    在 Python 程式碼中使用 async_(帶底線)。傳送至 CLI 時會自動轉換為 async。

    Hook 使用範例

    此範例註冊了兩個 Hook:一個阻止危險的 bash 命令(如 rm -rf /),另一個記錄所有工具使用以供稽核。安全 Hook 僅在 Bash 命令上執行(透過 matcher),而記錄 Hook 在所有工具上執行。

    from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
    from typing import Any
    
    async def validate_bash_command(
        input_data: dict[str, Any],
        tool_use_id: str | None,
        context: HookContext
    ) -> dict[str, Any]:
        """Validate and potentially block dangerous bash commands."""
        if input_data['tool_name'] == 'Bash':
            command = input_data['tool_input'].get('command', '')
            if 'rm -rf /' in command:
                return {
                    'hookSpecificOutput': {
                        'hookEventName': 'PreToolUse',
                        'permissionDecision': 'deny',
                        'permissionDecisionReason': 'Dangerous command blocked'
                    }
                }
        return {}
    
    async def log_tool_use(
        input_data: dict[str, Any],
        tool_use_id: str | None,
        context: HookContext
    ) -> dict[str, Any]:
        """Log all tool usage for auditing."""
        print(f"Tool used: {input_data.get('tool_name')}")
        return {}
    
    options = ClaudeAgentOptions(
        hooks={
            'PreToolUse': [
                HookMatcher(matcher='Bash', hooks=[validate_bash_command], timeout=120),  # 2 min for validation
                HookMatcher(hooks=[log_tool_use])  # Applies to all tools (default 60s timeout)
            ],
            'PostToolUse': [
                HookMatcher(hooks=[log_tool_use])
            ]
        }
    )
    
    async for message in query(
        prompt="Analyze this codebase",
        options=options
    ):
        print(message)

    工具輸入/輸出型別

    所有內建 Claude Code 工具的輸入/輸出結構描述文件。雖然 Python SDK 不會將這些匯出為型別,但它們代表訊息中工具輸入和輸出的結構。

    Task

    工具名稱: Task

    輸入:

    {
        "description": str,      # A short (3-5 word) description of the task
        "prompt": str,           # The task for the agent to perform
        "subagent_type": str     # The type of specialized agent to use
    }

    輸出:

    {
        "result": str,                    # Final result from the subagent
        "usage": dict | None,             # Token usage statistics
        "total_cost_usd": float | None,  # Total cost in USD
        "duration_ms": int | None         # Execution duration in milliseconds
    }

    AskUserQuestion

    工具名稱: AskUserQuestion

    在執行期間向使用者詢問澄清問題。有關使用詳情,請參閱處理核准和使用者輸入。

    輸入:

    {
        "questions": [                    # Questions to ask the user (1-4 questions)
            {
                "question": str,          # The complete question to ask the user
                "header": str,            # Very short label displayed as a chip/tag (max 12 chars)
                "options": [              # The available choices (2-4 options)
                    {
                        "label": str,         # Display text for this option (1-5 words)
                        "description": str    # Explanation of what this option means
                    }
                ],
                "multiSelect": bool       # Set to true to allow multiple selections
            }
        ],
        "answers": dict | None            # User answers populated by the permission system
    }

    輸出:

    {
        "questions": [                    # The questions that were asked
            {
                "question": str,
                "header": str,
                "options": [{"label": str, "description": str}],
                "multiSelect": bool
            }
        ],
        "answers": dict[str, str]         # Maps question text to answer string
                                          # Multi-select answers are comma-separated
    }

    Bash

    工具名稱: Bash

    輸入:

    {
        "command": str,                  # The command to execute
        "timeout": int | None,           # Optional timeout in milliseconds (max 600000)
        "description": str | None,       # Clear, concise description (5-10 words)
        "run_in_background": bool | None # Set to true to run in background
    }

    輸出:

    {
        "output": str,              # Combined stdout and stderr output
        "exitCode": int,            # Exit code of the command
        "killed": bool | None,      # Whether command was killed due to timeout
        "shellId": str | None       # Shell ID for background processes
    }

    Edit

    工具名稱: Edit

    輸入:

    {
        "file_path": str,           # The absolute path to the file to modify
        "old_string": str,          # The text to replace
        "new_string": str,          # The text to replace it with
        "replace_all": bool | None  # Replace all occurrences (default False)
    }

    輸出:

    {
        "message": str,      # Confirmation message
        "replacements": int, # Number of replacements made
        "file_path": str     # File path that was edited
    }

    Read

    工具名稱: Read

    輸入:

    {
        "file_path": str,       # The absolute path to the file to read
        "offset": int | None,   # The line number to start reading from
        "limit": int | None     # The number of lines to read
    }

    輸出(文字檔案):

    {
        "content": str,         # File contents with line numbers
        "total_lines": int,     # Total number of lines in file
        "lines_returned": int   # Lines actually returned
    }

    輸出(圖片):

    {
        "image": str,       # Base64 encoded image data
        "mime_type": str,   # Image MIME type
        "file_size": int    # File size in bytes
    }

    Write

    工具名稱: Write

    輸入:

    {
        "file_path": str,  # The absolute path to the file to write
        "content": str     # The content to write to the file
    }

    輸出:

    {
        "message": str,        # Success message
        "bytes_written": int,  # Number of bytes written
        "file_path": str       # File path that was written
    }

    Glob

    工具名稱: Glob

    輸入:

    {
        "pattern": str,       # The glob pattern to match files against
        "path": str | None    # The directory to search in (defaults to cwd)
    }

    輸出:

    {
        "matches": list[str],  # Array of matching file paths
        "count": int,          # Number of matches found
        "search_path": str     # Search directory used
    }

    Grep

    工具名稱: Grep

    輸入:

    {
        "pattern": str,                    # The regular expression pattern
        "path": str | None,                # File or directory to search in
        "glob": str | None,                # Glob pattern to filter files
        "type": str | None,                # File type to search
        "output_mode": str | None,         # "content", "files_with_matches", or "count"
        "-i": bool | None,                 # Case insensitive search
        "-n": bool | None,                 # Show line numbers
        "-B": int | None,                  # Lines to show before each match
        "-A": int | None,                  # Lines to show after each match
        "-C": int | None,                  # Lines to show before and after
        "head_limit": int | None,          # Limit output to first N lines/entries
        "multiline": bool | None           # Enable multiline mode
    }

    輸出(content 模式):

    {
        "matches": [
            {
                "file": str,
                "line_number": int | None,
                "line": str,
                "before_context": list[str] | None,
                "after_context": list[str] | None
            }
        ],
        "total_matches": int
    }

    輸出(files_with_matches 模式):

    {
        "files": list[str],  # Files containing matches
        "count": int         # Number of files with matches
    }

    NotebookEdit

    工具名稱: NotebookEdit

    輸入:

    {
        "notebook_path": str,                     # Absolute path to the Jupyter notebook
        "cell_id": str | None,                    # The ID of the cell to edit
        "new_source": str,                        # The new source for the cell
        "cell_type": "code" | "markdown" | None,  # The type of the cell
        "edit_mode": "replace" | "insert" | "delete" | None  # Edit operation type
    }

    輸出:

    {
        "message": str,                              # Success message
        "edit_type": "replaced" | "inserted" | "deleted",  # Type of edit performed
        "cell_id": str | None,                       # Cell ID that was affected
        "total_cells": int                           # Total cells in notebook after edit
    }

    WebFetch

    工具名稱: WebFetch

    輸入:

    {
        "url": str,     # The URL to fetch content from
        "prompt": str   # The prompt to run on the fetched content
    }

    輸出:

    {
        "response": str,           # AI model's response to the prompt
        "url": str,                # URL that was fetched
        "final_url": str | None,   # Final URL after redirects
        "status_code": int | None  # HTTP status code
    }

    WebSearch

    工具名稱: WebSearch

    輸入:

    {
        "query": str,                        # The search query to use
        "allowed_domains": list[str] | None, # Only include results from these domains
        "blocked_domains": list[str] | None  # Never include results from these domains
    }

    輸出:

    {
        "results": [
            {
                "title": str,
                "url": str,
                "snippet": str,
                "metadata": dict | None
            }
        ],
        "total_results": int,
        "query": str
    }

    TodoWrite

    工具名稱: TodoWrite

    輸入:

    {
        "todos": [
            {
                "content": str,                              # The task description
                "status": "pending" | "in_progress" | "completed",  # Task status
                "activeForm": str                            # Active form of the description
            }
        ]
    }

    輸出:

    {
        "message": str,  # Success message
        "stats": {
            "total": int,
            "pending": int,
            "in_progress": int,
            "completed": int
        }
    }

    BashOutput

    工具名稱: BashOutput

    輸入:

    {
        "bash_id": str,       # The ID of the background shell
        "filter": str | None  # Optional regex to filter output lines
    }

    輸出:

    {
        "output": str,                                      # New output since last check
        "status": "running" | "completed" | "failed",       # Current shell status
        "exitCode": int | None                              # Exit code when completed
    }

    KillBash

    工具名稱: KillBash

    輸入:

    {
        "shell_id": str  # The ID of the background shell to kill
    }

    輸出:

    {
        "message": str,  # Success message
        "shell_id": str  # ID of the killed shell
    }

    ExitPlanMode

    工具名稱: ExitPlanMode

    輸入:

    {
        "plan": str  # The plan to run by the user for approval
    }

    輸出:

    {
        "message": str,          # Confirmation message
        "approved": bool | None  # Whether user approved the plan
    }

    ListMcpResources

    工具名稱: ListMcpResources

    輸入:

    {
        "server": str | None  # Optional server name to filter resources by
    }

    輸出:

    {
        "resources": [
            {
                "uri": str,
                "name": str,
                "description": str | None,
                "mimeType": str | None,
                "server": str
            }
        ],
        "total": int
    }

    ReadMcpResource

    工具名稱: ReadMcpResource

    輸入:

    {
        "server": str,  # The MCP server name
        "uri": str      # The resource URI to read
    }

    輸出:

    {
        "contents": [
            {
                "uri": str,
                "mimeType": str | None,
                "text": str | None,
                "blob": str | None
            }
        ],
        "server": str
    }

    使用 ClaudeSDKClient 的進階功能

    建立連續對話介面

    from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, AssistantMessage, TextBlock
    import asyncio
    
    class ConversationSession:
        """Maintains a single conversation session with Claude."""
    
        def __init__(self, options: ClaudeAgentOptions = None):
            self.client = ClaudeSDKClient(options)
            self.turn_count = 0
    
        async def start(self):
            await self.client.connect()
            print("Starting conversation session. Claude will remember context.")
            print("Commands: 'exit' to quit, 'interrupt' to stop current task, 'new' for new session")
    
            while True:
                user_input = input(f"\n[Turn {self.turn_count + 1}] You: ")
    
                if user_input.lower() == 'exit':
                    break
                elif user_input.lower() == 'interrupt':
                    await self.client.interrupt()
                    print("Task interrupted!")
                    continue
                elif user_input.lower() == 'new':
                    # Disconnect and reconnect for a fresh session
                    await self.client.disconnect()
                    await self.client.connect()
                    self.turn_count = 0
                    print("Started new conversation session (previous context cleared)")
                    continue
    
                # Send message - Claude remembers all previous messages in this session
                await self.client.query(user_input)
                self.turn_count += 1
    
                # Process response
                print(f"[Turn {self.turn_count}] Claude: ", end="")
                async for message in self.client.receive_response():
                    if isinstance(message, AssistantMessage):
                        for block in message.content:
                            if isinstance(block, TextBlock):
                                print(block.text, end="")
                print()  # New line after response
    
            await self.client.disconnect()
            print(f"Conversation ended after {self.turn_count} turns.")
    
    async def main():
        options = ClaudeAgentOptions(
            allowed_tools=["Read", "Write", "Bash"],
            permission_mode="acceptEdits"
        )
        session = ConversationSession(options)
        await session.start()
    
    # Example conversation:
    # Turn 1 - You: "Create a file called hello.py"
    # Turn 1 - Claude: "I'll create a hello.py file for you..."
    # Turn 2 - You: "What's in that file?"
    # Turn 2 - Claude: "The hello.py file I just created contains..." (remembers!)
    # Turn 3 - You: "Add a main function to it"
    # Turn 3 - Claude: "I'll add a main function to hello.py..." (knows which file!)
    
    asyncio.run(main())

    使用 Hook 進行行為修改

    from claude_agent_sdk import (
        ClaudeSDKClient,
        ClaudeAgentOptions,
        HookMatcher,
        HookContext
    )
    import asyncio
    from typing import Any
    
    async def pre_tool_logger(
        input_data: dict[str, Any],
        tool_use_id: str | None,
        context: HookContext
    ) -> dict[str, Any]:
        """Log all tool usage before execution."""
        tool_name = input_data.get('tool_name', 'unknown')
        print(f"[PRE-TOOL] About to use: {tool_name}")
    
        # You can modify or block the tool execution here
        if tool_name == "Bash" and "rm -rf" in str(input_data.get('tool_input', {})):
            return {
                'hookSpecificOutput': {
                    'hookEventName': 'PreToolUse',
                    'permissionDecision': 'deny',
                    'permissionDecisionReason': 'Dangerous command blocked'
                }
            }
        return {}
    
    async def post_tool_logger(
        input_data: dict[str, Any],
        tool_use_id: str | None,
        context: HookContext
    ) -> dict[str, Any]:
        """Log results after tool execution."""
        tool_name = input_data.get('tool_name', 'unknown')
        print(f"[POST-TOOL] Completed: {tool_name}")
        return {}
    
    async def user_prompt_modifier(
        input_data: dict[str, Any],
        tool_use_id: str | None,
        context: HookContext
    ) -> dict[str, Any]:
        """Add context to user prompts."""
        original_prompt = input_data.get('prompt', '')
    
        # Add timestamp to all prompts
        from datetime import datetime
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
        return {
            'hookSpecificOutput': {
                'hookEventName': 'UserPromptSubmit',
                'updatedPrompt': f"[{timestamp}] {original_prompt}"
            }
        }
    
    async def main():
        options = ClaudeAgentOptions(
            hooks={
                'PreToolUse': [
                    HookMatcher(hooks=[pre_tool_logger]),
                    HookMatcher(matcher='Bash', hooks=[pre_tool_logger])
                ],
                'PostToolUse': [
                    HookMatcher(hooks=[post_tool_logger])
                ],
                'UserPromptSubmit': [
                    HookMatcher(hooks=[user_prompt_modifier])
                ]
            },
            allowed_tools=["Read", "Write", "Bash"]
        )
    
        async with ClaudeSDKClient(options=options) as client:
            await client.query("List files in current directory")
    
            async for message in client.receive_response():
                # Hooks will automatically log tool usage
                pass
    
    asyncio.run(main())

    即時進度監控

    from claude_agent_sdk import (
        ClaudeSDKClient,
        ClaudeAgentOptions,
        AssistantMessage,
        ToolUseBlock,
        ToolResultBlock,
        TextBlock
    )
    import asyncio
    
    async def monitor_progress():
        options = ClaudeAgentOptions(
            allowed_tools=["Write", "Bash"],
            permission_mode="acceptEdits"
        )
    
        async with ClaudeSDKClient(options=options) as client:
            await client.query(
                "Create 5 Python files with different sorting algorithms"
            )
    
            # Monitor progress in real-time
            files_created = []
            async for message in client.receive_messages():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, ToolUseBlock):
                            if block.name == "Write":
                                file_path = block.input.get("file_path", "")
                                print(f"🔨 Creating: {file_path}")
                        elif isinstance(block, ToolResultBlock):
                            print(f"✅ Completed tool execution")
                        elif isinstance(block, TextBlock):
                            print(f"💭 Claude says: {block.text[:100]}...")
    
                # Check if we've received the final result
                if hasattr(message, 'subtype') and message.subtype in ['success', 'error']:
                    print(f"\n🎯 Task completed!")
                    break
    
    asyncio.run(monitor_progress())

    使用範例

    基本檔案操作(使用 query)

    from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
    import asyncio
    
    async def create_project():
        options = ClaudeAgentOptions(
            allowed_tools=["Read", "Write", "Bash"],
            permission_mode='acceptEdits',
            cwd="/home/user/project"
        )
    
        async for message in query(
            prompt="Create a Python project structure with setup.py",
            options=options
        ):
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, ToolUseBlock):
                        print(f"Using tool: {block.name}")
    
    asyncio.run(create_project())

    錯誤處理

    from claude_agent_sdk import (
        query,
        CLINotFoundError,
        ProcessError,
        CLIJSONDecodeError
    )
    
    try:
        async for message in query(prompt="Hello"):
            print(message)
    except CLINotFoundError:
        print("Please install Claude Code: npm install -g @anthropic-ai/claude-code")
    except ProcessError as e:
        print(f"Process failed with exit code: {e.exit_code}")
    except CLIJSONDecodeError as e:
        print(f"Failed to parse response: {e}")

    使用客戶端的串流模式

    from claude_agent_sdk import ClaudeSDKClient
    import asyncio
    
    async def interactive_session():
        async with ClaudeSDKClient() as client:
            # Send initial message
            await client.query("What's the weather like?")
    
            # Process responses
            async for msg in client.receive_response():
                print(msg)
    
            # Send follow-up
            await client.query("Tell me more about that")
    
            # Process follow-up response
            async for msg in client.receive_response():
                print(msg)
    
    asyncio.run(interactive_session())

    使用 ClaudeSDKClient 的自訂工具

    from claude_agent_sdk import (
        ClaudeSDKClient,
        ClaudeAgentOptions,
        tool,
        create_sdk_mcp_server,
        AssistantMessage,
        TextBlock
    )
    import asyncio
    from typing import Any
    
    # Define custom tools with @tool decorator
    @tool("calculate", "Perform mathematical calculations", {"expression": str})
    async def calculate(args: dict[str, Any]) -> dict[str, Any]:
        try:
            result = eval(args["expression"], {"__builtins__": {}})
            return {
                "content": [{
                    "type": "text",
                    "text": f"Result: {result}"
                }]
            }
        except Exception as e:
            return {
                "content": [{
                    "type": "text",
                    "text": f"Error: {str(e)}"
                }],
                "is_error": True
            }
    
    @tool("get_time", "Get current time", {})
    async def get_time(args: dict[str, Any]) -> dict[str, Any]:
        from datetime import datetime
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        return {
            "content": [{
                "type": "text",
                "text": f"Current time: {current_time}"
            }]
        }
    
    async def main():
        # Create SDK MCP server with custom tools
        my_server = create_sdk_mcp_server(
            name="utilities",
            version="1.0.0",
            tools=[calculate, get_time]
        )
    
        # Configure options with the server
        options = ClaudeAgentOptions(
            mcp_servers={"utils": my_server},
            allowed_tools=[
                "mcp__utils__calculate",
                "mcp__utils__get_time"
            ]
        )
    
        # Use ClaudeSDKClient for interactive tool usage
        async with ClaudeSDKClient(options=options) as client:
            await client.query("What's 123 * 456?")
    
            # Process calculation response
            async for message in client.receive_response():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, TextBlock):
                            print(f"Calculation: {block.text}")
    
            # Follow up with time query
            await client.query("What time is it now?")
    
            async for message in client.receive_response():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, TextBlock):
                            print(f"Time: {block.text}")
    
    asyncio.run(main())

    沙箱配置

    SandboxSettings

    沙箱行為的配置。使用此設定以程式化方式啟用命令沙箱並配置網路限制。

    class SandboxSettings(TypedDict, total=False):
        enabled: bool
        autoAllowBashIfSandboxed: bool
        excludedCommands: list[str]
        allowUnsandboxedCommands: bool
        network: SandboxNetworkConfig
        ignoreViolations: SandboxIgnoreViolations
        enableWeakerNestedSandbox: bool
    屬性類型預設值說明
    enabledboolFalse啟用命令執行的沙箱模式
    autoAllowBashIfSandboxedboolFalse當沙箱啟用時自動批准 bash 命令
    excludedCommandslist[str][]始終繞過沙箱限制的命令(例如 ["docker"])。這些命令會自動在沙箱外執行,無需模型參與
    allowUnsandboxedCommands

    檔案系統和網路存取限制不是透過沙箱設定來配置的。相反,它們是從權限規則衍生而來:

    • 檔案系統讀取限制:讀取拒絕規則
    • 檔案系統寫入限制:編輯允許/拒絕規則
    • 網路限制:WebFetch 允許/拒絕規則

    使用沙箱設定進行命令執行沙箱化,使用權限規則進行檔案系統和網路存取控制。

    使用範例

    from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings
    
    sandbox_settings: SandboxSettings = {
        "enabled": True,
        "autoAllowBashIfSandboxed": True,
        "network": {
            "allowLocalBinding": True
        }
    }
    
    async for message in query(
        prompt="Build and test my project",
        options=ClaudeAgentOptions(sandbox=sandbox_settings)
    ):
        print(message)

    Unix socket 安全性:allowUnixSockets 選項可以授予對強大系統服務的存取權限。例如,允許 /var/run/docker.sock 實際上會透過 Docker API 授予完整的主機系統存取權限,繞過沙箱隔離。僅允許嚴格必要的 Unix socket,並了解每個 socket 的安全影響。

    SandboxNetworkConfig

    沙箱模式的網路特定配置。

    class SandboxNetworkConfig(TypedDict, total=False):
        allowLocalBinding: bool
        allowUnixSockets: list[str]
        allowAllUnixSockets: bool
        httpProxyPort: int
        socksProxyPort: int
    屬性類型預設值說明
    allowLocalBindingboolFalse允許程序綁定到本地連接埠(例如用於開發伺服器)
    allowUnixSocketslist[str][]程序可以存取的 Unix socket 路徑(例如 Docker socket)
    allowAllUnixSocketsboolFalse允許存取所有 Unix socket
    httpProxyPort

    SandboxIgnoreViolations

    忽略特定沙箱違規的配置。

    class SandboxIgnoreViolations(TypedDict, total=False):
        file: list[str]
        network: list[str]
    屬性類型預設值說明
    filelist[str][]要忽略違規的檔案路徑模式
    networklist[str][]要忽略違規的網路模式

    非沙箱命令的權限回退

    當啟用 allowUnsandboxedCommands 時,模型可以透過在工具輸入中設定 dangerouslyDisableSandbox: True 來請求在沙箱外執行命令。這些請求會回退到現有的權限系統,這意味著您的 can_use_tool 處理器將被呼叫,允許您實作自訂授權邏輯。

    excludedCommands 與 allowUnsandboxedCommands 的區別:

    • excludedCommands:一個靜態命令列表,始終自動繞過沙箱(例如 ["docker"])。模型無法控制此設定。
    • allowUnsandboxedCommands:讓模型在執行時透過在工具輸入中設定 dangerouslyDisableSandbox: True 來決定是否請求非沙箱執行。
    from claude_agent_sdk import query, ClaudeAgentOptions
    
    async def can_use_tool(tool: str, input: dict) -> bool:
        # Check if the model is requesting to bypass the sandbox
        if tool == "Bash" and input.get("dangerouslyDisableSandbox"):
            # The model wants to run this command outside the sandbox
            print(f"Unsandboxed command requested: {input.get('command')}")
    
            # Return True to allow, False to deny
            return is_command_authorized(input.get("command"))
        return True
    
    async def main():
        async for message in query(
            prompt="Deploy my application",
            options=ClaudeAgentOptions(
                sandbox={
                    "enabled": True,
                    "allowUnsandboxedCommands": True  # Model can request unsandboxed execution
                },
                permission_mode="default",
                can_use_tool=can_use_tool
            )
        ):
            print(message)

    此模式使您能夠:

    • 審計模型請求:記錄模型何時請求非沙箱執行
    • 實作允許清單:僅允許特定命令在非沙箱環境中執行
    • 新增審批工作流程:要求對特權操作進行明確授權

    使用 dangerouslyDisableSandbox: True 執行的命令具有完整的系統存取權限。請確保您的 can_use_tool 處理器仔細驗證這些請求。

    如果 permission_mode 設定為 bypassPermissions 且 allow_unsandboxed_commands 已啟用,模型可以在沒有任何審批提示的情況下自主在沙箱外執行命令。這種組合實際上允許模型靜默地逃脫沙箱隔離。

    另請參閱

    • Python SDK 指南 - 教學和範例
    • SDK 概覽 - 一般 SDK 概念
    • TypeScript SDK 參考 - TypeScript SDK 文件
    • CLI 參考 - 命令列介面
    • 常見工作流程 - 逐步指南
    disconnect()與 Claude 斷開連線
    "append"
    mcp_serversdict[str, McpServerConfig] | str | Path{}MCP 伺服器配置或配置檔案路徑
    permission_modePermissionMode | NoneNone工具使用的權限模式
    continue_conversationboolFalse繼續最近的對話
    resumestr | NoneNone要恢復的工作階段 ID
    max_turnsint | NoneNone最大對話回合數
    max_budget_usdfloat | NoneNone工作階段的最大預算(美元)
    disallowed_toolslist[str][]不允許的工具名稱列表
    enable_file_checkpointingboolFalse啟用檔案變更追蹤以進行回溯。請參閱檔案檢查點
    modelstr | NoneNone要使用的 Claude 模型
    fallback_modelstr | NoneNone當主要模型失敗時使用的備用模型
    betaslist[SdkBeta][]要啟用的 Beta 功能。請參閱 SdkBeta 了解可用選項
    output_formatOutputFormat | NoneNone定義代理結果的輸出格式。請參閱結構化輸出了解詳情
    permission_prompt_tool_namestr | NoneNone用於權限提示的 MCP 工具名稱
    cwdstr | Path | NoneNone目前工作目錄
    cli_pathstr | Path | NoneNoneClaude Code CLI 可執行檔的自訂路徑
    settingsstr | NoneNone設定檔案路徑
    add_dirslist[str | Path][]Claude 可以存取的額外目錄
    envdict[str, str]{}環境變數
    extra_argsdict[str, str | None]{}直接傳遞給 CLI 的額外 CLI 引數
    max_buffer_sizeint | NoneNone緩衝 CLI stdout 時的最大位元組數
    debug_stderrAnysys.stderr已棄用 - 用於除錯輸出的類檔案物件。請改用 stderr 回呼函式
    stderrCallable[[str], None] | NoneNone用於 CLI stderr 輸出的回呼函式
    can_use_toolCanUseTool | NoneNone工具權限回呼函式。請參閱權限型別了解詳情
    hooksdict[HookEvent, list[HookMatcher]] | NoneNone用於攔截事件的 Hook 配置
    userstr | NoneNone使用者識別碼
    include_partial_messagesboolFalse包含部分訊息串流事件。啟用時,會產生 StreamEvent 訊息
    fork_sessionboolFalse使用 resume 恢復時,分叉到新的工作階段 ID 而不是繼續原始工作階段
    agentsdict[str, AgentDefinition] | NoneNone以程式方式定義的子代理
    pluginslist[SdkPluginConfig][]從本地路徑載入自訂外掛程式。請參閱外掛程式了解詳情
    sandboxSandboxSettings | NoneNone以程式方式配置沙箱行為。請參閱沙箱設定了解詳情
    setting_sourceslist[SettingSource] | NoneNone(不載入設定)控制要載入哪些檔案系統設定。省略時不載入任何設定。注意: 必須包含 "project" 才能載入 CLAUDE.md 檔案
    max_thinking_tokensint | NoneNone思考區塊的最大 token 數
    用於新增/移除目錄操作的目錄
    destinationLiteral[...] | None權限更新套用的位置
    bool
    False
    允許模型請求在沙箱外執行命令。當設為 True 時,模型可以在工具輸入中設定 dangerouslyDisableSandbox,這會回退到權限系統
    networkSandboxNetworkConfigNone網路特定的沙箱配置
    ignoreViolationsSandboxIgnoreViolationsNone配置要忽略哪些沙箱違規
    enableWeakerNestedSandboxboolFalse啟用較弱的巢狀沙箱以提高相容性
    int
    None
    用於網路請求的 HTTP 代理連接埠
    socksProxyPortintNone用於網路請求的 SOCKS 代理連接埠