Claude Agent SDK 入門:建構你的 AI Agent

Claude Agent SDK 是 Anthropic 推出的開發套件,讓你能以程式化方式建構 AI Agent。它將驅動 Claude Code 的核心引擎——包括 Agent 迴圈、內建工具、Context 管理——全部封裝成可程式化的 Library,支援 TypeScript 與 Python 兩種語言。本篇將帶你從零開始,了解 Agent SDK 的核心概念、安裝方式、Tool 定義、Agent 生命週期,並透過完整範例實際建構一個 AI Agent。

什麼是 Claude Agent SDK?

Claude Agent SDK(前身為 Claude Code SDK)是 Anthropic 官方提供的開發套件,讓開發者能建構具有自主能力的 AI Agent。這些 Agent 可以自動讀取檔案、執行終端指令、搜尋網頁、編輯程式碼等,無需你手動實作工具執行邏輯。簡單來說,Agent SDK 就是把 Claude Code 的能力開放給你,讓你能在自己的應用程式中嵌入同等級的 AI 自動化能力。

Agent SDK vs Client SDK vs Claude Code CLI

Anthropic 提供了多種方式與 Claude 互動,它們之間的定位各不相同。以下整理三者的差異,幫助你選擇適合的工具:

比較項目Client SDKAgent SDKClaude Code CLI
定位API 直接存取內建工具的 Agent 框架互動式開發工具
工具執行需自行實作 Tool LoopClaude 自主處理Claude 自主處理
適用場景自訂 API 整合CI/CD、自動化、產品嵌入日常開發、一次性任務
程式語言Python / TypeScriptPython / TypeScript終端指令

用一段程式碼來說明 Client SDK 與 Agent SDK 的差異:

// Client SDK:你需要自己實作 Tool Loop
let response = await client.messages.create({ ...params });
while (response.stop_reason === "tool_use") {
  const result = yourToolExecutor(response.tool_use);
  response = await client.messages.create({ tool_result: result, ...params });
}

// Agent SDK:Claude 自主處理工具呼叫
for await (const message of query({
  prompt: "Fix the bug in auth.py"
})) {
  console.log(message);
}

安裝與環境設定

前置需求

  • Node.js 18+(TypeScript 版本)
  • Python 3.10+(Python 版本)
  • Anthropic API Key:從 Claude Console 取得

安裝套件

根據你使用的程式語言,選擇對應的安裝方式:

# TypeScript
npm install @anthropic-ai/claude-agent-sdk

# Python(使用 pip)
pip install claude-agent-sdk

# Python(使用 uv,推薦)
uv init && uv add claude-agent-sdk

設定 API Key

安裝完成後,你需要設定 Anthropic API Key 作為環境變數。Agent SDK 也支援透過第三方雲端服務進行驗證,包括 Amazon Bedrock、Google Vertex AI 與 Microsoft Azure:

# 設定 API Key 環境變數
export ANTHROPIC_API_KEY=your-api-key

# 或建立 .env 檔案
echo "ANTHROPIC_API_KEY=your-api-key" > .env

# 若使用 Amazon Bedrock
export CLAUDE_CODE_USE_BEDROCK=1

# 若使用 Google Vertex AI
export CLAUDE_CODE_USE_VERTEX=1

建構你的第一個 Agent

Agent SDK 的核心進入點是 query 函式。它建立一個 Agentic Loop(代理迴圈),以串流方式回傳 Claude 工作過程中的每一個訊息,包括推理過程、工具呼叫、工具結果與最終輸出。

基本 Agent 範例(TypeScript)

以下範例建立一個能讀取並修復程式碼 Bug 的 Agent:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
  options: {
    allowedTools: ["Read", "Edit", "Glob"],
    permissionMode: "acceptEdits"
  }
})) {
  if (message.type === "assistant" && message.message?.content) {
    for (const block of message.message.content) {
      if ("text" in block) {
        console.log(block.text);     // Claude 的推理過程
      } else if ("name" in block) {
        console.log(`Tool: ${block.name}`); // 工具呼叫
      }
    }
  } else if (message.type === "result") {
    console.log(`Done: ${message.subtype}`);
  }
}

基本 Agent 範例(Python)

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 that would cause crashes. 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())

這段程式碼有三個關鍵部分:query 是建立 Agentic Loop 的主要進入點;prompt 告訴 Claude 要做什麼;options 設定 Agent 可以使用的工具與權限模式。Claude 會根據任務自動判斷該使用哪些工具。

Tool 定義與使用

Agent SDK 提供了豐富的內建工具,讓 Agent 可以直接與檔案系統、終端和網路互動。你只需在 allowedTools 中指定要啟用的工具,Claude 就會自動判斷何時使用它們。

內建工具一覽

