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

在這個範例中,我們正在建立一個文件管理伺服器,具有兩個核心工具:一個用於讀取文件,另一個用於更新文件。所有文件都以簡單的字典形式存在於記憶體中,其中鍵是文件 ID,值是內容。
取得專案
本課程的各課程是以一個小型入門專案為基礎建置的,這是一個具有 MCP 用戶端和 MCP 伺服器的命令列聊天機器人。請從本課程結尾的下載區段下載 cli_project.zip,並將其解壓縮到您偏好的開發目錄中。在專案資料夾中開啟您的程式碼編輯器。
該專案包含一個 README 檔案,其中有設定說明。請將您的 Anthropic API 金鑰新增到 .env 檔案中。然後使用 uv(建議)或 pip 安裝相依套件。該專案使用 MCP Python SDK 的第 1 版,其設定會為您安裝該版本。
設定 MCP 伺服器
MCP Python SDK 讓伺服器建立變得簡單直接。請開啟 mcp_server.py。它已經用一行程式碼初始化了一個伺服器。下面的工具還需要 Field 匯入:
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"
}使用裝飾器定義工具
SDK 使用裝飾器來定義工具。您不需要手動撰寫 JSON 結構描述,而是可以使用 Python 型別提示和欄位描述。SDK 會自動產生 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]裝飾器指定了工具名稱和描述,而函式參數則定義了必要的引數。來自 Pydantic 的 Field 類別提供了引數描述,有助於 Claude 理解每個參數的預期內容。
建置文件編輯工具
第二個工具對文件執行簡單的尋找與取代操作:
@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、要尋找的文字,以及取代文字。該實作包含對缺少文件的錯誤處理,並執行直接的字串取代。
SDK 方法的主要優點
- 不需要手動撰寫 JSON 結構描述
- 型別提示提供自動驗證
- 清楚的參數描述有助於 Claude 理解工具用法
- 錯誤處理能自然地與 Python 例外整合
- 工具註冊透過裝飾器自動完成
MCP Python SDK 將工具建立從複雜的結構描述撰寫工作,轉變為簡單的 Python 函式定義。這種方法讓建置和維護 MCP 伺服器變得更加容易,同時確保 Claude 能收到格式正確的工具規格。