Claude Code SDK 能夠將 Claude Code 作為子程序運行,提供了一種構建 AI 驅動的編程助手和工具的方式,利用 Claude 的能力。

SDK 可用於命令列、TypeScript 和 Python 使用。

身份驗證

要使用 Claude Code SDK,我們建議創建一個專用的 API 金鑰:

  1. Anthropic Console 中創建一個 Anthropic API 金鑰
  2. 然後,設置 ANTHROPIC_API_KEY 環境變數。我們建議安全地存儲此金鑰(例如,使用 Github secret

基本 SDK 使用

Claude Code SDK 允許您在應用程式中以非互動模式使用 Claude Code。

命令列

以下是命令列 SDK 的一些基本範例:

# 運行單個提示並退出(列印模式)
$ claude -p "Write a function to calculate Fibonacci numbers"

# 使用管道提供 stdin
$ echo "Explain this code" | claude -p

# 以 JSON 格式輸出並包含元數據
$ claude -p "Generate a hello world function" --output-format json

# 在到達時串流 JSON 輸出
$ claude -p "Build a React component" --output-format stream-json

TypeScript

TypeScript SDK 包含在 NPM 上的主要 @anthropic-ai/claude-code 套件中:

import { query, type SDKMessage } from "@anthropic-ai/claude-code";

const messages: SDKMessage[] = [];

for await (const message of query({
  prompt: "Write a haiku about foo.py",
  abortController: new AbortController(),
  options: {
    maxTurns: 3,
  },
})) {
  messages.push(message);
}

console.log(messages);

TypeScript SDK 接受命令列 SDK 支援的所有參數,以及:

參數描述預設值
abortController中止控制器new AbortController()
cwd當前工作目錄process.cwd()
executable要使用的 JavaScript 運行時使用 Node.js 運行時為 node,使用 Bun 運行時為 bun
executableArgs傳遞給可執行檔的參數[]
pathToClaudeCodeExecutableClaude Code 可執行檔的路徑@anthropic-ai/claude-code 一起提供的可執行檔

Python

Python SDK 在 PyPI 上以 claude-code-sdk 的形式提供:

pip install claude-code-sdk

先決條件:

  • Python 3.10+
  • Node.js
  • Claude Code CLI:npm install -g @anthropic-ai/claude-code

基本使用:

import anyio
from claude_code_sdk import query, ClaudeCodeOptions, Message

async def main():
    messages: list[Message] = []
    
    async for message in query(
        prompt="Write a haiku about foo.py",
        options=ClaudeCodeOptions(max_turns=3)
    ):
        messages.append(message)
    
    print(messages)

anyio.run(main)

Python SDK 通過 ClaudeCodeOptions 類接受命令列 SDK 支援的所有參數:

from claude_code_sdk import query, ClaudeCodeOptions
from pathlib import Path

options = ClaudeCodeOptions(
    max_turns=3,
    system_prompt="You are a helpful assistant",
    cwd=Path("/path/to/project"),  # 可以是字串或 Path
    allowed_tools=["Read", "Write", "Bash"],
    permission_mode="acceptEdits"
)

async for message in query(prompt="Hello", options=options):
    print(message)

進階使用

以下文件使用命令列 SDK 作為範例,但也可以與 TypeScript 和 Python SDK 一起使用。

多輪對話

對於多輪對話,您可以恢復對話或從最近的會話繼續:

# 繼續最近的對話
$ claude --continue

# 繼續並提供新的提示
$ claude --continue "Now refactor this for better performance"

# 通過會話 ID 恢復特定對話
$ claude --resume 550e8400-e29b-41d4-a716-446655440000

# 在列印模式下恢復(非互動)
$ claude -p --resume 550e8400-e29b-41d4-a716-446655440000 "Update the tests"

# 在列印模式下繼續(非互動)
$ claude -p --continue "Add error handling"

自定義系統提示

您可以提供自定義系統提示來指導 Claude 的行為:

# 覆蓋系統提示(僅適用於 --print)
$ claude -p "Build a REST API" --system-prompt "You are a senior backend engineer. Focus on security, performance, and maintainability."

# 具有特定要求的系統提示
$ claude -p "Create a database schema" --system-prompt "You are a database architect. Use PostgreSQL best practices and include proper indexing."

您也可以將指令附加到預設系統提示:

# 附加系統提示(僅適用於 --print)
$ claude -p "Build a REST API" --append-system-prompt "After writing code, be sure to code review yourself."

MCP 配置

模型上下文協議(MCP)允許您使用來自外部伺服器的額外工具和資源來擴展 Claude Code。使用 --mcp-config 標誌,您可以載入提供專門功能的 MCP 伺服器,如資料庫存取、API 整合或自定義工具。

使用您的 MCP 伺服器創建 JSON 配置檔案:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/path/to/allowed/files"
      ]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "your-github-token"
      }
    }
  }
}

