Token导航 LogoToken导航

Agent Skill · 研究检索

claude-agent-sdk-python(Claude Agent SDK Python 搜索)

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

claude-agent-sdk-python 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为调用外部服务;许可证信息还不明确,第三方扫描有提醒项,按安装量在研究检索类的 73,675 个 Skill 里排第 65,612。

总安装 279周安装 12GitHub Stars 6下载 98核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:claude-agent-sdk-python(Claude Agent SDK Python 搜索)
来源仓库:https://github.com/waltersumbon/claude-agent-sdk-skill
仓库路径:skills/claude-agent-sdk-python
安装命令:
npx skills add https://github.com/waltersumbon/claude-agent-sdk-skill --skill claude-agent-sdk-python
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/waltersumbon/claude-agent-sdk-skill --skill claude-agent-sdk-python

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

claude-agent-sdk-python 提供 Python 环境下构建 Claude Agent 的生产级指导。涵盖消息类型定义、流式响应处理与工具调用封装。支持异步交互与错误重试机制,适合集成到后端服务中。使用前需安装 claude-agent-sdk 包并配置 API 访问凭证。

适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

来源仓库内路径:skills/claude-agent-sdk-python

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/waltersumbon/claude-agent-sdk-skill --skill cl…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要调用外部服务,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

claude-agent-sdk-python 怎么安装?

在终端执行 npx skills add https://github.com/waltersumbon/claude-agent-sdk-skill --skill claude-agent…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

claude-agent-sdk-python 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

claude-agent-sdk-python 需要什么权限?

权限级别是调用外部服务。该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

claude-agent-sdk-python 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

claude-agent-sdk-python 用的人多吗?

公开数据是累计安装 279 次,近一周安装 12 次,下载 98 次,GitHub 6 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

claude-agent-sdk-python 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
claude-agent-sdk-python

Claude Agent SDK Python 搜索 · 本页

2796调用外部服务未明确有提醒

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Claude Agent SDK — Python Guide

Production guidance for building AI agents with the Claude Agent SDK in Python.

Naming: The Claude Code SDK was renamed to the Claude Agent SDK (v0.1.0+). Package: pip install claude-agent-sdk · Import: from claude_agent_sdk import...

Message Types

All message types for type checking and isinstance() checks:

from claude_agent_sdk import (
    AssistantMessage,     # Claude's text/tool responses
    ResultMessage,        # Final result with subtype (success/error/cancelled)
    SystemMessage,        # System events (session_id, etc.)
    UserMessage,          # User prompts
    ToolUseMessage,       # Tool invocation requests
    ToolResultMessage,    # Tool execution results
)

Quick Reference — Two Interaction Modes

1. query() — Stateless, One-Shot

Best for: independent tasks, automation scripts, CI pipelines.

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage

async def main():
    async for message in query(
        prompt="Review utils.py for bugs. Fix any issues you find.",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Glob"],
            permission_mode="acceptEdits",
        ),
    ):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if hasattr(block, "text"):
                    print(block.text)
                elif hasattr(block, "name"):
                    print(f"Tool: {block.name}")
        elif isinstance(message, ResultMessage):
            print(f"Done: {message.subtype}")

asyncio.run(main())

2. ClaudeSDKClient — Stateful, Multi-Turn

Best for: conversations, follow-up questions, interactive apps.

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

async with ClaudeSDKClient(
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Write", "Bash"],
        permission_mode="acceptEdits",
    )
) as client:
    await client.query("Analyze the codebase structure")
    async for msg in client.receive_messages():
        print(msg)
    # Continue the conversation with context preserved
    await client.query("Now refactor the largest file you found")
    async for msg in client.receive_messages():
        print(msg)

ClaudeAgentOptions — Complete Configuration

All options are optional. Key fields:

FieldTypeDescription
allowed_tools`list[str] \None`Tools Claude can use. See Built-in Tools below.
disallowed_tools`list[str] \None`Explicitly block specific tools.
permission_mode`"default" \"acceptEdits" \"bypassPermissions"`Permission strategy.
system_prompt`str \dict \None`Custom instructions. Use {"type": "preset", "preset": "claude_code"} for CC default.
model`str \None`e.g. "sonnet", "opus", "haiku", or full model string.
cwd`str \Path \None`Working directory for the agent.
max_turns`int \None`Maximum agentic loop iterations.
setting_sources`list[Literal["user", "project"]] \None`["user", "project"] to load Skills/CLAUDE.md from filesystem.
mcp_servers`dict \None`MCP server configurations.
agents`dict[str, AgentDefinition] \None`Named subagent definitions.
hooks`dict \None`Lifecycle hook callbacks.

