加载中
加载中

使用官方 Python SDK 时,构建 MCP 服务器会变得简单得多。您无需手动编写复杂的 JSON 模式来定义工具,SDK 会通过装饰器和类型提示为您处理所有这些复杂性。

我们的 MCP 服务器拥有读取和更新文档的工具,连接到 document.pdf、spreadsheet.xlsx、report.txt 和 spec.md。

在这个示例中,我们正在创建一个管理内存中存储的文档的 MCP 服务器。该服务器将提供两个基本工具:一个用于读取文档内容,另一个用于通过查找替换操作来更新文档。

设置 MCP 服务器

该项目使用 MCP Python SDK 的第 1 版,其设置会为您安装该版本。如果您要自行设置项目,请安装 "mcp[cli]<2"。版本 2 将 FastMCP 重命名为 MCPServer,因此下面的导入在该版本上会失败。

Python MCP SDK 让服务器创建变得异常简单。您只需一行代码即可初始化一个完整的 MCP 服务器:

python
from mcp.server.fastmcp import FastMCP
from pydantic import Field

mcp = FastMCP("DocumentMCP", log_level="ERROR")

在这个实现中,文档被存储在一个简单的 Python 字典中,其中键是文档 ID,值包含文档内容:

python
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 expenditure",
    "outlook.pdf": "This document presents the projected future performance of the",
    "plan.md": "The plan outlines the steps for the project's implementation.",
    "spec.txt": "These specifications define the technical requirements for the equipment"
}

使用装饰器进行工具定义

我们的 MCP 服务器拥有读取和更新文档的工具,连接到 document.pdf、spreadsheet.xlsx、report.txt 和 spec.md。

该 SDK 将工具创建从一个冗长的过程转变为简洁易读的过程。您无需编写冗长的 JSON 模式,而是使用 Python 装饰器和类型提示。

创建文档读取工具

第一个工具允许 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]

@mcp.tool 装饰器会自动生成 Claude 所需的 JSON 模式。来自 Pydantic 的 Field 类提供参数描述,帮助 Claude 理解每个参数的预期内容。

构建文档编辑工具

第二个工具在文档上执行简单的查找替换操作:

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 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() 方法来实现简洁性。

错误处理

这两个工具都包含基本的错误处理,以应对 Claude 请求不存在的文档的情况。当提供了无效的文档 ID 时,这些工具会抛出一个带有描述性消息的 ValueError,Claude 可以理解并据此采取相应行动。

SDK 方法的主要优势

  • 根据 Python 类型提示自动生成 JSON 模式
  • 简洁、易读、易于维护的代码
  • 通过 Pydantic 实现内置参数验证
  • 相比手动编写模式减少了样板代码
  • 开发时的类型安全性和 IDE 支持

MCP Python SDK 将曾经复杂的工具定义编写过程转变为对 Python 开发人员来说自然而然的事情。您可以专注于业务逻辑,而 SDK 会处理协议细节。