English ← MyDocs

文档索引

在此处获取完整文档索引:https://code.claude.com/docs/llms.txt 使用此文件发现所有可用页面,然后再进一步探索。

Agent SDK 参考 - Python

Python Agent SDK 的完整 API 参考,包括所有函数、类型和类。

安装

pip install claude-agent-sdk

选择 query() 还是 ClaudeSDKClient

Python SDK 提供了两种与 Claude Code 交互的方式:

快速对比

特性query()ClaudeSDKClient
会话默认创建新会话复用同一会话
对话单次交互同一上下文中的多次交互
连接自动管理手动控制
流式输入✅ 支持✅ 支持
中断❌ 不支持✅ 支持
钩子✅ 支持✅ 支持
自定义工具✅ 支持✅ 支持
继续对话需手动通过 continue_conversationresume✅ 自动
使用场景一次性任务持续对话

何时使用 query()(一次性任务)

最适合:

  • 不需要对话历史的一次性问题
  • 不需要之前交互上下文的独立任务
  • 简单的自动化脚本
  • 每次都需要全新开始的场景

何时使用 ClaudeSDKClient(持续对话)

最适合:

  • 持续对话 - 需要 Claude 记住上下文时
  • 追问 - 基于之前的回答继续提问
  • 交互式应用 - 聊天界面、REPL
  • 响应驱动逻辑 - 下一步操作取决于 Claude 的响应
  • 会话控制 - 需要显式管理对话生命周期时

函数

query()

默认为每次与 Claude Code 的交互创建一个新会话。返回一个异步迭代器,在消息到达时逐条生成。除非传入 continue_conversation=True 或在 ClaudeAgentOptions 中指定 resume,否则每次调用 query() 都是全新开始,不记忆之前的交互。参见会话

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

参数

参数类型描述
promptstr | AsyncIterable[dict]输入提示,可以是字符串或用于流式模式的异步可迭代对象
optionsClaudeAgentOptions | None可选的配置对象(如果为 None 则默认为 ClaudeAgentOptions()
transportTransport | None可选的自定义传输层,用于与 CLI 进程通信

返回值

返回一个 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],
    annotations: ToolAnnotations | None = None
) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]

参数

参数类型描述
namestr工具的唯一标识符
descriptionstr工具功能的人类可读描述
input_schematype | dict[str, Any]定义工具输入参数的模式(见下方)
annotationsToolAnnotations | None可选的 MCP 工具注解,为客户端提供行为提示

输入模式选项

  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']}!"}]}

ToolAnnotations

mcp.types 重新导出(也可通过 from claude_agent_sdk import ToolAnnotations 导入)。所有字段都是可选的提示;客户端不应依赖它们进行安全决策。

字段类型默认值描述
titlestr | NoneNone工具的人类可读标题
readOnlyHintbool | NoneFalse如果为 True,则工具不会修改其环境
destructiveHintbool | NoneTrue如果为 True,则工具可能执行破坏性更新(仅在 readOnlyHintFalse 时有意义)
idempotentHintbool | NoneFalse如果为 True,则使用相同参数重复调用不会产生额外效果(仅在 readOnlyHintFalse 时有意义)
openWorldHintbool | NoneTrue如果为 True,则工具与外部实体交互(例如网络搜索)。如果为 False,则工具的领域是封闭的(例如记忆工具)
from claude_agent_sdk import tool, ToolAnnotations
from typing import Any


@tool(
    "search",
    "Search the web",
    {"query": str},
    annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True),
)
async def search(args: dict[str, Any]) -> dict[str, Any]:
    return {"content": [{"type": "text", "text": f"Results for: {args['query']}"}]}

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

list_sessions()

列出历史会话及其元数据。可按项目目录筛选或列出所有项目的会话。同步操作;立即返回。

def list_sessions(
    directory: str | None = None,
    limit: int | None = None,
    include_worktrees: bool = True
) -> list[SDKSessionInfo]

参数

参数类型默认值描述
directorystr | NoneNone要列出会话的目录。省略时返回所有项目的会话
limitint | NoneNone返回的最大会话数
include_worktreesboolTruedirectory 位于 git 仓库内时,包含所有 worktree 路径的会话

返回类型:SDKSessionInfo

属性类型描述
session_idstr唯一会话标识符
summarystr显示标题:自定义标题、自动生成的摘要或第一个提示
last_modifiedint最后修改时间,自 epoch 以来的毫秒数
file_sizeint | None会话文件大小(字节),远程存储后端为 None
custom_titlestr | None用户设置的会话标题
first_promptstr | None会话中第一个有意义的用户提示
git_branchstr | None会话结束时的 Git 分支
cwdstr | None会话的工作目录
tagstr | None用户设置的会话标签(参见 tag_session()
created_atint | None会话创建时间,自 epoch 以来的毫秒数

示例

打印项目的 10 个最近会话。结果按 last_modified 降序排列,因此第一项是最新的。省略 directory 可搜索所有项目。

from claude_agent_sdk import list_sessions

for session in list_sessions(directory="/path/to/project", limit=10):
    print(f"{session.summary} ({session.session_id})")

get_session_messages()

从历史会话中检索消息。同步操作;立即返回。

def get_session_messages(
    session_id: str,
    directory: str | None = None,
    limit: int | None = None,
    offset: int = 0
) -> list[SessionMessage]

参数

参数类型默认值描述
session_idstr必填要检索消息的会话 ID
directorystr | NoneNone要查找的项目目录。省略时搜索所有项目
limitint | NoneNone返回的最大消息数
offsetint0从开头跳过的消息数

返回类型:SessionMessage

属性类型描述
typeLiteral["user", "assistant"]消息角色
uuidstr唯一消息标识符
session_idstr会话标识符
messageAny原始消息内容
parent_tool_use_idNone保留供将来使用

示例

from claude_agent_sdk import list_sessions, get_session_messages

sessions = list_sessions(limit=1)
if sessions:
    messages = get_session_messages(sessions[0].session_id)
    for msg in messages:
        print(f"[{msg.type}] {msg.uuid}")

get_session_info()

通过 ID 读取单个会话的元数据,无需扫描整个项目目录。同步操作;立即返回。

def get_session_info(
    session_id: str,
    directory: str | None = None,
) -> SDKSessionInfo | None

参数

参数类型默认值描述
session_idstr必填要查找的会话 UUID
directorystr | NoneNone项目目录路径。省略时搜索所有项目目录

返回 SDKSessionInfo,如果未找到会话则返回 None

示例

无需扫描项目目录即可查找单个会话的元数据。当你已从之前的运行中获得会话 ID 时非常有用。

from claude_agent_sdk import get_session_info

info = get_session_info("550e8400-e29b-41d4-a716-446655440000")
if info:
    print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})")

rename_session()

通过追加自定义标题条目来重命名会话。重复调用是安全的;最新的标题生效。同步操作。

def rename_session(
    session_id: str,
    title: str,
    directory: str | None = None,
) -> None

参数

参数类型默认值描述
session_idstr必填要重命名的会话 UUID
titlestr必填新标题。去除空白后必须非空
directorystr | NoneNone项目目录路径。省略时搜索所有项目目录

如果 session_id 不是有效的 UUID 或 title 为空则抛出 ValueError;如果找不到会话则抛出 FileNotFoundError

示例

重命名最近的会话,以便稍后更容易找到。新标题将出现在后续读取的 SDKSessionInfo.custom_title 中。

from claude_agent_sdk import list_sessions, rename_session

sessions = list_sessions(directory="/path/to/project", limit=1)
if sessions:
    rename_session(sessions[0].session_id, "Refactor auth module")

tag_session()