Built-in Tools

Tool names for allowed_tools:

  • File ops: Read, Write, Edit, MultiEdit
  • Search: Glob, Grep
  • Execution: Bash
  • Web: WebSearch, WebFetch
  • Delegation: Task (required for subagents)
  • Skills: Skill (requires setting_sources)

Custom Tools via SDK MCP Server

Define in-process tools without a separate MCP server process:

from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions

@tool("search_orders", "Search orders by customer ID", {"customer_id": str, "status": str})
async def search_orders(args):
    results = await db.query_orders(args["customer_id"], args.get("status"))
    return {"content": [{"type": "text", "text": json.dumps(results)}]}

@tool("send_email", "Send an email notification", {"to": str, "subject": str, "body": str})
async def send_email(args):
    await email_service.send(args["to"], args["subject"], args["body"])
    return {"content": [{"type": "text", "text": f"Email sent to {args['to']}"}]}

server = create_sdk_mcp_server(name="business-tools", tools=[search_orders, send_email])

options = ClaudeAgentOptions(
    mcp_servers={"biz": server},
    allowed_tools=["mcp__biz__search_orders", "mcp__biz__send_email"],
)

Tool naming convention: MCP tools are accessed as mcp__<server-name>__<tool-name>.

Subagents

Delegate specialized tasks to isolated agents with their own context and tool permissions:

from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

async for message in query(
    prompt="Review auth module for security issues, then write tests",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Grep", "Glob", "Task"],  # Task is required
        agents={
            "security-reviewer": AgentDefinition(
                description="Security specialist. Use for vulnerability analysis.",
                prompt="You are a security expert. Analyze code for OWASP Top 10...",
                tools=["Read", "Grep", "Glob"],
                model="opus",
            ),
            "test-writer": AgentDefinition(
                description="Test specialist. Use to generate test suites.",
                prompt="You are a testing expert. Write comprehensive unit tests...",
                tools=["Read", "Write", "Bash"],
                model="sonnet",
            ),
        },
    ),
):
    print(message)

Factory pattern for dynamic agents:

def create_reviewer(language: str) -> AgentDefinition:
    return AgentDefinition(
        description=f"{language} code review specialist",
        prompt=f"You are an expert {language} developer...",
        tools=["Read", "Grep", "Glob"],
        model="opus" if language in ["rust", "c++"] else "sonnet",
    )

Hooks — Lifecycle Callbacks

Available events: PreToolUse, PostToolUse, Stop, SessionStart, SessionEnd, UserPromptSubmit.

from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

async def block_dangerous_commands(input_data, tool_use_id, context):
    """Block destructive bash commands."""
    if input_data.get("tool_name") == "Bash":
        cmd = input_data.get("tool_input", {}).get("command", "")
        if any(danger in cmd for danger in ["rm -rf /", "DROP TABLE", "mkfs"]):
            return {
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": f"Blocked dangerous command: {cmd}",
                }
            }
    return {}

async def audit_log(input_data, tool_use_id, context):
    """Log all tool usage for auditing."""
    with open("audit.log", "a") as f:
        f.write(f"{input_data.get('tool_name')}: {input_data.get('tool_input')}\n")
    return {}

options = ClaudeAgentOptions(
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="Bash", hooks=[block_dangerous_commands]),
            HookMatcher(matcher=".*", hooks=[audit_log]),
        ]
    }
)

MCP Integration (External Servers)

options = ClaudeAgentOptions(
    mcp_servers={
        "github": {
            "type": "stdio",
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-github"],
            "env": {"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")},
        },
        "postgres": {
            "type": "stdio",
            "command": "docker",
            "args": ["run", "mcp-postgres-server"],
            "env": {"DATABASE_URL": os.getenv("DATABASE_URL")},
        },
    },
    allowed_tools=["mcp__github", "mcp__postgres"],
)

You can mix SDK MCP servers (in-process) and external MCP servers in the same config.

Using Skills in the SDK

Skills are filesystem-based and must be explicitly enabled:

options = ClaudeAgentOptions(
    cwd="/path/to/project",
    setting_sources=["user", "project"],  # REQUIRED — loads Skills from filesystem
    allowed_tools=["Skill", "Read", "Write", "Bash"],
)

Common mistake: forgetting setting_sources. Without it, Skills won't be discovered even if "Skill" is in allowed_tools.

