概述

Claude Agent SDK 是 Anthropic 提供的 Python/TypeScript 開發框架,讓開發者能以程式化方式使用 Claude Code 的所有能力,建立各種自動化代理。

🚀
核心價值
  • 提供與 Claude Code 相同的工具和能力
  • 程式化控制 Agent 行為
  • 可整合到 CI/CD、自動化流程、生產環境
  • 支援自訂工具、Hooks、MCP 整合

什麼時候使用 SDK?

場景 使用 Claude Code CLI 使用 Agent SDK
互動式開發
自動化流程
整合到產品
批次處理
自訂工具/Hooks

前置需求

系統需求

  • Python 3.10 或更高版本
  • Claude Code CLI(SDK 會自動捆綁)

安裝方式

pip install claude-agent-sdk
Claude Code CLI 會自動捆綁在套件中,無需單獨安裝。

計費方式

Claude Agent SDK 可以使用 Pro/Max 訂閱額度,不一定需要 API Key。

兩種計費模式

模式 認證方式 計費 適用情況
訂閱制 Claude Pro/Max 登入 使用訂閱額度 個人使用、學習、實驗
API 制 ANTHROPIC_API_KEY 按 token 計費 大量使用、整合到產品
如果設定了 ANTHROPIC_API_KEY 環境變數,會優先使用 API 計費而非訂閱。
1

第一階段:基礎理解

理解 SDK 架構、核心 API、工具系統

核心概念

SDK 架構

┌─────────────────────────────────────────┐
│            Claude API / 模型            │
└─────────────────────────────────────────┘
                    ↑
┌─────────────────────────────────────────┐
│         Claude Code CLI(核心引擎)      │
│    (工具呼叫、檔案操作、bash 執行)      │
└─────────────────────────────────────────┘
              ↑               ↑
    ┌─────────┴───┐     ┌─────┴─────────┐
    │ Claude Code │     │ Agent SDK     │
    │ (人用介面)│     │ (程式用介面) │
    └─────────────┘     └───────────────┘

核心元件

  • query():一次性查詢函數,每次創建新 session
  • ClaudeSDKClient:持續對話客戶端,保留 context
  • ClaudeAgentOptions:配置選項
  • 內建工具:Read、Write、Edit、Bash、Glob、Grep 等

query() vs ClaudeSDKClient

特性 query() ClaudeSDKClient
Session 每次新建 重用相同 session
對話連貫性 單次交互 多輪交互
Hooks 支援
自訂工具
使用場景 一次性任務 交互應用、chatbot

query() 範例

import anyio
from claude_agent_sdk import query

async def main():
    async for message in query(prompt="What is 2 + 2?"):
        print(message)

anyio.run(main)

ClaudeSDKClient 範例

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Write"],
        permission_mode="acceptEdits"
    )

    async with ClaudeSDKClient(options=options) as client:
        # 第一輪對話
        await client.query("讀取 config.py 檔案")
        async for message in client.receive_response():
            print(message)

        # 第二輪對話(Claude 記得上一輪)
        await client.query("在該檔案中加入新的設定")
        async for message in client.receive_response():
            print(message)

配置選項 (ClaudeAgentOptions)

工具與權限

參數 類型 說明
allowed_tools list[str] 允許的工具列表
disallowed_tools list[str] 禁止的工具列表
permission_mode str default | acceptEdits | bypassPermissions | plan

模型與配置

參數 類型 說明
model str 模型選擇
system_prompt str 系統提示詞
max_turns int 最大對話輪數
max_budget_usd float 預算上限(美元)
cwd str | Path 工作目錄
2

第二階段:實作練習

動手寫程式,從 Hello World 到進階功能

Hello World

練習 1:基本查詢

import anyio
from claude_agent_sdk import query

async def hello_world():
    async for message in query(prompt="用繁體中文說 Hello World"):
        print(message)

anyio.run(hello_world)

練習 2:使用工具

from claude_agent_sdk import query, ClaudeAgentOptions

async def use_tools():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Glob"],
        cwd="/path/to/your/project"
    )

    async for message in query(
        prompt="列出這個目錄下所有的 Python 檔案",
        options=options
    ):
        print(message)

anyio.run(use_tools)

練習 3:檔案操作

from claude_agent_sdk import query, ClaudeAgentOptions

async def file_operations():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Write", "Edit"],
        permission_mode="acceptEdits"  # 自動接受編輯
    )

    async for message in query(
        prompt="建立一個 hello.py 檔案,內容是印出 Hello World",
        options=options
    ):
        print(message)

anyio.run(file_operations)

自訂工具

使用 @tool 裝飾器定義 Claude 可以呼叫的工具:

from claude_agent_sdk import (
    tool,
    create_sdk_mcp_server,
    ClaudeAgentOptions,
    ClaudeSDKClient
)

