加载中

使用MCP定义工具

第 50 课10 分钟

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

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

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

设置MCP服务器

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会处理协议细节。