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

在這個範例中,我們正在建立一個管理文件操作的 MCP 伺服器。該伺服器將有兩個主要工具:一個用於讀取文件內容,另一個用於更新文件內容。所有文件都以簡單字典的形式存在於記憶體中,鍵是文件 ID,值是內容字串。
MCP Python SDK 的優勢
MCP 專案提供了官方 SDK,可用於跨多種程式語言建構伺服器和客戶端。使用 Python SDK 具有以下幾項優勢:
- 以最少的樣板程式碼建立 MCP 伺服器
- 自動從 Python 函式簽章生成 JSON 結構描述
- 透過裝飾器簡化工具定義
- 處理型別驗證和錯誤處理

以下示範使用此 SDK 定義工具有多麼容易。@mcp.tool 裝飾器結合型別提示和欄位描述,會自動建立 Claude 能夠理解和使用的正確工具結構描述。
設定伺服器
本課程使用 MCP Python SDK 的第 1 版。下方的 import 在第 2 版中會失敗,因為該版本重新命名了 FastMCP。如果您自行設定專案,請將 SDK 保持在第 2 版以下:
uv add "mcp[cli]<2"若使用 pip,同樣的版本鎖定方式為 pip install "mcp[cli]<2"。
基本的伺服器設定只需要幾行程式碼:
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 來讀取文件內容:
@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 的錯誤處理
實作編輯工具
第二個工具會對文件內容執行簡單的尋找並取代操作:
@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 結構描述
相較於手動撰寫 JSON 結構描述,MCP Python SDK 大幅降低了建立工具的複雜度。過去需要數十行結構描述定義才能完成的工作,現在只需幾行帶有裝飾器的 Python 函式即可完成。
@mcp.tool 裝飾器及其基於簽章的結構描述生成功能,來自於 MCP Python SDK。Claude Agent SDK 提供了一個獨立的 @tool 裝飾器(在新分頁中開啟) 用於定義自訂工具,它需要明確的 input_schema 參數,而不是在函式簽章上使用 pydantic 的 Field 註解。在 Python 中,該結構描述是一個將參數名稱對應到型別的字典,例如 {"latitude": float},Agent SDK 會為您將其轉換為 JSON Schema;或者當您需要列舉值、範圍、選用欄位或巢狀物件時,則可使用完整的 JSON Schema 字典。當您在其他地方閱讀工具程式碼時,請檢查它匯入的是哪一個 SDK,因為這兩個裝飾器很容易混淆。