跳至主要內容
MCP Claude SDK Python Integration Tool Use

Claude SDK MCP Helpers:Python 原生 MCP 整合

Anthropic Python SDK(現為 Claude SDK)新增原生 MCP helpers -- mcp_tool()、async_mcp_tool() 和 mcp_message(),實現無縫 MCP 伺服器整合。一行程式碼即可將 MCP 工具轉換為 Anthropic API 格式。

2026年3月5日 8 分鐘閱讀 作者:Claude World

建構透過 MCP 將 Claude 連接到外部工具的應用程式,過去一直需要在 MCP 協定型別與 Anthropic API 格式之間手動進行型別轉換。隨著 v0.84.0 的發布,Anthropic Python SDK — 現已更名為 Claude SDK — 內建了原生 MCP helpers,徹底消除了這些樣板程式碼。一個函式呼叫即可將 MCP 工具轉換為 Claude API 能理解的格式,另一個函式則可轉換 MCP prompt 訊息。本文將介紹此版本的新功能、使用方式,以及 SDK 近期的其他變更。


SDK 品牌更新:Anthropic SDK 正式成為 Claude SDK

從 v0.84.0 開始,原名為 anthropic-sdk-python 的套件現已正式更名為 Claude SDK。PyPI 套件名稱仍為 anthropic,匯入路徑也依然是 from anthropic import ...,因此現有程式碼完全不需要修改。此次品牌更新反映了 Anthropic 將開發者工具整合至 Claude 品牌之下的策略,使 Python SDK 與 Claude Agent SDK、Claude Code 及整個 Claude 生態系統保持一致。

實際影響:如果你在 Anthropic 文件中看到「Claude SDK」的引用,它指的就是你已經在使用的 pip install anthropic 套件。


MCP Helpers 解決的問題

在這些 helpers 出現之前,將 MCP 伺服器與 Anthropic API 整合意味著你需要自行撰寫轉換程式碼。MCP 伺服器以 mcp.types.Tool 物件公開工具,使用其專屬的 schema 格式。而 Anthropic API 則期望工具以 BetaFunctionTool 物件的形式提供。MCP 的 prompts 使用 PromptMessage,但 Anthropic 期望的是 MessageParam 字典。資源以 ReadResourceResult 回傳,但你需要的是 Anthropic content blocks。

每個 MCP 整合都必須撰寫(並維護)這些轉換的膠水程式碼。anthropic.lib.tools.mcp 中的新 helpers 處理了所有這些工作。


新的 MCP Helpers

此模組匯出五個公開函式:

Helper用途
mcp_tool(tool, session)將 MCP Tool 轉換為同步 Anthropic tool
async_mcp_tool(tool, session)將 MCP Tool 轉換為非同步 Anthropic tool
mcp_message(message)將 MCP PromptMessage 轉換為 Anthropic 訊息格式
mcp_resource_to_content(result)將 MCP 資源轉換為 Anthropic content block
mcp_resource_to_file(result)將 MCP 資源轉換為檔案 tuple 以供上傳

所有函式也接受可選的 cache_control 參數,用於 Anthropic 的 prompt 快取功能。

async_mcp_tool — 核心 Helper

這是你最常使用的函式。它接受一個 MCP Tool 定義和一個 ClientSession,並回傳一個 BetaAsyncFunctionTool,可直接由 Anthropic 的 tool_runner() 執行。當 Claude 決定呼叫該工具時,helper 會自動將呼叫轉發至 MCP 伺服器並將結果轉換回來。

from anthropic.lib.tools.mcp import async_mcp_tool

# Convert all MCP tools in one line
tools = [async_mcp_tool(t, mcp_client) for t in tools_result.tools]

這一行 list comprehension 取代了過去需要 30-50 行的手動 schema 對應、工具分發和結果轉換程式碼。

mcp_tool — 同步版本

同步版本的運作方式完全相同,但內部使用 anyio.from_thread 從同步程式碼呼叫非同步的 MCP client。當你的應用程式不是非同步架構時使用:

from anthropic.lib.tools.mcp import mcp_tool

tools = [mcp_tool(t, mcp_client) for t in tools_result.tools]
runner = client.beta.messages.tool_runner(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "List files in /tmp"}],
)

mcp_message — Prompt 轉換

MCP 伺服器可以公開可重複使用的 prompts。mcp_message() helper 將 MCP 的 PromptMessage 格式轉換為 Anthropic 的訊息格式:

from anthropic.lib.tools.mcp import mcp_message

prompt = await mcp_client.get_prompt(name="code-review")
response = await client.beta.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    messages=[mcp_message(m) for m in prompt.messages],
)

mcp_resource_to_content — 資源整合

當 MCP 伺服器提供資源(檔案、文件、資料)時,此 helper 會將其轉換為 Anthropic content blocks,以便你在訊息中使用。它支援文字、圖片(JPEG、PNG、GIF、WebP)和 PDF:

from anthropic.lib.tools.mcp import mcp_resource_to_content

resource = await mcp_client.read_resource(uri="file:///path/to/doc.txt")
response = await client.beta.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            mcp_resource_to_content(resource),
            {"type": "text", "text": "Summarize this document"},
        ],
    }],
)

完整運作範例

以下是一個完整的端到端範例,連接到 MCP filesystem 伺服器、轉換其工具,並執行一個 Claude 可以列出和讀取檔案的對話:

import asyncio

from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client

from anthropic import AsyncAnthropic
from anthropic.lib.tools.mcp import async_mcp_tool

client = AsyncAnthropic()


async def main() -> None:
    server_params = StdioServerParameters(
        command="npx",
        args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
    )

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as mcp_client:
            await mcp_client.initialize()

            # Convert all MCP tools to Anthropic format
            tools_result = await mcp_client.list_tools()
            tools = [async_mcp_tool(t, mcp_client) for t in tools_result.tools]

            print(f"Connected with {len(tools)} tools:")
            for tool in tools:
                print(f"  - {tool.name}")

            # Run the conversation -- tool_runner handles the loop
            runner = client.beta.messages.tool_runner(
                model="claude-sonnet-4-5-20250929",
                max_tokens=1024,
                tools=tools,
                messages=[{
                    "role": "user",
                    "content": "List the files in /tmp and tell me what you find",
                }],
            )
            async for message in runner:
                print(message)


asyncio.run(main())

tool_runner() 負責處理完整的工具使用迴圈:Claude 發出工具呼叫請求,runner 透過 MCP helper 執行它,將結果回傳,並持續運作直到 Claude 產生最終回應。不需要手動管理迴圈。


進階選項

mcp_tool()async_mcp_tool() helpers 除了基本參數外,還接受幾個可選參數:

tool = async_mcp_tool(
    t,
    mcp_client,
    cache_control={"type": "ephemeral"},  # Enable prompt caching
    defer_loading=True,       # Exclude from initial system prompt
    strict=True,              # Enforce schema validation
    input_examples=[          # Provide example inputs
        {"path": "/tmp", "recursive": False}
    ],
)
  • cache_control:將 Anthropic 的快取控制指令附加到工具定義上,有助於減少重複呼叫的延遲。
  • defer_loading:設為 True 時,工具定義不會包含在初始 system prompt 中。當你有大量工具但想減少 prompt 大小時很有用。
  • strict:啟用工具名稱和輸入的嚴格 schema 驗證。
  • input_examples:提供範例輸入,幫助 Claude 正確理解如何使用該工具。

錯誤處理

當 MCP 值無法轉換為 Claude API 支援的格式時,helpers 會拋出 UnsupportedMCPValueError。這會在遇到不支援的內容類型(如音訊)或不支援的 MIME 類型時發生:

from anthropic.lib.tools.mcp import async_mcp_tool, UnsupportedMCPValueError

try:
    tools = [async_mcp_tool(t, mcp_client) for t in tools_result.tools]
except UnsupportedMCPValueError as e:
    print(f"Tool conversion failed: {e}")

當 MCP 工具呼叫回傳錯誤(即 CallToolResult.isErrorTrue)時,helper 會拋出 ToolErrortool_runner() 會自動處理,將錯誤回報給 Claude。


安裝

安裝包含 MCP 支援的 SDK:

pip install anthropic[mcp]

這會將 mcp 套件作為額外依賴項一併安裝。MCP 支援需要 Python 3.10 或更高版本 — MCP SDK 本身不支援較舊的 Python 版本。

如果你已經安裝了 anthropic,升級以取得最新的 helpers:

pip install --upgrade anthropic[mcp]

其他近期 SDK 更新

MCP helpers 是自 v0.77 以來一系列 SDK 改進的一部分。以下是其他已發布的更新:

v0.83 — 自動快取

頂層快取控制支援。無需手動為個別訊息標記快取中斷點,你現在可以在請求層級設定快取行為,SDK 會自動處理放置位置。

v0.80 — Sonnet 4.6

新增對 Claude Sonnet 4.6 的支援,包含新的模型識別碼和 Sonnet 特有的參數。

v0.78-0.79 — Opus 4.6 和 Fast Mode

支援具有 1M token context window 的 Claude Opus 4.6,包括 effort tuning(fast/normal/thorough)和新的 Agent Teams 功能。SDK 新增了這些功能所需的參數和型別定義。

v0.77 — Structured Outputs

原生支援 structured outputs,允許你定義 Pydantic 模型或 JSON schema,讓 Claude 的回應必須符合其規範。這消除了從 Claude 輸出中進行事後解析以擷取結構化資料的需求。


為什麼這很重要

MCP 正在成為連接 AI 模型與外部工具和資料來源的標準協定。在這些 helpers 出現之前,每個想要搭配 Claude 使用 MCP 工具的 Python 應用程式都必須實作自己的轉換層 — 將 MCP 工具 schema 對應到 Anthropic 格式、將工具呼叫分發到 MCP 伺服器,以及將結果轉換回來。這既重複又容易出錯,且當 MCP 規格或 Anthropic API 演進時會產生維護負擔。

有了原生 helpers,整合簡化為每個工具僅需一個函式呼叫。SDK 擁有轉換邏輯的所有權,使其與 API 變更保持同步,並處理應用程式開發者否則需要自行管理的邊界情況(不支援的內容類型、錯誤傳播、資源 MIME 類型偵測)。

對於建構 MCP 驅動的 Claude 應用程式的團隊而言 — 無論是具有檔案系統存取的程式碼助手、擁有資料庫工具的資料管線,還是整合 CRM 的客服代理 — 這意味著更少的膠水程式碼和更快的迭代速度。


相關資源