为会话打标签。传入 None 可清除标签。重复调用是安全的;最新的标签生效。同步操作。

def tag_session(
    session_id: str,
    tag: str | None,
    directory: str | None = None,
) -> None

参数

参数类型默认值描述
session_idstr必填要打标签的会话 UUID
tagstr | None必填标签字符串,或 None 以清除。存储前会进行 Unicode 净化处理
directorystr | NoneNone项目目录路径。省略时搜索所有项目目录

如果 session_id 不是有效的 UUID 或净化后 tag 为空则抛出 ValueError;如果找不到会话则抛出 FileNotFoundError

示例

为会话打标签,然后在后续读取时按该标签筛选。传入 None 可清除现有标签。

from claude_agent_sdk import list_sessions, tag_session

# Tag a session
tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")

# Later: find all sessions with that tag
for session in list_sessions(directory="/path/to/project"):
    if session.tag == "needs-review":
        print(session.summary)

ClaudeSDKClient

跨多次交互维护对话会话。 这是 TypeScript SDK 的 query() 函数内部工作方式的 Python 等价实现 - 它创建一个可以继续对话的客户端对象。

主要特性

  • 会话连续性:跨多次 query() 调用维护对话上下文
  • 同一对话:会话保留之前的消息
  • 中断支持:可在任务执行过程中停止
  • 显式生命周期:你控制会话的开始和结束
  • 响应驱动流程:可对响应做出反应并发送后续消息
  • 自定义工具和钩子:支持自定义工具(使用 @tool 装饰器创建)和钩子
class ClaudeSDKClient:
    def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | 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 set_permission_mode(self, mode: str) -> None
    async def set_model(self, model: str | None = None) -> None
    async def rewind_files(self, user_message_id: str) -> None
    async def get_mcp_status(self) -> McpStatusResponse
    async def reconnect_mcp_server(self, server_name: str) -> None
    async def toggle_mcp_server(self, server_name: str, enabled: bool) -> None
    async def stop_task(self, task_id: str) -> None
    async def get_server_info(self) -> dict[str, Any] | None
    async def disconnect(self) -> None

方法

方法描述
__init__(options)使用可选配置初始化客户端
connect(prompt)连接到 Claude,可选传入初始提示或消息流
query(prompt, session_id)以流式模式发送新请求
receive_messages()以异步迭代器方式接收来自 Claude 的所有消息
receive_response()接收消息直到收到 ResultMessage(包含 ResultMessage)
interrupt()发送中断信号(仅在流式模式下有效)
set_permission_mode(mode)更改当前会话的权限模式
set_model(model)更改当前会话的模型。传入 None 恢复默认值
rewind_files(user_message_id)将文件恢复到指定用户消息时的状态。需要 enable_file_checkpointing=True。参见文件检查点
get_mcp_status()获取所有已配置 MCP 服务器的状态。返回 McpStatusResponse
reconnect_mcp_server(server_name)重试连接失败或已断开的 MCP 服务器
toggle_mcp_server(server_name, enabled)在会话中启用或禁用 MCP 服务器。禁用会移除其工具
stop_task(task_id)停止正在运行的后台任务。消息流中会随后出现状态为 "stopped"TaskNotificationMessage
get_server_info()获取服务器信息,包括会话 ID 和功能
disconnect()断开与 Claude 的连接

上下文管理器支持

客户端可以用作异步上下文管理器来自动管理连接:

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 - the session retains 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": "user",
        "message": {"role": "user", "content": "Analyze the following data:"},
    }
    await asyncio.sleep(0.5)
    yield {
        "type": "user",
        "message": {"role": "user", "content": "Temperature: 25°C, Humidity: 60%"},
    }
    await asyncio.sleep(0.5)
    yield {
        "type": "user",
        "message": {"role": "user", "content": "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, ResultMessage


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, using the bash sleep command")

        # Let it run for a bit
        await asyncio.sleep(2)

        # Interrupt the task
        await client.interrupt()
        print("Task interrupted!")

        # Drain the interrupted task's messages (including its ResultMessage)
        async for message in client.receive_response():
            if isinstance(message, ResultMessage):
                print(f"Interrupted task finished with subtype={message.subtype!r}")
                # subtype is "error_during_execution" for interrupted tasks

        # Send a new command
        await client.query("Just say hello instead")

        # Now receive the new response
        async for message in client.receive_response():
            if isinstance(message, ResultMessage) and message.subtype == "success":
                print(f"New result: {message.result}")


asyncio.run(interruptible_task())
Note

中断后的缓冲行为: interrupt() 发送停止信号但不清除消息缓冲区。被中断任务已产生的消息(包括其 ResultMessagesubtype="error_during_execution")仍保留在流中。你必须在读取新查询的响应之前用 receive_response() 排空它们。如果你在 interrupt() 后立即发送新查询并只调用一次 receive_response(),你将收到被中断任务的消息,而不是新查询的响应。

示例 - 高级权限控制

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
from claude_agent_sdk.types import (
    PermissionResultAllow,
    PermissionResultDeny,
    ToolPermissionContext,
)


async def custom_permission_handler(
    tool_name: str, input_data: dict, context: ToolPermissionContext
) -> 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())

类型

Note

@dataclassTypedDict 此 SDK 使用两种类型。用 @dataclass 装饰的类(如 ResultMessageAgentDefinitionTextBlock)在运行时是对象实例,支持属性访问:msg.result。用 TypedDict 定义的类(如 ThinkingConfigEnabledMcpStdioServerConfigSyncHookJSONOutput)在运行时是纯字典,需要键访问:config["budget_tokens"],而非 config.budget_tokensClassName(field=value) 调用语法对两者都有效,但只有 dataclass 会产生具有属性的对象。

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]]]
    annotations: ToolAnnotations | None = None
属性类型描述
namestr工具的唯一标识符
descriptionstr人类可读描述
input_schematype[T] | dict[str, Any]输入验证的模式
handlerCallable[[T], Awaitable[dict[str, Any]]]处理工具执行的异步函数
annotationsToolAnnotations | None可选的 MCP 工具注解(例如 readOnlyHintdestructiveHintopenWorldHint)。来自 mcp.types

Transport

自定义传输实现的抽象基类。用于通过自定义通道(例如远程连接而非本地子进程)与 Claude 进程通信。

Warning

这是低级内部 API。接口可能在未来版本中发生变化。自定义实现必须更新以匹配任何接口变更。

from abc import ABC, abstractmethod
from collections.abc import AsyncIterator
from typing import Any


class Transport(ABC):
    @abstractmethod
    async def connect(self) -> None: ...

    @abstractmethod
    async def write(self, data: str) -> None: ...

    @abstractmethod
    def read_messages(self) -> AsyncIterator[dict[str, Any]]: ...

    @abstractmethod
    async def close(self) -> None: ...

    @abstractmethod
    def is_ready(self) -> bool: ...

    @abstractmethod
    async def end_input(self) -> None: ...
方法描述
connect()连接传输层并准备通信
write(data)向传输层写入原始数据(JSON + 换行符)
read_messages()生成已解析 JSON 消息的异步迭代器
close()关闭连接并清理资源
is_ready()如果传输层可以发送和接收则返回 True
end_input()关闭输入流(例如关闭子进程传输的 stdin)

导入:from claude_agent_sdk import Transport

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)
    strict_mcp_config: bool = False
    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: dict[str, Any] | 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
    include_hook_events: bool = False
    fork_session: bool = False
    agents: dict[str, AgentDefinition] | None = None
    setting_sources: list[SettingSource] | None = None
    sandbox: SandboxSettings | None = None
    plugins: list[SdkPluginConfig] = field(default_factory=list)
    max_thinking_tokens: int | None = None  # Deprecated: use thinking instead
    thinking: ThinkingConfig | None = None
    effort: EffortLevel | None = None
    enable_file_checkpointing: bool = False
    session_store: SessionStore | None = None
    session_store_flush: SessionStoreFlushMode = "batched"