Skill locations:

  • Project: .claude/skills/*/SKILL.md (shared via git)
  • User: ~/.claude/skills/*/SKILL.md (personal, cross-project)

Note: The allowed-tools field in SKILL.md frontmatter only works in Claude Code CLI, not in the SDK. Use allowed_tools in ClaudeAgentOptions to control tool access.

Sessions and Conversation Management

from claude_agent_sdk import query, ClaudeAgentOptions

session_id = None

# First interaction — capture session_id
async for message in query(
    prompt="Review this codebase and identify the top 3 issues",
    options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
):
    if message.type == "system" and hasattr(message, "session_id"):
        session_id = message.session_id
    print(message)

# Resume with context
async for message in query(
    prompt="Now fix issue #1 that you found",
    options=ClaudeAgentOptions(
        session_id=session_id,
        allowed_tools=["Read", "Edit", "Bash"],
        permission_mode="acceptEdits",
    ),
):
    print(message)

System Prompt Configuration

# 1. Custom system prompt (v0.1.0+ default: minimal prompt)
options = ClaudeAgentOptions(system_prompt="You are a senior Python engineer...")

# 2. Claude Code's full system prompt (opt-in)
options = ClaudeAgentOptions(
    system_prompt={"type": "preset", "preset": "claude_code"}
)

# 3. No system prompt — SDK default (minimal)
options = ClaudeAgentOptions()  # uses minimal built-in prompt

Breaking change in v0.1.0: The SDK no longer loads Claude Code's system prompt by default. If you need the old behavior, explicitly set preset: "claude_code".

Authentication

# Direct API (default)
export ANTHROPIC_API_KEY=your-api-key

# Amazon Bedrock
export CLAUDE_CODE_USE_BEDROCK=1
# + configure AWS credentials

# Google Vertex AI
export CLAUDE_CODE_USE_VERTEX=1
# + configure GCP credentials

# Microsoft Azure AI Foundry
export CLAUDE_CODE_USE_FOUNDRY=1
# + configure Azure credentials

Common Patterns

Batch Processing (Parallel Agents)

import asyncio

async def process_file(filepath: str):
    async for msg in query(
        prompt=f"Review {filepath} for security issues",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Grep"],
            max_turns=50,
        ),
    ):
        if isinstance(msg, ResultMessage):
            return msg.result

results = await asyncio.gather(
    process_file("auth.py"),
    process_file("payments.py"),
    process_file("users.py"),
)

Structured Output Collection

messages = []
async for msg in query(prompt="Analyze this codebase", options=options):
    messages.append(msg)

# Extract final result
result = next((m for m in reversed(messages) if hasattr(m, "result")), None)

Error Handling

Available exception types:

  • CLINotFoundError — Claude Code CLI binary not found in PATH
  • CLIConnectionError — Failed to connect to CLI process
  • Standard Python exceptions (e.g., asyncio.TimeoutError) may also be raised
from claude_agent_sdk import CLINotFoundError, CLIConnectionError

try:
    async for msg in query(prompt="...", options=options):
        print(msg)
except CLINotFoundError:
    print("Claude Code CLI not found. Install: curl -fsSL https://claude.ai/install.sh | bash")
except CLIConnectionError as e:
    print(f"Connection error: {e}")

Migration from Claude Code SDK (< v0.1.0)

Key changes:

  1. ClaudeCodeOptions → ClaudeAgentOptions
  2. System prompt no longer loads Claude Code's prompt by default
  3. setting_sources must be explicitly set (was auto-loaded before)
  4. Import path unchanged (claude_agent_sdk), but class names changed

Best Practices

  1. Principle of least privilege: Only grant tools the agent actually needs.
  2. Use permission_mode="acceptEdits" for automation, "default" for interactive use.
  3. Prefer SDK MCP servers over external ones for custom tools — less overhead, easier debugging.
  4. Use subagents for specialized tasks — isolate context and apply the right model per task.
  5. Add hooks for safety — block dangerous commands and audit tool usage in production.
  6. Set max_turns to prevent runaway agents in production environments.
  7. Use cwd to scope the agent to a specific directory.
  8. Capture session_id from system messages if you need conversation continuity.
For troubleshooting common issues, see references/troubleshooting.md.

Official Resources

平台分布

Codex

34.65%
按下载量换算34

Claude

31.68%
按下载量换算31

Cursor

20.22%
按下载量换算20

Gemini CLI

10.72%
按下载量换算11

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

调用外部服务

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills