当您使用官方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接收到格式正确的工具规范。