属性类型默认值描述
toolslist[str] | ToolsPreset | NoneNone工具配置。使用 {"type": "preset", "preset": "claude_code"} 获取 Claude Code 的默认工具
allowed_toolslist[str][]无需提示即可自动批准的工具。这不限制 Claude 只能使用这些工具;未列出的工具会回退到 permission_modecan_use_tool。使用 disallowed_tools 来阻止工具。参见权限
system_promptstr | SystemPromptPreset | NoneNone系统提示配置。传入字符串作为自定义提示,或使用 {"type": "preset", "preset": "claude_code"} 获取 Claude Code 的系统提示。添加 "append" 可扩展现有预设
mcp_serversdict[str, McpServerConfig] | str | Path{}MCP 服务器配置或配置文件路径
strict_mcp_configboolFalseTrue 时,仅使用 mcp_servers 中传入的服务器,忽略项目的 .mcp.json、用户设置和插件提供的 MCP 服务器。映射到 CLI 的 --strict-mcp-config 标志
permission_modePermissionMode | NoneNone工具使用的权限模式
continue_conversationboolFalse继续最近的对话
resumestr | NoneNone要恢复的会话 ID
max_turnsint | NoneNone最大代理轮次(工具使用往返)
max_budget_usdfloat | NoneNone当客户端成本估算达到此美元值时停止查询。与 total_cost_usd 使用相同的估算值比较;准确性注意事项参见跟踪成本和用量
disallowed_toolslist[str][]要拒绝的工具。裸名称(如 "Bash")会从 Claude 的上下文中移除该工具。范围规则(如 "Bash(rm *)")保持工具可用但在所有权限模式(包括 bypassPermissions)中拒绝匹配的调用。参见权限
enable_file_checkpointingboolFalse启用文件变更跟踪以支持回退。参见文件检查点
modelstr | NoneNone要使用的 Claude 模型
fallback_modelstr | NoneNone主模型失败时使用的备用模型
betaslist[SdkBeta][]要启用的 Beta 功能。参见 SdkBeta 了解可用选项
output_formatdict[str, Any] | NoneNone结构化响应的输出格式(例如 {"type": "json_schema", "schema": {...}})。详情参见结构化输出
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]{}合并到继承的进程环境之上的环境变量。底层 CLI 读取的变量参见环境变量,超时相关变量参见处理缓慢或停滞的 API 响应
extra_argsdict[str, str | None]{}直接传递给 CLI 的附加 CLI 参数
max_buffer_sizeint | NoneNone缓冲 CLI stdout 时的最大字节数
debug_stderrAnysys.stderr已弃用 - 用于调试输出的类文件对象。请使用 stderr 回调代替
stderrCallable[[str], None] | NoneNoneCLI stderr 输出的回调函数
can_use_toolCanUseTool | NoneNone工具权限回调函数。详情参见权限类型
hooksdict[HookEvent, list[HookMatcher]] | NoneNone用于拦截事件的钩子配置
userstr | NoneNone用户标识符
include_partial_messagesboolFalse包含部分消息流事件。启用后会生成 StreamEvent 消息
include_hook_eventsboolFalse在消息流中包含钩子生命周期事件,作为 HookEventMessage 对象
fork_sessionboolFalse使用 resume 恢复时,fork 到新会话 ID 而不是继续原始会话
agentsdict[str, AgentDefinition] | NoneNone以编程方式定义的子代理
pluginslist[SdkPluginConfig][]从本地路径加载自定义插件。详情参见插件
sandboxSandboxSettings | NoneNone以编程方式配置沙盒行为。详情参见沙盒设置
setting_sourceslist[SettingSource] | NoneNone(CLI 默认:所有来源)控制加载哪些文件系统设置。传入 [] 可禁用用户、项目和本地设置。托管策略设置始终加载。参见使用 Claude Code 功能
skillslist[str] | Literal["all"] | NoneNone会话可用的技能。传入 "all" 启用所有发现的技能,或传入技能名称列表。设置后,SDK 会自动启用 Skill 工具而无需在 allowed_tools 中列出。参见技能
max_thinking_tokensint | NoneNone已弃用 - 思考块的最大 token 数。请使用 thinking 代替
thinkingThinkingConfig | NoneNone控制扩展思考行为。优先于 max_thinking_tokens
effortEffortLevel | NoneNone思考深度的努力级别
session_storeSessionStore | NoneNone将会话记录镜像到外部后端,以便任何主机都可以恢复它们。参见将会话持久化到外部存储
session_store_flushLiteral["batched", "eager"]"batched"何时将镜像的记录条目刷新到 session_store"batched" 在每轮结束或缓冲区满时刷新;"eager" 在每帧后触发后台刷新。当 session_storeNone 时忽略

处理缓慢或停滞的 API 响应

CLI 子进程读取多个环境变量来控制 API 超时和停滞检测。通过 ClaudeAgentOptions.env 传递它们:

options = ClaudeAgentOptions(
    env={
        "API_TIMEOUT_MS": "120000",
        "CLAUDE_CODE_MAX_RETRIES": "2",
        "CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS": "120000",
    },
)
  • API_TIMEOUT_MS:Anthropic 客户端的每请求超时,以毫秒为单位。默认 600000。适用于主循环和所有子代理。
  • CLAUDE_CODE_MAX_RETRIES:最大 API 重试次数。默认 10。每次重试都有自己的 API_TIMEOUT_MS 窗口,因此最坏情况下的实际时间约为 API_TIMEOUT_MS x (CLAUDE_CODE_MAX_RETRIES + 1) 加上退避时间。
  • CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS:使用 run_in_background 启动的子代理的停滞看门狗。默认 600000。在每个流事件时重置;停滞时中止子代理、标记任务失败,并将错误连同任何部分结果一起呈现给父代理。不适用于同步子代理。
  • CLAUDE_ENABLE_STREAM_WATCHDOG=1 配合 CLAUDE_STREAM_IDLE_TIMEOUT_MS:当响应头已到达但响应体停止流式传输时中止请求。默认关闭。CLAUDE_STREAM_IDLE_TIMEOUT_MS 默认为 300000,并被限制在该最小值。中止的请求会通过正常的重试路径。

OutputFormat

结构化输出验证的配置。将其作为 dict 传递给 ClaudeAgentOptionsoutput_format 字段:

# Expected dict shape for output_format
{
    "type": "json_schema",
    "schema": {...},  # Your JSON Schema definition
}
字段必填描述
type必须为 "json_schema" 以进行 JSON Schema 验证
schema输出验证的 JSON Schema 定义

SystemPromptPreset

使用 Claude Code 预设系统提示的配置,可选择添加额外内容。

class SystemPromptPreset(TypedDict):
    type: Literal["preset"]
    preset: Literal["claude_code"]
    append: NotRequired[str]
    exclude_dynamic_sections: NotRequired[bool]
字段必填描述
type必须为 "preset" 以使用预设系统提示
preset必须为 "claude_code" 以使用 Claude Code 的系统提示
append追加到预设系统提示的附加指令
exclude_dynamic_sections将每会话上下文(如工作目录、git 仓库标志和自动记忆路径)从系统提示移到第一条用户消息中。改善跨用户和机器的提示缓存复用。参见修改系统提示

SettingSource

控制 SDK 从哪些基于文件系统的配置源加载设置。