工具名稱功能說明典型用途
Read讀取工作目錄中的任何檔案閱讀程式碼、設定檔
Write建立新檔案產生報告、建立設定
Edit精確編輯現有檔案修復 Bug、重構程式碼
Bash執行終端指令、腳本、Git 操作執行測試、安裝套件
Glob以 Pattern 搜尋檔案尋找特定類型的檔案
Grep以正則表達式搜尋檔案內容搜尋函式定義、錯誤訊息
WebSearch搜尋網路上的最新資訊查詢文件、API 規格
WebFetch擷取並解析網頁內容讀取線上文件

工具組合策略

根據 Agent 的用途,可以組合不同的工具來達成目標。以下是常見的工具組合建議:

工具組合Agent 能力適用場景
Read, Glob, Grep唯讀分析Code Review、程式碼搜尋
Read, Edit, Glob分析與修改程式碼Bug 修復、重構
Read, Edit, Bash, Glob, Grep完整自動化CI/CD Pipeline、全面測試

Agent 生命週期與 Hooks

Agent SDK 提供了 Hooks 機制,讓你在 Agent 生命週期的關鍵節點執行自訂邏輯。你可以用 Hooks 來驗證、記錄、阻擋或轉換 Agent 的行為。

可用的 Hook 類型

Hook 名稱觸發時機常見用途
PreToolUse工具呼叫前參數驗證、存取控制
PostToolUse工具呼叫後結果記錄、稽核日誌
StopAgent 完成任務時結果驗證、清理作業
SessionStartSession 開始時初始化設定、載入環境
SessionEndSession 結束時資源釋放、產出報告

Hook 實作範例:稽核日誌

以下範例展示如何使用 PostToolUse Hook 將所有檔案變更記錄到稽核日誌中:

import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFile } from "fs/promises";

const logFileChange: HookCallback = async (input) => {
  const filePath = (input as any).tool_input?.file_path ?? "unknown";
  await appendFile(
    "./audit.log",
    `${new Date().toISOString()}: modified ${filePath}\n`
  );
  return {};
};

