載入中

使用 MCP 定義工具

第 51 課9 分鐘

當您使用官方的 MCP Python SDK 時,建置 MCP 伺服器會變得簡單許多。您不需要手動撰寫複雜的 JSON schema 來定義工具,而是可以使用裝飾器來定義它們,並讓 SDK 處理繁重的工作。

我們的 MCP 伺服器的讀取與更新工具連接到四個檔案:document.pdf、spreadsheet.xlsx、report.txt 和 spec.md。

在這個範例中,我們正在建立一個管理文件操作的 MCP 伺服器。該伺服器將有兩個主要工具:一個用於讀取文件內容,另一個用於更新文件內容。所有文件都以簡單的字典形式存在於記憶體中,其中鍵是文件 ID,值是內容字串。

MCP Python SDK 的優勢

MCP 專案為跨多種程式語言建置伺服器和客戶端提供了官方 SDK。使用 Python SDK 具有以下幾項優勢:

  • 以最少的樣板程式碼建立 MCP 伺服器
  • 自動從 Python 函式簽章產生 JSON schema
  • 透過裝飾器簡化工具定義
  • 處理型別驗證和錯誤處理

我們的 MCP 伺服器的讀取與更新工具連接到四個檔案:document.pdf、spreadsheet.xlsx、report.txt 和 spec.md。

以下說明使用 SDK 定義工具是多麼容易。@mcp.tool 裝飾器結合型別提示和欄位描述,會自動建立 Claude 能夠理解和使用的正確工具 schema。

設定伺服器

本課程使用 MCP Python SDK 的第 1 版。下方的匯入在第 2 版上會失敗,因為該版本重新命名了 FastMCP。如果您自行設定專案,請將 SDK 版本保持在 2 以下:

bash
uv add "mcp[cli]<2"

若使用 pip,相同的版本限制為 pip install "mcp[cli]<2"。

基本的伺服器設定只需要幾行程式碼:

python
from mcp.server.fastmcp import FastMCP
from pydantic import Field

mcp = FastMCP("DocumentMCP", log_level="ERROR")

docs = {
    "deposition.md": "This deposition covers the testimony of Angela Smith, P.E.",
    "report.pdf": "The report details the state of a 20m condenser tower.",
    "financials.docx": "These financials outline the project's budget and expenditures",
    "outlook.pdf": "This document presents the projected future performance of the system",
    "plan.md": "The plan outlines the steps for the project's implementation.",
    "spec.txt": "These specifications define the technical requirements for the equipment"
}

實作讀取工具

第一個工具讓 Claude 能夠透過提供文件 ID 來讀取文件內容:

python
@mcp.tool(
    name="read_doc_contents",
    description="Read the contents of a document and return it as a string."
)
def read_document(
    doc_id: str = Field(description="Id of the document to read")
):
    if doc_id not in docs:
        raise ValueError(f"Doc with id {doc_id} not found")
    
    return docs[doc_id]

工具定義包括:

  • 一個清楚描述動作的名稱
  • 一個說明工具功能的描述
  • 帶有欄位描述的型別化參數
  • 針對無效文件 ID 的錯誤處理

實作編輯工具

第二個工具對文件內容執行簡單的尋找與取代操作:

python
@mcp.tool(
    name="edit_document",
    description="Edit a document by replacing a string in the documents content with a new string."
)
def edit_document(
    doc_id: str = Field(description="Id of the document that will be edited"),
    old_str: str = Field(description="The text to replace. Must match exactly, including whitespace."),
    new_str: str = Field(description="The new text to insert in place of the old text.")
):
    if doc_id not in docs:
        raise ValueError(f"Doc with id {doc_id} not found")
    
    docs[doc_id] = docs[doc_id].replace(old_str, new_str)

這個工具接受三個參數:文件 ID、要尋找的文字,以及取代文字。為求簡單,實作使用了 Python 內建的字串 replace() 方法。

關鍵實作細節

使用 MCP SDK 定義工具時,請記住以下重要事項:

  • 從 pydantic 匯入 Field 以新增參數描述
  • 使用型別提示來指定參數型別
  • 為邊緣情況加入錯誤處理
  • 撰寫清楚、具描述性的工具名稱和描述
  • MCP Python SDK 會自動將您的函式簽章轉換為正確的 JSON schema

與手動撰寫 JSON schema 相比,MCP Python SDK 大幅降低了建立工具的複雜度。過去需要數十行 schema 定義的工作,現在只需幾行經過裝飾的 Python 函式即可完成。

@mcp.tool 裝飾器及其基於簽章的 schema 產生功能來自 MCP Python SDK。Claude Agent SDK 提供了一個獨立的 @tool 裝飾器用於定義自訂工具,它需要明確的 input_schema 引數,而不是在函式簽章上使用 pydantic 的 Field 註解。在 Python 中,該 schema 是一個將參數名稱對應到型別的字典,例如 {"latitude": float},Agent SDK 會為您將其轉換為 JSON Schema;或者當您需要列舉、範圍、選用欄位或巢狀物件時,也可以使用完整的 JSON Schema 字典。當您在其他地方閱讀工具程式碼時,請檢查它匯入的是哪個 SDK,因為這兩個裝飾器很容易混淆。