SettingSource = Literal["user", "project", "local"]
描述位置
"user"全局用户设置~/.claude/settings.json
"project"共享项目设置(版本控制).claude/settings.json
"local"本地项目设置(已 gitignore).claude/settings.local.json

默认行为

setting_sources 被省略或为 None 时,query() 会加载与 Claude Code CLI 相同的文件系统设置:用户、项目和本地设置。托管策略设置在所有情况下都会加载。参见settingSources 不控制的内容,了解无论此选项如何都会读取的输入,以及如何禁用它们。

为什么使用 setting_sources

禁用文件系统设置:

# Do not load user, project, or local settings from disk
from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="Analyze this code",
    options=ClaudeAgentOptions(
        setting_sources=[]
    ),
):
    print(message)
Note

在 Python SDK 0.1.59 及更早版本中,空列表被视为与省略该选项相同,因此 setting_sources=[] 不会禁用文件系统设置。如果需要空列表生效,请升级到更新版本。TypeScript SDK 不受此影响。

显式加载所有文件系统设置:

from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="Analyze this code",
    options=ClaudeAgentOptions(
        setting_sources=["user", "project", "local"]
    ),
):
    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.
# Pass [] to opt out of filesystem setting sources.
async for message in query(
    prompt="Review this PR",
    options=ClaudeAgentOptions(
        setting_sources=[],
        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"],  # Loads CLAUDE.md from project
        allowed_tools=["Read", "Write", "Edit"],
    ),
):
    print(message)

设置优先级

当加载多个来源时,设置按以下优先级合并(从高到低):

  1. 本地设置(.claude/settings.local.json
  2. 项目设置(.claude/settings.json
  3. 用户设置(~/.claude/settings.json

编程选项(如 agentsallowed_tools)会覆盖用户、项目和本地文件系统设置。托管策略设置优先于编程选项。

AgentDefinition

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

@dataclass
class AgentDefinition:
    description: str
    prompt: str
    tools: list[str] | None = None
    disallowedTools: list[str] | None = None
    model: str | None = None
    skills: list[str] | None = None
    memory: Literal["user", "project", "local"] | None = None
    mcpServers: list[str | dict[str, Any]] | None = None
    initialPrompt: str | None = None
    maxTurns: int | None = None
    background: bool | None = None
    effort: EffortLevel | int | None = None
    permissionMode: PermissionMode | None = None
字段必填描述
description何时使用此代理的自然语言描述
prompt代理的系统提示
tools允许的工具名称数组。如果省略则继承所有工具
disallowedTools从代理工具集中移除的工具名称数组
model此代理的模型覆盖。接受别名如 "sonnet""opus""haiku""inherit",或完整模型 ID。如果省略则使用主模型
skills在启动时预加载到代理上下文中的技能名称列表。未列出的技能仍可通过 Skill 工具调用
memory此代理的记忆源:"user""project""local"
mcpServers此代理可用的 MCP 服务器。每个条目是服务器名称或内联的 {name: config} 字典
initialPrompt当此代理作为主线程代理运行时,自动提交为第一轮用户输入
maxTurns代理停止前的最大代理轮次数
background调用时将此代理作为非阻塞后台任务运行
effort此代理的推理努力级别。接受命名级别或整数。参见 EffortLevel
permissionMode此代理内工具执行的权限模式。参见 PermissionMode
Note

AgentDefinition 字段名称使用 camelCase,如 disallowedToolspermissionModemaxTurns。这些名称直接映射到与 TypeScript SDK 共享的传输格式。这与 ClaudeAgentOptions 不同,后者对等效的顶级字段(如 disallowed_toolspermission_mode)使用 Python snake_case。由于 AgentDefinition 是一个数据类,传入 snake_case 关键字会在构造时引发 TypeError

PermissionMode

控制工具执行的权限模式。

PermissionMode = Literal[
    "default",  # Standard permission behavior
    "acceptEdits",  # Auto-accept file edits
    "plan",  # Planning mode - read-only tools only
    "dontAsk",  # Deny anything not pre-approved instead of prompting
    "bypassPermissions",  # Bypass all permission checks (use with caution)
]

EffortLevel

引导思考深度的努力级别。

EffortLevel = Literal[
    "low",  # Minimal thinking, fastest responses
    "medium",  # Moderate thinking
    "high",  # Deep reasoning
    "xhigh",  # Extended reasoning (Opus 4.7 only; falls back to "high" on other models)
    "max",  # Maximum effort
]

CanUseTool

工具权限回调函数的类型别名。

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

回调接收:

  • tool_name:被调用工具的名称
  • input_data:工具的输入参数
  • context:包含附加信息的 ToolPermissionContext

返回 PermissionResultPermissionResultAllowPermissionResultDeny)。

ToolPermissionContext

传递给工具权限回调的上下文信息。

@dataclass
class ToolPermissionContext:
    signal: Any | None = None  # Future: abort signal support
    suggestions: list[PermissionUpdate] = field(default_factory=list)
    blocked_path: str | None = None
    decision_reason: str | None = None
    title: str | None = None
    display_name: str | None = None
    description: str | None = None
字段类型描述
signalAny | None保留供将来中止信号支持
suggestionslist[PermissionUpdate]来自 CLI 的权限更新建议。Bash 提示包含一个带有 localSettings 目标的建议,因此在 updated_permissions 中返回它会将规则写入 .claude/settings.local.json 并跨会话持久化。
blocked_pathstr | None触发权限请求的文件路径(如适用)。例如,当 Bash 命令尝试访问允许目录之外的路径时
decision_reasonstr | None触发此权限请求的原因。当 PreToolUse 钩子返回 "ask" 时,从钩子的 permissionDecisionReason 转发
titlestr | None完整的权限提示句子,如 Claude wants to read foo.txt。存在时用作主要提示文本
display_namestr | None工具操作的简短短语,如 Read file,适用于按钮标签
descriptionstr | None权限 UI 的人类可读副标题

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添加/删除目录操作的目录
destinationLiteral[...] | None应用权限更新的位置

PermissionRuleValue

权限更新中要添加、替换或删除的规则。

@dataclass
class PermissionRuleValue:
    tool_name: str
    rule_content: str | None = None

ToolsPreset

使用 Claude Code 默认工具集的预设工具配置。

class ToolsPreset(TypedDict):
    type: Literal["preset"]
    preset: Literal["claude_code"]

ThinkingConfig

控制扩展思考行为。三种配置的联合:

ThinkingDisplay = Literal["summarized", "omitted"]


class ThinkingConfigAdaptive(TypedDict):
    type: Literal["adaptive"]
    display: NotRequired[ThinkingDisplay]


class ThinkingConfigEnabled(TypedDict):
    type: Literal["enabled"]
    budget_tokens: int
    display: NotRequired[ThinkingDisplay]


class ThinkingConfigDisabled(TypedDict):
    type: Literal["disabled"]


ThinkingConfig = ThinkingConfigAdaptive | ThinkingConfigEnabled | ThinkingConfigDisabled
变体字段描述
adaptivetype, displayClaude 自适应决定何时思考
enabledtype, budget_tokens, display启用思考并设置特定的 token 预算
disabledtype禁用思考

可选的 display 字段控制思考文本是以 "summarized" 还是 "omitted" 形式返回。在 Claude Opus 4.7 及更高版本中,API 默认为 "omitted",因此需要设置 "summarized" 才能在 ThinkingBlock 输出中接收思考内容。

由于这些是 TypedDict 类,它们在运行时是纯字典。可以用字典字面量构造或像构造函数一样调用类;两者都生成 dict。使用 config["budget_tokens"] 访问字段,而非 config.budget_tokens

from claude_agent_sdk import ClaudeAgentOptions, ThinkingConfigEnabled

# Option 1: dict literal (recommended, no import needed)
options = ClaudeAgentOptions(thinking={"type": "enabled", "budget_tokens": 20000})

# Option 2: constructor-style (returns a plain dict)
config = ThinkingConfigEnabled(type="enabled", budget_tokens=20000)
print(config["budget_tokens"])  # 20000
# config.budget_tokens would raise AttributeError

SdkBeta

SDK Beta 功能的字面类型。

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

ClaudeAgentOptions 中的 betas 字段一起使用以启用 Beta 功能。

Warning

context-1m-2025-08-07 Beta 已于 2026 年 4 月 30 日退役。将此头信息与 Claude Sonnet 4.5 或 Sonnet 4 一起传递没有效果,超过标准 200k token 上下文窗口的请求会返回错误。要使用 1M token 上下文窗口,请迁移到 Claude Sonnet 4.6、Claude Opus 4.6 或 Claude Opus 4.7,这些模型包含 1M 上下文且无需 Beta 头信息,价格与标准相同。

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]]

