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

在此範例中,我們正在建立一個文件管理伺服器,其中包含兩個核心工具:一個用於讀取文件,另一個用於更新文件。所有文件都以簡單的字典形式存在於記憶體中,其中鍵為文件 ID,值為內容。
設定 MCP 伺服器
Python MCP SDK 讓伺服器建立變得簡單明瞭。您只需一行程式碼即可初始化伺服器:
python
from mcp.server.fastmcp import FastMCP
from pydantic import Field
mcp = FastMCP("DocumentMCP", log_level="ERROR")這會建立一個功能完整的 MCP 伺服器,能夠處理工具定義、客戶端連線以及訊息路由。
使用裝飾器定義工具

SDK 的裝飾器方法免除了手動撰寫 JSON 結構描述的需求。以下是定義簡單工具的方式:
python
@mcp.tool(
name="add_ints",
description="Add two integers together",
)
def tool_fn(
a=Field(description="First number to add"),
b=Field(description="Second number to add"),
) -> int:
return a + b在幕後,MCP 會產生 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]此函式包含基本的錯誤處理,用以攔截對不存在文件的請求。當 Claude 以有效的文件 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 white space."),
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)此實作使用 Python 內建的字串 replace 方法,該方法需要完全相符(包括空白字元)。此工具會就地修改字典中的文件。
SDK 方法的主要優勢
- 無需手動撰寫 JSON 結構描述
- 型別提示提供自動參數驗證
- 欄位描述有助於 Claude 理解工具用途
- 錯誤處理能與 Python 例外自然整合
- 工具註冊透過裝飾器自動完成
MCP Python SDK 將工具建立從複雜的結構描述撰寫工作,轉變為簡單明瞭的 Python 函式定義。您的工具變得更易於維護與測試,同時 Claude 也能獲得有效使用這些工具所需的所有元數據。