当您使用官方Python SDK时,构建MCP服务器会变得简单得多。您无需手动编写复杂的JSON schema,而是可以使用装饰器来定义工具,让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 schema的需要。以下是如何定义一个简单工具的方法:
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会生成完整的工具schema,供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内置的字符串替换方法,该方法需要精确匹配,包括空白字符。该工具会就地修改字典中的文档。
SDK方法的主要优势
- 无需手动编写JSON schema
- 类型提示提供自动参数验证
- 字段描述帮助Claude理解工具用法
- 错误处理与Python异常自然集成
- 工具注册通过装饰器自动完成
MCP Python SDK将工具创建从复杂的schema编写工作转变为简单直接的Python函数定义。您的工具变得更易于维护和测试,同时Claude也获得了有效使用这些工具所需的全部元数据。