McpServerStatusConfig

get_mcp_status() 报告的 MCP 服务器配置。这是所有 McpServerConfig 传输变体的联合,加上一个仅输出的 claudeai-proxy 变体,用于通过 claude.ai 代理的服务器。

McpServerStatusConfig = (
    McpStdioServerConfig
    | McpSSEServerConfig
    | McpHttpServerConfig
    | McpSdkServerConfigStatus
    | McpClaudeAIProxyServerConfig
)

McpSdkServerConfigStatusMcpSdkServerConfig 的可序列化形式,仅包含 type"sdk")和 namestr)字段;进程内的 instance 被省略。McpClaudeAIProxyServerConfig 包含 type"claudeai-proxy")、urlstr)和 idstr)字段。

McpStatusResponse

来自 ClaudeSDKClient.get_mcp_status() 的响应。在 mcpServers 键下包装服务器状态列表。

class McpStatusResponse(TypedDict):
    mcpServers: list[McpServerStatus]

McpServerStatus

已连接 MCP 服务器的状态,包含在 McpStatusResponse 中。

class McpServerStatus(TypedDict):
    name: str
    status: McpServerConnectionStatus  # "connected" | "failed" | "needs-auth" | "pending" | "disabled"
    serverInfo: NotRequired[McpServerInfo]
    error: NotRequired[str]
    config: NotRequired[McpServerStatusConfig]
    scope: NotRequired[str]
    tools: NotRequired[list[McpToolInfo]]
字段类型描述
namestr服务器名称
statusstr"connected""failed""needs-auth""pending""disabled" 之一
serverInfodict(可选)服务器名称和版本({"name": str, "version": str}
errorstr(可选)服务器连接失败时的错误消息
configMcpServerStatusConfig(可选)服务器配置。形状与 McpServerConfig(stdio、SSE、HTTP 或 SDK)相同,加上通过 claude.ai 连接的服务器的 claudeai-proxy 变体
scopestr(可选)配置作用域
toolslist(可选)此服务器提供的工具,每个工具包含 namedescriptionannotations 字段

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

UserMessage

用户输入消息。

@dataclass
class UserMessage:
    content: str | list[ContentBlock]
    uuid: str | None = None
    parent_tool_use_id: str | None = None
    tool_use_result: dict[str, Any] | None = None
字段类型描述
contentstr | list[ContentBlock]消息内容,文本或内容块
uuidstr | None唯一消息标识符
parent_tool_use_idstr | None如果此消息是工具结果响应,则为工具使用 ID
tool_use_resultdict[str, Any] | None工具结果数据(如适用)

AssistantMessage

包含内容块的助手响应消息。

@dataclass
class AssistantMessage:
    content: list[ContentBlock]
    model: str
    parent_tool_use_id: str | None = None
    error: AssistantMessageError | None = None
    usage: dict[str, Any] | None = None
    message_id: str | None = None
字段类型描述
contentlist[ContentBlock]响应中的内容块列表
modelstr生成响应的模型
parent_tool_use_idstr | None如果这是嵌套响应,则为工具使用 ID
errorAssistantMessageError | None响应遇到错误时的错误类型
usagedict[str, Any] | None每条消息的 token 用量(与 ResultMessage.usage 相同的键)
message_idstr | NoneAPI 消息 ID。一轮中的多条消息共享相同的 ID

AssistantMessageError

助手消息的可能错误类型。

AssistantMessageError = Literal[
    "authentication_failed",
    "billing_error",
    "rate_limit",
    "invalid_request",
    "server_error",
    "max_output_tokens",
    "unknown",
]

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
    stop_reason: str | None = None
    total_cost_usd: float | None = None
    usage: dict[str, Any] | None = None
    result: str | None = None
    structured_output: Any = None
    model_usage: dict[str, Any] | None = None
    permission_denials: list[Any] | None = None
    deferred_tool_use: DeferredToolUse | None = None
    errors: list[str] | None = None
    api_error_status: int | None = None
    uuid: str | None = None

usage 字典包含以下键(如存在):

类型描述
input_tokensint消耗的总输入 token。
output_tokensint生成的总输出 token。
cache_creation_input_tokensint用于创建新缓存条目的 token。
cache_read_input_tokensint从现有缓存条目读取的 token。

model_usage 字典将模型名称映射到每模型用量。内部字典键使用 camelCase,因为值从底层 CLI 进程原样传递,与 TypeScript ModelUsage 类型匹配:

类型描述
inputTokensint此模型的输入 token。
outputTokensint此模型的输出 token。
cacheReadInputTokensint此模型的缓存读取 token。
cacheCreationInputTokensint此模型的缓存创建 token。
webSearchRequestsint此模型发出的网络搜索请求。
costUSDfloat此模型的估计成本(美元),客户端计算。计费注意事项参见跟踪成本和用量
contextWindowint此模型的上下文窗口大小。
maxOutputTokensint此模型的最大输出 token 限制。

StreamEvent

流式传输期间部分消息更新的流事件。仅在 ClaudeAgentOptions 中设置 include_partial_messages=True 时接收。通过 from claude_agent_sdk.types import StreamEvent 导入。

@dataclass
class StreamEvent:
    uuid: str
    session_id: str
    event: dict[str, Any]  # The raw Claude API stream event
    parent_tool_use_id: str | None = None
字段类型描述
uuidstr此事件的唯一标识符
session_idstr会话标识符
eventdict[str, Any]原始 Claude API 流事件数据
parent_tool_use_idstr | None如果此事件来自子代理,则为父工具使用 ID

RateLimitEvent

当速率限制状态发生变化时发出(例如从 "allowed" 变为 "allowed_warning")。用于在用户达到硬限制之前发出警告,或在状态为 "rejected" 时退避。

@dataclass
class RateLimitEvent:
    rate_limit_info: RateLimitInfo
    uuid: str
    session_id: str
字段类型描述
rate_limit_infoRateLimitInfo当前速率限制状态
uuidstr唯一事件标识符
session_idstr会话标识符

RateLimitInfo

RateLimitEvent 携带的速率限制状态。

RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]
RateLimitType = Literal[
    "five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "overage"
]


@dataclass
class RateLimitInfo:
    status: RateLimitStatus
    resets_at: int | None = None
    rate_limit_type: RateLimitType | None = None
    utilization: float | None = None
    overage_status: RateLimitStatus | None = None
    overage_resets_at: int | None = None
    overage_disabled_reason: str | None = None
    raw: dict[str, Any] = field(default_factory=dict)