然後與 Claude Code 一起使用:

# 從配置載入 MCP 伺服器
$ claude -p "List all files in the project" --mcp-config mcp-servers.json

# 重要:必須使用 --allowedTools 明確允許 MCP 工具
# MCP 工具遵循格式:mcp__$serverName__$toolName
$ claude -p "Search for TODO comments" \
  --mcp-config mcp-servers.json \
  --allowedTools "mcp__filesystem__read_file,mcp__filesystem__list_directory"

# 在非互動模式下使用 MCP 工具處理權限提示
$ claude -p "Deploy the application" \
  --mcp-config mcp-servers.json \
  --allowedTools "mcp__permissions__approve" \
  --permission-prompt-tool mcp__permissions__approve

使用 MCP 工具時,您必須使用 --allowedTools 標誌明確允許它們。MCP 工具名稱遵循模式 mcp__<serverName>__<toolName>,其中:

  • serverName 是您的 MCP 配置檔案中的金鑰
  • toolName 是該伺服器提供的特定工具

這種安全措施確保 MCP 工具僅在明確許可時使用。

如果您只指定伺服器名稱(即 mcp__<serverName>),該伺服器的所有工具都將被允許。

不支援萬用字元模式(例如 mcp__go*)。

自定義權限提示工具

可選地,使用 --permission-prompt-tool 傳入一個 MCP 工具,我們將使用它來檢查使用者是否授予模型調用給定工具的權限。當模型調用工具時,會發生以下情況:

  1. 我們首先檢查權限設定:所有 settings.json 檔案,以及傳入 SDK 的 --allowedTools--disallowedTools;如果其中一個允許或拒絕工具調用,我們繼續進行工具調用
  2. 否則,我們調用您在 --permission-prompt-tool 中提供的 MCP 工具

--permission-prompt-tool MCP 工具會接收工具名稱和輸入,並且必須返回一個帶有結果的 JSON 字串化負載。負載必須是以下之一:

// 工具調用被允許
{
  "behavior": "allow",
  "updatedInput": {...}, // 更新的輸入,或只是返回原始輸入
}

// 工具調用被拒絕
{
  "behavior": "deny",
  "message": "..." // 解釋為什麼權限被拒絕的人類可讀字串
}

例如,TypeScript MCP 權限提示工具實現可能如下所示:

const server = new McpServer({
  name: "Test permission prompt MCP Server",
  version: "0.0.1",
});

server.tool(
  "approval_prompt",
  'Simulate a permission check - approve if the input contains "allow", otherwise deny',
  {
    tool_name: z.string().describe("The tool requesting permission"),
    input: z.object({}).passthrough().describe("The input for the tool"),
  },
  async ({ tool_name, input }) => {
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(
            JSON.stringify(input).includes("allow")
              ? {
                  behavior: "allow",
                  updatedInput: input,
                }
              : {
                  behavior: "deny",
                  message: "Permission denied by test approval_prompt tool",
                }
          ),
        },
      ],
    };
  }
);