# 定義工具
@tool("greet", "向使用者打招呼", {"name": str})
async def greet_user(args):
    return {
        "content": [
            {"type": "text", "text": f"你好,{args['name']}!"}
        ]
    }

@tool("calculate", "計算數學表達式", {"expression": str})
async def calculate(args):
    try:
        result = eval(args["expression"], {"__builtins__": {}})
        return {
            "content": [
                {"type": "text", "text": f"計算結果:{result}"}
            ]
        }
    except Exception as e:
        return {
            "content": [
                {"type": "text", "text": f"計算錯誤:{str(e)}"}
            ]
        }

# 建立 SDK MCP 伺服器
server = create_sdk_mcp_server(
    name="my-tools",
    version="1.0.0",
    tools=[greet_user, calculate]
)

# 使用自訂工具
async def main():
    options = ClaudeAgentOptions(
        mcp_servers={"tools": server},
        allowed_tools=["mcp__tools__greet", "mcp__tools__calculate"]
    )

    async with ClaudeSDKClient(options=options) as client:
        await client.query("向 Kevin 打招呼,然後計算 123 * 456")
        async for msg in client.receive_response():
            print(msg)
SDK MCP 伺服器在同一進程中運行,無需管理子進程,效能更好。

Hooks 系統

Hooks 讓你在 Agent 執行過程中插入自訂邏輯:

可用 Hook 事件

事件 觸發時機 用途
PreToolUse 工具執行前 阻止危險操作、修改輸入
PostToolUse 工具執行後 審計日誌、結果處理
UserPromptSubmit 使用者提交 輸入驗證
Stop 代理停止 清理資源

安全檢查範例

from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, HookMatcher

async def block_dangerous_commands(input_data, tool_use_id, context):
    if input_data['hook_event_name'] != 'PreToolUse':
        return {}

    if input_data['tool_name'] != 'Bash':
        return {}

    command = input_data['tool_input'].get('command', '')
    dangerous_patterns = ['rm -rf', 'format', 'dd if=/dev/']

    for pattern in dangerous_patterns:
        if pattern in command:
            return {
                'hookSpecificOutput': {
                    'hookEventName': 'PreToolUse',
                    'permissionDecision': 'deny',
                    'permissionDecisionReason': f'危險命令已阻止:{pattern}'
                }
            }
    return {}

# 使用 Hook
options = ClaudeAgentOptions(
    allowed_tools=["Bash", "Read", "Write"],
    hooks={
        'PreToolUse': [
            HookMatcher(matcher='Bash', hooks=[block_dangerous_commands])
        ]
    }
)

審計日誌範例

from datetime import datetime

async def audit_logger(input_data, tool_use_id, context):
    log_entry = {
        'timestamp': datetime.now().isoformat(),
        'event': input_data['hook_event_name'],
        'tool': input_data.get('tool_name', 'N/A'),
        'session': input_data.get('session_id', 'N/A')
    }
    print(f"[AUDIT] {log_entry}")
    return {}
3

第三階段:進階功能

MCP 整合、Subagents、權限管理

MCP 整合

MCP(Model Context Protocol)讓 Agent 連接外部服務:

三種傳輸類型

類型 說明 適用場景
Stdio 本地進程 本機工具、CLI 程式
HTTP/SSE 遠端服務 雲端 API、外部服務
SDK MCP Server 程式內 tools 自訂工具、無需子進程

Stdio 範例(GitHub MCP)

import os
from claude_agent_sdk import query, ClaudeAgentOptions

options = ClaudeAgentOptions(
    mcp_servers={
        "github": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-github"],
            "env": {
                "GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]
            }
        }
    },
    allowed_tools=["mcp__github__list_issues", "mcp__github__search_issues"]
)

HTTP 範例

options = ClaudeAgentOptions(
    mcp_servers={
        "api": {
            "type": "http",
            "url": "https://api.example.com/mcp",
            "headers": {
                "Authorization": f"Bearer {API_TOKEN}"
            }
        }
    },
    allowed_tools=["mcp__api__*"]
)

Subagents

Subagents 讓你定義專門的子代理,處理特定任務:

from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Grep", "Glob", "Task"],
    agents={
        "code-reviewer": AgentDefinition(
            description="程式碼審查專家,專門檢查品質、安全性和可維護性",
            prompt="""你是程式碼審查專家。你的任務是:
            - 識別潛在的安全漏洞
            - 檢查效能問題
            - 驗證編碼風格""",
            tools=["Read", "Grep", "Glob"],
            model="sonnet"
        ),
        "test-runner": AgentDefinition(
            description="測試執行專家,執行和分析測試套件",
            prompt="你是測試執行專家...",
            tools=["Bash", "Read", "Grep"]
        )
    }
)

Subagent 特性

  • Context 隔離:每個 subagent 有獨立 context
  • 並列執行:多個 subagent 可同時執行
  • 工具限制:可指定允許的工具集
  • 不可遞歸:Subagent 不能生成子 subagent