字段类型描述
statusRateLimitStatus当前状态。"allowed_warning" 表示接近限制;"rejected" 表示已达到限制
resets_atint | None速率限制窗口重置的 Unix 时间戳
rate_limit_typeRateLimitType | None适用的速率限制窗口
utilizationfloat | None已消耗的速率限制比例(0.0 到 1.0)
overage_statusRateLimitStatus | None按需超额使用状态(如适用)
overage_resets_atint | None超额窗口重置的 Unix 时间戳
overage_disabled_reasonstr | None如果状态为 "rejected",超额不可用的原因
rawdict[str, Any]来自 CLI 的完整原始字典,包括上面未建模的字段

TaskStartedMessage

当后台任务启动时发出。后台任务是在主轮次之外跟踪的任何任务:后台 Bash 命令、Monitor 监视、通过 Agent 工具生成的子代理或远程代理。task_type 字段告诉你属于哪种类型。此命名与 TaskAgent 工具重命名无关。

@dataclass
class TaskStartedMessage(SystemMessage):
    task_id: str
    description: str
    uuid: str
    session_id: str
    tool_use_id: str | None = None
    task_type: str | None = None
字段类型描述
task_idstr任务的唯一标识符
descriptionstr任务描述
uuidstr唯一消息标识符
session_idstr会话标识符
tool_use_idstr | None关联的工具使用 ID
task_typestr | None后台任务类型:"local_bash" 用于后台 Bash 和 Monitor 监视,"local_agent""remote_agent"

TaskUsage

后台任务的 token 和计时数据。

class TaskUsage(TypedDict):
    total_tokens: int
    tool_uses: int
    duration_ms: int

TaskProgressMessage

定期发出,包含正在运行的后台任务的进度更新。

@dataclass
class TaskProgressMessage(SystemMessage):
    task_id: str
    description: str
    usage: TaskUsage
    uuid: str
    session_id: str
    tool_use_id: str | None = None
    last_tool_name: str | None = None
字段类型描述
task_idstr任务的唯一标识符
descriptionstr当前状态描述
usageTaskUsage此任务迄今为止的 token 用量
uuidstr唯一消息标识符
session_idstr会话标识符
tool_use_idstr | None关联的工具使用 ID
last_tool_namestr | None任务最后使用的工具名称

TaskNotificationMessage

当后台任务完成、失败或被停止时发出。后台任务包括 run_in_background Bash 命令、Monitor 监视和后台子代理。

@dataclass
class TaskNotificationMessage(SystemMessage):
    task_id: str
    status: TaskNotificationStatus  # "completed" | "failed" | "stopped"
    output_file: str
    summary: str
    uuid: str
    session_id: str
    tool_use_id: str | None = None
    usage: TaskUsage | None = None
字段类型描述
task_idstr任务的唯一标识符
statusTaskNotificationStatus"completed""failed""stopped" 之一
output_filestr任务输出文件的路径
summarystr任务结果摘要
uuidstr唯一消息标识符
session_idstr会话标识符
tool_use_idstr | None关联的工具使用 ID
usageTaskUsage | None任务的最终 token 用量

内容块类型

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

钩子类型

有关使用钩子的完整指南(包含示例和常见模式),请参见钩子指南

HookEvent

支持的钩子事件类型。

HookEvent = Literal[
    "PreToolUse",  # Called before tool execution
    "PostToolUse",  # Called after tool execution
    "PostToolUseFailure",  # Called when a tool execution fails
    "UserPromptSubmit",  # Called when user submits a prompt
    "Stop",  # Called when stopping execution
    "SubagentStop",  # Called when a subagent stops
    "PreCompact",  # Called before message compaction
    "Notification",  # Called for notification events
    "SubagentStart",  # Called when a subagent starts
    "PermissionRequest",  # Called when a permission decision is needed
]
Note

TypeScript SDK 支持 Python 中尚未提供的其他钩子事件:SessionStartSessionEndSetupTeammateIdleTaskCompletedConfigChangeWorktreeCreateWorktreeRemovePostToolBatch

HookCallback

钩子回调函数的类型定义。

HookCallback = Callable[[HookInput, str | None, HookContext], Awaitable[HookJSONOutput]]