for await (const message of query({
  prompt: "Refactor utils.py to improve readability",
  options: {
    permissionMode: "acceptEdits",
    hooks: {
      PostToolUse: [
        { matcher: "Edit|Write", hooks: [logFileChange] }
      ]
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

權限控制模式

Agent SDK 提供多種權限模式,讓你精確控制 Agent 的行為。選擇適合的模式,可以在自動化效率與安全性之間取得平衡:

模式行為適用場景
acceptEdits自動核准檔案編輯,其他操作需確認信任的開發環境
dontAsk拒絕不在 allowedTools 中的操作鎖定的 Headless Agent
auto(僅 TypeScript)模型分類器自動核准或拒絕自主 Agent + 安全護欄
bypassPermissions所有工具無需提示直接執行沙箱化的 CI 環境
default需提供 canUseTool callback 處理自訂審核流程

Subagents:多 Agent 協作

Agent SDK 支援 Subagent(子代理)機制,讓主 Agent 可以將特定任務委派給專門的子 Agent 處理。你可以為每個 Subagent 定義專屬的指令與工具集,實現分工合作。

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Use the code-reviewer agent to review this codebase",
  options: {
    allowedTools: ["Read", "Glob", "Grep", "Agent"],
    agents: {
      "code-reviewer": {
        description: "Expert code reviewer for quality and security.",
        prompt: "Analyze code quality and suggest improvements.",
        tools: ["Read", "Glob", "Grep"]
      }
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

使用 Subagent 時,需要在 allowedTools 中加入 Agent 工具。每個 Subagent 執行時產生的訊息會帶有 parent_tool_use_id 欄位,方便你追蹤哪些訊息屬於哪個 Subagent。

MCP 整合:連接外部系統

Agent SDK 透過 Model Context Protocol(MCP)支援連接外部系統,包括資料庫、瀏覽器、API 等。你可以透過 mcpServers 選項配置 MCP Server,讓 Agent 獲得額外的能力。

import { query } from "@anthropic-ai/claude-agent-sdk";

// 連接 Playwright MCP Server 賦予瀏覽器自動化能力
for await (const message of query({
  prompt: "Open example.com and describe what you see",
  options: {
    mcpServers: {
      playwright: {
        command: "npx",
        args: ["@playwright/mcp@latest"]
      }
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

MCP 生態系中有數百個現成的 Server 可供使用,包括 Slack、GitHub、Google Drive、Asana 等,無需自行撰寫整合程式碼即可讓你的 Agent 連接各種外部服務。

Session 管理:維持對話脈絡

Agent SDK 支援 Session(會話)機制,讓 Agent 能在多次交互中保持上下文。Claude 會記住已讀取的檔案、分析結果與對話歷史。你可以恢復先前的 Session,或分叉 Session 來探索不同的方案。

import { query } from "@anthropic-ai/claude-agent-sdk";

let sessionId: string | undefined;

// 第一次查詢:取得 Session ID
for await (const message of query({
  prompt: "Read the authentication module",
  options: { allowedTools: ["Read", "Glob"] }
})) {
  if (message.type === "system" && message.subtype === "init") {
    sessionId = message.session_id;
  }
}

// 恢復 Session,延續先前的上下文
for await (const message of query({
  prompt: "Now find all places that call it",
  options: { resume: sessionId }
})) {
  if ("result" in message) console.log(message.result);
}

完整範例:自動化 Bug 修復 Agent

以下是一個完整的 Agent 範例,結合了前面介紹的各項功能。這個 Agent 能自動掃描程式碼、找出潛在的 Bug、修復問題,並產出修復報告:

import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFile, writeFile } from "fs/promises";

// Hook:記錄所有檔案變更
const auditLog: HookCallback = async (input) => {
  const filePath = (input as any).tool_input?.file_path ?? "unknown";
  await appendFile(
    "./bug-fix-audit.log",
    `${new Date().toISOString()}: modified ${filePath}\n`
  );
  return {};
};

// 執行 Bug 修復 Agent
async function runBugFixer() {
  const results: string[] = [];

  for await (const message of query({
    prompt: `Scan all Python files for common bugs:
      1. Division by zero risks
      2. Null/None reference errors
      3. Unhandled exceptions
      Fix each issue and add defensive coding.`,
    options: {
      allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],
      permissionMode: "acceptEdits",
      systemPrompt: "You are a senior Python developer. Follow PEP 8.",
      hooks: {
        PostToolUse: [
          { matcher: "Edit|Write", hooks: [auditLog] }
        ]
      }
    }
  })) {
    if (message.type === "assistant") {
      for (const block of message.message?.content ?? []) {
        if ("text" in block) results.push(block.text);
      }
    }
  }

  // 產出修復報告
  await writeFile("./fix-report.md", results.join("\n"));
  console.log("Bug fix complete! See fix-report.md");
}

runBugFixer();

這個範例展示了 Agent SDK 的幾個核心特性:透過 systemPrompt 設定 Agent 角色、使用 hooks 記錄稽核日誌、結合多種工具實現完整的自動化流程,以及將結果輸出到檔案中。

Agent SDK 與 Claude Code 的關係

Agent SDK 與 Claude Code 共享相同的底層引擎。你在 Claude Code CLI 中能做到的事,透過 Agent SDK 都能以程式化方式實現。許多團隊會同時使用兩者:在日常開發中使用 CLI 進行互動式操作,在 CI/CD Pipeline 和自動化流程中使用 SDK。

Agent SDK 也支援 Claude Code 基於檔案系統的設定機制。只需在選項中設定 settingSources: ['project'],就能啟用以下功能:

  • Skills:在 .claude/skills/*/SKILL.md 定義專門能力
  • Slash Commands:在 .claude/commands/*.md 建立自訂指令
  • Memory:透過 CLAUDE.md 設定專案上下文與指令
  • Plugins:以程式化方式透過 plugins 選項擴展功能

部署與最佳實踐

在將 Agent 部署到正式環境前,以下幾點建議能幫助你建構更穩定、更安全的 Agent:

  • 最小權限原則:只授權 Agent 真正需要的工具,避免使用 bypassPermissions(除非在完全隔離的沙箱環境中)
  • 使用 Hooks 記錄操作:透過 PostToolUse Hook 建立完整的稽核軌跡,方便追蹤問題
  • 設定 System Prompt:為 Agent 提供明確的角色定義與行為準則,提升輸出品質的一致性
  • 善用 Session 管理:在需要多步驟的任務中使用 Session 保持上下文,避免重複讀取相同的檔案
  • 錯誤處理:Agent 可能會遇到工具執行失敗的情況,確保你的程式碼能妥善處理這些情境
  • 容器化部署:Agent SDK 支援 Docker 部署,建議在容器中執行以獲得更好的隔離性

延伸閱讀

想要深入了解 Claude Agent SDK 的更多功能,可以參考以下官方資源:

總結

Claude Agent SDK 為開發者提供了一個強大的框架,讓你能以程式化方式建構具有自主能力的 AI Agent。無論是自動化程式碼審查、Bug 修復、測試執行,還是與外部系統整合,Agent SDK 都能勝任。它的設計哲學是「讓 Claude 自主處理工具呼叫」,你只需定義目標與限制,Claude 會自動規劃與執行所需的步驟。

從本系列的第一篇到現在的第二十篇,我們已經走過了 Claude Code 的完整旅程——從基礎安裝、CLI 指令、Context 管理到 Hooks、Plugins,一直到今天的 Agent SDK。掌握了這些知識,你已經具備了在開發流程中充分運用 AI 能力的基礎。接下來,就是動手實踐的時候了!