要使用此工具,添加您的 MCP 伺服器(例如使用 --mcp-config),然後像這樣調用 SDK:

claude -p "..." \
  --permission-prompt-tool mcp__test-server__approval_prompt \
  --mcp-config my-config.json

使用注意事項:

  • 使用 updatedInput 告訴模型權限提示改變了其輸入;否則,將 updatedInput 設置為原始輸入,如上面的範例所示。例如,如果工具向使用者顯示檔案編輯差異並讓他們手動編輯差異,權限提示工具應該返回該更新的編輯。
  • 負載必須是 JSON 字串化的

可用的 CLI 選項

SDK 利用 Claude Code 中可用的所有 CLI 選項。以下是 SDK 使用的關鍵選項:

標誌描述範例
--print, -p在非互動模式下運行claude -p "query"
--output-format指定輸出格式(textjsonstream-jsonclaude -p --output-format json
--resume, -r通過會話 ID 恢復對話claude --resume abc123
--continue, -c繼續最近的對話claude --continue
--verbose啟用詳細日誌記錄claude --verbose
--max-turns在非互動模式下限制代理輪數claude --max-turns 3
--system-prompt覆蓋系統提示(僅適用於 --printclaude --system-prompt "Custom instruction"
--append-system-prompt附加到系統提示(僅適用於 --printclaude --append-system-prompt "Custom instruction"
--allowedTools以空格分隔的允許工具列表,或

以逗號分隔的允許工具字串
claude --allowedTools mcp__slack mcp__filesystem

claude --allowedTools "Bash(npm install),mcp__filesystem"
--disallowedTools以空格分隔的拒絕工具列表,或

以逗號分隔的拒絕工具字串
claude --disallowedTools mcp__splunk mcp__github

claude --disallowedTools "Bash(git commit),mcp__github"
--mcp-config從 JSON 檔案載入 MCP 伺服器claude --mcp-config servers.json
--permission-prompt-tool用於處理權限提示的 MCP 工具(僅適用於 --printclaude --permission-prompt-tool mcp__auth__prompt

有關 CLI 選項和功能的完整列表,請參閱 CLI 參考 文件。

輸出格式

SDK 支援多種輸出格式:

文字輸出(預設)

僅返回回應文字:

$ claude -p "Explain file src/components/Header.tsx"
# 輸出:This is a React component showing...

JSON 輸出

返回包含元數據的結構化數據:

$ claude -p "How does the data layer work?" --output-format json

回應格式:

{
  "type": "result",
  "subtype": "success",
  "total_cost_usd": 0.003,
  "is_error": false,
  "duration_ms": 1234,
  "duration_api_ms": 800,
  "num_turns": 6,
  "result": "The response text here...",
  "session_id": "abc123"
}

串流 JSON 輸出

在接收到每個訊息時串流:

$ claude -p "Build an application" --output-format stream-json

每個對話都以初始的 init 系統訊息開始,然後是使用者和助手訊息列表,最後是帶有統計資料的最終 result 系統訊息。每個訊息都作為單獨的 JSON 物件發出。

訊息架構

從 JSON API 返回的訊息根據以下架構嚴格類型化:

type SDKMessage =
  // 助手訊息
  | {
      type: "assistant";
      message: Message; // 來自 Anthropic SDK
      session_id: string;
    }

  // 使用者訊息
  | {
      type: "user";
      message: MessageParam; // 來自 Anthropic SDK
      session_id: string;
    }

  // 作為最後一個訊息發出
  | {
      type: "result";
      subtype: "success";
      duration_ms: float;
      duration_api_ms: float;
      is_error: boolean;
      num_turns: int;
      result: string;
      session_id: string;
      total_cost_usd: float;
    }

  // 當我們達到最大輪數時作為最後一個訊息發出
  | {
      type: "result";
      subtype: "error_max_turns" | "error_during_execution";
      duration_ms: float;
      duration_api_ms: float;
      is_error: boolean;
      num_turns: int;
      session_id: string;
      total_cost_usd: float;
    }

  // 在對話開始時作為第一個訊息發出
  | {
      type: "system";
      subtype: "init";
      apiKeySource: string;
      cwd: string;
      session_id: string;
      tools: string[];
      mcp_servers: {
        name: string;
        status: string;
      }[];
      model: string;
      permissionMode: "default" | "acceptEdits" | "bypassPermissions" | "plan";
    };

我們很快將以 JSONSchema 相容格式發布這些類型。我們對主要 Claude Code 套件使用語義版本控制來傳達此格式的重大變更。

MessageMessageParam 類型在 Anthropic SDK 中可用。例如,請參閱 Anthropic TypeScriptPython SDK。

輸入格式

SDK 支援多種輸入格式:

文字輸入(預設)

輸入文字可以作為參數提供:

$ claude -p "Explain this code"

或者輸入文字可以通過 stdin 管道傳輸:

$ echo "Explain this code" | claude -p

串流 JSON 輸入

通過 stdin 提供的訊息串流,其中每個訊息代表一個使用者輪次。這允許對話的多個輪次而無需重新啟動 claude 二進位檔案,並允許在模型處理請求時向模型提供指導。

每個訊息都是一個 JSON「使用者訊息」物件,遵循與輸出訊息架構相同的格式。訊息使用 jsonl 格式格式化,其中每行輸入都是一個完整的 JSON 物件。串流 JSON 輸入需要 -p--output-format stream-json

目前這僅限於純文字使用者訊息。

$ echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Explain this code"}]}}' | claude -p --output-format=stream-json --input-format=stream-json --verbose

範例

簡單腳本整合

#!/bin/bash

# 運行 Claude 並檢查退出代碼的簡單函數
run_claude() {
    local prompt="$1"
    local output_format="${2:-text}"

    if claude -p "$prompt" --output-format "$output_format"; then
        echo "Success!"
    else
        echo "Error: Claude failed with exit code $?" >&2
        return 1
    fi
}

# 使用範例
run_claude "Write a Python function to read CSV files"
run_claude "Optimize this database query" "json"

使用 Claude 處理檔案

# 通過 Claude 處理檔案
$ cat mycode.py | claude -p "Review this code for bugs"

# 處理多個檔案
$ for file in *.js; do
    echo "Processing $file..."
    claude -p "Add JSDoc comments to this file:" < "$file" > "${file}.documented"
done

# 在管道中使用 Claude
$ grep -l "TODO" *.py | while read file; do
    claude -p "Fix all TODO items in this file" < "$file"
done

會話管理

# 開始會話並捕獲會話 ID
$ claude -p "Initialize a new project" --output-format json | jq -r '.session_id' > session.txt

# 使用相同會話繼續
$ claude -p --resume "$(cat session.txt)" "Add unit tests"

最佳實踐

  1. 使用 JSON 輸出格式 進行程式化解析回應:

    # 使用 jq 解析 JSON 回應
    result=$(claude -p "Generate code" --output-format json)
    code=$(echo "$result" | jq -r '.result')
    cost=$(echo "$result" | jq -r '.cost_usd')
    
  2. 優雅地處理錯誤 - 檢查退出代碼和 stderr:

    if ! claude -p "$prompt" 2>error.log; then
        echo "Error occurred:" >&2
        cat error.log >&2
        exit 1
    fi
    
  3. 使用會話管理 在多輪對話中維護上下文

  4. 考慮超時 對於長時間運行的操作:

    timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes"
    
  5. 尊重速率限制 在進行多個請求時,通過在調用之間添加延遲

實際應用

Claude Code SDK 能夠與您的開發工作流程進行強大的整合。一個值得注意的範例是 Claude Code GitHub Actions,它使用 SDK 直接在您的 GitHub 工作流程中提供自動化程式碼審查、PR 創建和問題分類功能。

相關資源