参数:

  • input:基于 hook_event_name 的强类型钩子输入,带可辨识联合(参见 HookInput
  • tool_use_id:可选的工具使用标识符(用于工具相关的钩子)
  • context:包含附加信息的钩子上下文

返回一个 HookJSONOutput,可能包含:

  • decision"block" 以阻止操作
  • systemMessage:显示给用户的警告消息
  • hookSpecificOutput:钩子特定的输出数据

HookContext

传递给钩子回调的上下文信息。

class HookContext(TypedDict):
    signal: Any | None  # Future: abort signal support

HookMatcher

将钩子匹配到特定事件或工具的配置。

@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_event_name 字段。

HookInput = (
    PreToolUseHookInput
    | PostToolUseHookInput
    | PostToolUseFailureHookInput
    | UserPromptSubmitHookInput
    | StopHookInput
    | SubagentStopHookInput
    | PreCompactHookInput
    | NotificationHookInput
    | SubagentStartHookInput
    | PermissionRequestHookInput
)

BaseHookInput

所有钩子输入类型中都存在的基础字段。

class BaseHookInput(TypedDict):
    session_id: str
    transcript_path: str
    cwd: str
    permission_mode: NotRequired[str]
字段类型描述
session_idstr当前会话标识符
transcript_pathstr会话记录文件路径
cwdstr当前工作目录
permission_modestr(可选)当前权限模式

PreToolUseHookInput

PreToolUse 钩子事件的输入数据。

class PreToolUseHookInput(BaseHookInput):
    hook_event_name: Literal["PreToolUse"]
    tool_name: str
    tool_input: dict[str, Any]
    tool_use_id: str
    agent_id: NotRequired[str]
    agent_type: NotRequired[str]
字段类型描述
hook_event_nameLiteral["PreToolUse"]始终为 "PreToolUse"
tool_namestr即将执行的工具名称
tool_inputdict[str, Any]工具的输入参数
tool_use_idstr此工具使用的唯一标识符
agent_idstr(可选)子代理标识符,钩子在子代理内触发时存在
agent_typestr(可选)子代理类型,钩子在子代理内触发时存在

PostToolUseHookInput

PostToolUse 钩子事件的输入数据。

class PostToolUseHookInput(BaseHookInput):
    hook_event_name: Literal["PostToolUse"]
    tool_name: str
    tool_input: dict[str, Any]
    tool_response: Any
    tool_use_id: str
    agent_id: NotRequired[str]
    agent_type: NotRequired[str]
字段类型描述
hook_event_nameLiteral["PostToolUse"]始终为 "PostToolUse"
tool_namestr已执行工具的名称
tool_inputdict[str, Any]使用的输入参数
tool_responseAny工具执行的响应
tool_use_idstr此工具使用的唯一标识符
agent_idstr(可选)子代理标识符,钩子在子代理内触发时存在
agent_typestr(可选)子代理类型,钩子在子代理内触发时存在

PostToolUseFailureHookInput

PostToolUseFailure 钩子事件的输入数据。当工具执行失败时调用。

class PostToolUseFailureHookInput(BaseHookInput):
    hook_event_name: Literal["PostToolUseFailure"]
    tool_name: str
    tool_input: dict[str, Any]
    tool_use_id: str
    error: str
    is_interrupt: NotRequired[bool]
    agent_id: NotRequired[str]
    agent_type: NotRequired[str]
字段类型描述
hook_event_nameLiteral["PostToolUseFailure"]始终为 "PostToolUseFailure"
tool_namestr失败工具的名称
tool_inputdict[str, Any]使用的输入参数
tool_use_idstr此工具使用的唯一标识符
errorstr失败执行的错误消息
is_interruptbool(可选)失败是否由中断引起
agent_idstr(可选)子代理标识符,钩子在子代理内触发时存在
agent_typestr(可选)子代理类型,钩子在子代理内触发时存在

UserPromptSubmitHookInput

UserPromptSubmit 钩子事件的输入数据。

class UserPromptSubmitHookInput(BaseHookInput):
    hook_event_name: Literal["UserPromptSubmit"]
    prompt: str
字段类型描述
hook_event_nameLiteral["UserPromptSubmit"]始终为 "UserPromptSubmit"
promptstr用户提交的提示

StopHookInput

Stop 钩子事件的输入数据。

class StopHookInput(BaseHookInput):
    hook_event_name: Literal["Stop"]
    stop_hook_active: bool
字段类型描述
hook_event_nameLiteral["Stop"]始终为 "Stop"
stop_hook_activebool停止钩子是否处于活跃状态

SubagentStopHookInput

SubagentStop 钩子事件的输入数据。

class SubagentStopHookInput(BaseHookInput):
    hook_event_name: Literal["SubagentStop"]
    stop_hook_active: bool
    agent_id: str
    agent_transcript_path: str
    agent_type: str
字段类型描述
hook_event_nameLiteral["SubagentStop"]始终为 "SubagentStop"
stop_hook_activebool停止钩子是否处于活跃状态
agent_idstr子代理的唯一标识符
agent_transcript_pathstr子代理记录文件的路径
agent_typestr子代理的类型

PreCompactHookInput

PreCompact 钩子事件的输入数据。

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压缩的自定义指令

NotificationHookInput

Notification 钩子事件的输入数据。

class NotificationHookInput(BaseHookInput):
    hook_event_name: Literal["Notification"]
    message: str
    title: NotRequired[str]
    notification_type: str
字段类型描述
hook_event_nameLiteral["Notification"]始终为 "Notification"
messagestr通知消息内容
titlestr(可选)通知标题
notification_typestr通知类型

SubagentStartHookInput

SubagentStart 钩子事件的输入数据。

class SubagentStartHookInput(BaseHookInput):
    hook_event_name: Literal["SubagentStart"]
    agent_id: str
    agent_type: str
字段类型描述
hook_event_nameLiteral["SubagentStart"]始终为 "SubagentStart"
agent_idstr子代理的唯一标识符
agent_typestr子代理的类型

PermissionRequestHookInput

PermissionRequest 钩子事件的输入数据。允许钩子以编程方式处理权限决策。

class PermissionRequestHookInput(BaseHookInput):
    hook_event_name: Literal["PermissionRequest"]
    tool_name: str
    tool_input: dict[str, Any]
    permission_suggestions: NotRequired[list[Any]]
字段类型描述
hook_event_nameLiteral["PermissionRequest"]始终为 "PermissionRequest"
tool_namestr请求权限的工具名称
tool_inputdict[str, Any]工具的输入参数
permission_suggestionslist[Any](可选)CLI 建议的权限更新

HookJSONOutput

钩子回调返回值的联合类型。

HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput

SyncHookJSONOutput

带控制和决策字段的同步钩子输出。

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[HookSpecificOutput]
Note

在 Python 代码中使用 continue_(带下划线)。发送到 CLI 时会自动转换为 continue

HookSpecificOutput

包含钩子事件名称和事件特定字段的 TypedDict。形状取决于 hookEventName 值。每个钩子事件可用字段的完整详情,请参见使用钩子控制执行

事件特定输出类型的可辨识联合。hookEventName 字段决定哪些字段有效。

class PreToolUseHookSpecificOutput(TypedDict):
    hookEventName: Literal["PreToolUse"]
    permissionDecision: NotRequired[Literal["allow", "deny", "ask", "defer"]]
    permissionDecisionReason: NotRequired[str]
    updatedInput: NotRequired[dict[str, Any]]
    additionalContext: NotRequired[str]


class PostToolUseHookSpecificOutput(TypedDict):
    hookEventName: Literal["PostToolUse"]
    additionalContext: NotRequired[str]
    updatedToolOutput: NotRequired[Any]
    updatedMCPToolOutput: NotRequired[Any]  # Deprecated: use updatedToolOutput, which works for all tools


class PostToolUseFailureHookSpecificOutput(TypedDict):
    hookEventName: Literal["PostToolUseFailure"]
    additionalContext: NotRequired[str]


class UserPromptSubmitHookSpecificOutput(TypedDict):
    hookEventName: Literal["UserPromptSubmit"]
    additionalContext: NotRequired[str]


class NotificationHookSpecificOutput(TypedDict):
    hookEventName: Literal["Notification"]
    additionalContext: NotRequired[str]


class SubagentStartHookSpecificOutput(TypedDict):
    hookEventName: Literal["SubagentStart"]
    additionalContext: NotRequired[str]


class PermissionRequestHookSpecificOutput(TypedDict):
    hookEventName: Literal["PermissionRequest"]
    decision: dict[str, Any]


HookSpecificOutput = (
    PreToolUseHookSpecificOutput
    | PostToolUseHookSpecificOutput
    | PostToolUseFailureHookSpecificOutput
    | UserPromptSubmitHookSpecificOutput
    | NotificationHookSpecificOutput
    | SubagentStartHookSpecificOutput
    | PermissionRequestHookSpecificOutput
)

AsyncHookJSONOutput

延迟钩子执行的异步钩子输出。

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

在 Python 代码中使用 async_(带下划线)。发送到 CLI 时会自动转换为 async

钩子使用示例

此示例注册两个钩子:一个阻止危险的 bash 命令(如 rm -rf /),另一个记录所有工具使用情况以供审计。安全钩子仅在 Bash 命令上运行(通过 matcher),而记录钩子在所有工具上运行。

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 不将这些导出为类型,但它们代表了消息中工具输入和输出的结构。

Agent

工具名称: Agent(之前为 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,  # Estimated 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[str, str | list[str]] | None,
    # User answers populated by the permission system. Multi-select
    # answers may be a list of labels or a comma-joined string
}

输出:

{
    "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
}

Monitor

工具名称: Monitor

运行后台脚本并将每行 stdout 作为事件发送给 Claude,使其无需轮询即可做出反应。Monitor 遵循与 Bash 相同的权限规则。行为和提供商可用性参见 Monitor 工具参考

输入:

{
    "command": str,  # Shell script; each stdout line is an event, exit ends the watch
    "description": str,  # Short description shown in notifications
    "timeout_ms": int | None,  # Kill after this deadline (default 300000, max 3600000)
    "persistent": bool | None,  # Run for the lifetime of the session; stop with TaskStop
}

输出:

{
    "taskId": str,  # ID of the background monitor task
    "timeoutMs": int,  # Timeout deadline in milliseconds (0 when persistent)
    "persistent": bool | None,  # True when running until TaskStop or session end
}

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
}

输出:

{
    "bytes": int,  # Size of the fetched content in bytes
    "code": int,  # HTTP response code
    "codeText": str,  # HTTP response code text
    "result": str,  # Processed result from applying the prompt to the content
    "durationMs": int,  # Time to fetch and process the content, in milliseconds
    "url": str,  # URL that was fetched
}

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
}

输出:

{
    "query": str,  # The search query
    "results": list[str | {"tool_use_id": str, "content": list[{"title": str, "url": str}]}],
    "durationSeconds": float,  # Search duration in seconds
}

TodoWrite

工具名称: TodoWrite

Note

从 Claude Code v2.1.142 起,TodoWrite 默认被禁用。请改用 TaskCreateTaskGetTaskUpdateTaskList。参见迁移到 Task 工具更新你的监控代码,或设置 CLAUDE_CODE_ENABLE_TASKS=0 恢复使用 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},
}

TaskCreate