權限管理

權限模式

模式 行為 使用場景
default 無自動批准 預設安全模式
acceptEdits 自動批准檔案編輯 開發工作流
bypassPermissions 所有工具無提示執行 ⚠ 極危險,只用於受信任環境
plan 禁止執行,只規劃 代碼審查、審批工作流
bypassPermissions 模式會讓 Agent 執行任何命令,包括危險操作。只在完全受控的環境中使用。
4

第四階段:實戰應用

實戰案例與專案整合

實戰案例

案例 1:Bug 修復 Agent

from claude_agent_sdk import query, ClaudeAgentOptions

async def bug_fixer():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Edit", "Glob", "Grep"],
        permission_mode="acceptEdits",
        system_prompt="你是一個 Bug 修復專家。仔細分析程式碼,找出並修復問題。"
    )

    async for message in query(
        prompt="審查 src/utils.py 中的 bug,修復任何問題",
        options=options
    ):
        print(message)

案例 2:代碼審查系統

from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

async def code_review_system():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Glob", "Grep", "Task"],
        agents={
            "style-checker": AgentDefinition(
                description="程式碼風格和格式檢查",
                prompt="檢查 PEP 8 合規性、命名慣例、程式碼組織...",
                tools=["Read", "Grep", "Glob"]
            ),
            "security-scanner": AgentDefinition(
                description="安全漏洞掃描",
                prompt="查找常見安全問題:SQL injection、XSS、敏感資料外洩...",
                tools=["Read", "Grep", "Glob"]
            ),
            "performance-analyzer": AgentDefinition(
                description="效能分析",
                prompt="識別效能問題:N+1 查詢、記憶體洩漏、阻塞操作...",
                tools=["Read", "Bash", "Grep"]
            )
        }
    )

    async for message in query(
        prompt="對 src/ 目錄進行完整的程式碼審查",
        options=options
    ):
        print(message)

案例 3:安全 Agent(帶 Hooks)

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, HookMatcher

async def validate_bash(input_data, tool_use_id, context):
    if input_data['tool_name'] != 'Bash':
        return {}

    command = input_data['tool_input'].get('command', '')
    dangerous = ['rm -rf', 'format', 'dd if=/dev/', 'chmod 777']

    for pattern in dangerous:
        if pattern in command:
            return {
                'hookSpecificOutput': {
                    'hookEventName': 'PreToolUse',
                    'permissionDecision': 'deny',
                    'permissionDecisionReason': f'危險命令:{pattern}'
                }
            }
    return {}

async def secure_agent():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Edit", "Bash", "Glob"],
        hooks={
            'PreToolUse': [
                HookMatcher(matcher='Bash', hooks=[validate_bash])
            ]
        }
    )

    async with ClaudeSDKClient(options=options) as client:
        await client.query("執行部署任務")
        async for msg in client.receive_response():
            print(msg)

專案整合構想

專案/場景 Agent 應用 複雜度
Research_zoo 自動整理 Fleeting Notes、生成研究摘要 ★★
估價報告處理 自動從 PDF 擷取資料、填入模板 ★★★
MOPS 公告監控 自動分析公告內容、生成摘要通知 ★★
個人助理 整合行事曆、記帳、筆記等日常任務 ★★★★
程式碼審查 自動審查 PR、安全掃描、風格檢查 ★★★

API 參考

query(prompt, options?) -> AsyncIterator[Message]

一次性查詢 Claude Code,每次創建新 session。

參數

  • prompt (str): 查詢內容
  • options (ClaudeAgentOptions): 配置選項

回傳

AsyncIterator of Message objects

ClaudeSDKClient(options?) -> AsyncContextManager

持續對話客戶端,支援多輪對話、Hooks、自訂工具。

方法

  • query(prompt): 發送查詢
  • receive_response(): 接收回應
  • interrupt(): 中斷執行
@tool(name, description, parameters)

裝飾器,定義自訂工具。

參數

  • name (str): 工具名稱
  • description (str): 工具描述
  • parameters (dict): 參數定義

工具參考

工具 用途 關鍵參數
Read 讀取檔案 file_path, offset, limit
Write 寫入檔案 file_path, content
Edit 編輯檔案 file_path, old_string, new_string
Bash 執行命令 command, timeout
Glob 檔案搜尋 pattern, path
Grep 內容搜尋 pattern, path, output_mode
WebSearch 網頁搜尋 query
WebFetch 擷取網頁 url, prompt
Task 呼叫子代理 description, prompt, subagent_type

延伸資源

官方文件

GitHub 資源

相關研究筆記

  • 2026-01-06-Anthropic-Agent-SDK深度研究
  • 2026-01-31-主流AI-Agent-SDK生態系比較與認證計費模式分析
  • 2026-01-31-Claude-Agent-SDK完整學習指南與實作計畫