工具名称: TaskCreate

输入:

{
    "subject": str,  # Short task title
    "description": str,  # Detailed task body
    "activeForm": str | None,  # Present-tense label shown while in progress
    "metadata": dict | None,  # Arbitrary caller metadata
}

输出:

{
    "task": {"id": str, "subject": str},  # Created task with assigned ID
}

TaskUpdate

工具名称: TaskUpdate

输入:

{
    "taskId": str,  # ID of the task to patch
    "status": Literal["pending", "in_progress", "completed", "deleted"] | None,
    "subject": str | None,
    "description": str | None,
    "activeForm": str | None,
    "addBlocks": list[str] | None,  # Task IDs this task now blocks
    "addBlockedBy": list[str] | None,  # Task IDs that now block this task
    "owner": str | None,
    "metadata": dict | None,
}

输出:

{
    "success": bool,
    "taskId": str,
    "updatedFields": list[str],  # Names of fields that changed
    "error": str | None,
    "statusChange": {"from": str, "to": str} | None,
}

TaskGet

工具名称: TaskGet

输入:

{
    "taskId": str,  # ID of the task to read
}

输出:

{
    "task": {
        "id": str,
        "subject": str,
        "description": str,
        "status": Literal["pending", "in_progress", "completed"],
        "blocks": list[str],
        "blockedBy": list[str],
    } | None,  # None when the ID is not found
}

TaskList

工具名称: TaskList

输入:

{}

输出:

{
    "tasks": [
        {
            "id": str,
            "subject": str,
            "status": Literal["pending", "in_progress", "completed"],
            "owner": str | None,
            "blockedBy": list[str],
        }
    ],
}

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 = 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 - the session retains all previous messages
            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())

使用钩子进行行为修改

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 a timestamp as additional context for Claude to see
    from datetime import datetime

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    return {
        "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": f"[Submitted at {timestamp}] Original prompt: {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
        async for message in client.receive_response():
            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("Completed tool execution")
                    elif isinstance(block, TextBlock):
                        print(f"Claude says: {block.text[:100]}...")

        print("Task completed!")


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(
        "Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"
    )
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为命令执行启用沙盒模式
autoAllowBashIfSandboxedboolTrue沙盒启用时自动批准 bash 命令
excludedCommandslist[str][]始终绕过沙盒限制的命令(例如 ["docker"])。这些命令会自动以非沙盒方式运行,无需模型参与
allowUnsandboxedCommandsboolTrue允许模型请求在沙盒外运行命令。为 True 时,模型可在工具输入中设置 dangerouslyDisableSandbox,这会回退到权限系统
networkSandboxNetworkConfigNone网络特定的沙盒配置
ignoreViolationsSandboxIgnoreViolationsNone配置要忽略哪些沙盒违规
enableWeakerNestedSandboxboolFalse启用较弱的嵌套沙盒以提高兼容性

使用示例

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

Unix socket 安全allowUnixSockets 选项可以授予对强大系统服务的访问权限。例如,允许 /var/run/docker.sock 实际上通过 Docker API 授予对主机系统的完全访问权限,绕过沙盒隔离。仅允许严格必要的 Unix socket,并了解每个的安全影响。

SandboxNetworkConfig

沙盒模式的网络特定配置。

class SandboxNetworkConfig(TypedDict, total=False):
    allowedDomains: list[str]
    deniedDomains: list[str]
    allowManagedDomainsOnly: bool
    allowUnixSockets: list[str]
    allowAllUnixSockets: bool
    allowLocalBinding: bool
    allowMachLookup: list[str]
    httpProxyPort: int
    socksProxyPort: int
属性类型默认值描述
allowedDomainslist[str][]沙盒进程可访问的域名
deniedDomainslist[str][]沙盒进程不可访问的域名。优先于 allowedDomains
allowManagedDomainsOnlyboolFalse仅托管设置:在托管设置中设置时,忽略非托管设置源的 allowedDomains。通过 SDK 选项设置时无效果
allowUnixSocketslist[str][]进程可访问的 Unix socket 路径(例如 Docker socket)
allowAllUnixSocketsboolFalse允许访问所有 Unix socket
allowLocalBindingboolFalse允许进程绑定到本地端口(例如用于开发服务器)
allowMachLookuplist[str][]仅 macOS:允许的 XPC/Mach 服务名称。支持尾部通配符
httpProxyPortintNone网络请求的 HTTP 代理端口
socksProxyPortintNone网络请求的 SOCKS 代理端口
Note

内置沙盒代理基于请求的主机名强制执行网络允许列表,不会终止或检查 TLS 流量,因此 domain fronting 等技术可能绕过它。详情参见沙盒安全限制,配置 TLS 终止代理参见安全部署

SandboxIgnoreViolations

忽略特定沙盒违规的配置。

class SandboxIgnoreViolations(TypedDict, total=False):
    file: list[str]
    network: list[str]
属性类型默认值描述
filelist[str][]要忽略违规的文件路径模式
networklist[str][]要忽略违规的网络模式

非沙盒命令的权限回退

allowUnsandboxedCommands 启用时,模型可以通过在工具输入中设置 dangerouslyDisableSandbox: True 来请求在沙盒外运行命令。这些请求会回退到现有的权限系统,这意味着你的 can_use_tool 处理程序将被调用,允许你实现自定义授权逻辑。

Note

excludedCommandsallowUnsandboxedCommands 的区别:

  • excludedCommands:始终自动绕过沙盒的静态命令列表(例如 ["docker"])。模型对此没有控制权。
  • allowUnsandboxedCommands:允许模型在运行时通过在工具输入中设置 dangerouslyDisableSandbox: True 来决定是否请求非沙盒执行。
from claude_agent_sdk import (
    query,
    ClaudeAgentOptions,
    HookMatcher,
    PermissionResultAllow,
    PermissionResultDeny,
    ToolPermissionContext,
)


async def can_use_tool(
    tool: str, input: dict, context: ToolPermissionContext
) -> PermissionResultAllow | PermissionResultDeny:
    # Check if the model is requesting to bypass the sandbox
    if tool == "Bash" and input.get("dangerouslyDisableSandbox"):
        # The model is requesting to run this command outside the sandbox
        print(f"Unsandboxed command requested: {input.get('command')}")

        if is_command_authorized(input.get("command")):
            return PermissionResultAllow()
        return PermissionResultDeny(
            message="Command not authorized for unsandboxed execution"
        )
    return PermissionResultAllow()


# Required: dummy hook keeps the stream open for can_use_tool
async def dummy_hook(input_data, tool_use_id, context):
    return {"continue_": True}


async def prompt_stream():
    yield {
        "type": "user",
        "message": {"role": "user", "content": "Deploy my application"},
    }


async def main():
    async for message in query(
        prompt=prompt_stream(),
        options=ClaudeAgentOptions(
            sandbox={
                "enabled": True,
                "allowUnsandboxedCommands": True,  # Model can request unsandboxed execution
            },
            permission_mode="default",
            can_use_tool=can_use_tool,
            hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},
        ),
    ):
        print(message)

此模式使你能够:

  • 审计模型请求:记录模型何时请求非沙盒执行
  • 实现允许列表:仅允许特定命令以非沙盒方式运行
  • 添加审批工作流:对特权操作要求显式授权
Warning

dangerouslyDisableSandbox: True 运行的命令具有完全的系统访问权限。确保你的 can_use_tool 处理程序仔细验证这些请求。

如果 permission_mode 设置为 bypassPermissionsallow_unsandboxed_commands 已启用,模型可以在没有任何审批提示的情况下自主执行沙盒外的命令。此组合实际上允许模型静默逃脱沙盒隔离。

另请参见