Phần 9 · Model Context Protocol (MCP) · Bài 57

Định nghĩa tool bằng MCP

3:49

Việc xây dựng một MCP server (tạm dịch: máy chủ MCP) trở nên đơn giản hơn nhiều khi bạn dùng Python SDK (tạm dịch: bộ thư viện lập trình) chính thức. Thay vì tự viết các JSON schema phức tạp cho tool, SDK xử lý toàn bộ phần phức tạp đó giúp bạn bằng decorators và type hints.

Trong ví dụ này, chúng ta tạo một MCP server để quản lý các document được lưu trong memory. Server sẽ cung cấp hai tool thiết yếu: một tool để đọc nội dung document và một tool để cập nhật nội dung bằng thao tác tìm và thay thế.

Thiết lập MCP server

Python MCP SDK giúp việc tạo server trở nên cực kỳ đơn giản. Bạn có thể khởi tạo một MCP server hoàn chỉnh chỉ bằng một dòng:

from mcp.server.fastmcp import FastMCP

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

Trong phần implement này, các document được lưu trong một Python dictionary đơn giản. Key là document ID, còn value chứa nội dung document:

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"
}

Định nghĩa tool bằng decorators

SDK biến việc tạo tool từ một quy trình dài dòng thành code gọn gàng, dễ đọc. Thay vì viết những JSON schema dài, bạn dùng Python decorators và type hints.

Tạo tool đọc document

Tool đầu tiên cho phép Claude đọc bất kỳ document nào bằng ID của document đó. Đây là phần implement đầy đủ:

@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]

Decorator @mcp.tool tự động tạo JSON schema mà Claude cần. Class Field của Pydantic cung cấp mô tả parameter để giúp Claude hiểu mỗi argument cần gì.

Xây dựng tool sửa document

Tool thứ hai thực hiện thao tác tìm và thay thế đơn giản trên document:

@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)

Tool này nhận ba parameter: document ID, đoạn text cần tìm và đoạn text thay thế. Để giữ mọi thứ đơn giản, phần implement dùng method replace() có sẵn của Python string.

Xử lý lỗi

Cả hai tool đều có phần xử lý lỗi cơ bản cho trường hợp Claude yêu cầu một document không tồn tại. Khi nhận được document ID không hợp lệ, tool sẽ raise ValueError kèm một thông báo rõ ràng để Claude có thể hiểu và có thể xử lý tiếp.

Lợi ích chính khi dùng SDK

  • Tự động tạo JSON schema từ Python type hints
  • Code gọn gàng, dễ đọc và dễ bảo trì
  • Pydantic hỗ trợ sẵn việc kiểm tra parameter
  • Ít boilerplate hơn so với việc tự viết schema
  • Có type safety và hỗ trợ từ IDE khi phát triển

Python MCP SDK biến công việc định nghĩa tool vốn phức tạp thành một việc rất tự nhiên với Python developer. Bạn tập trung vào business logic, còn SDK lo các chi tiết của protocol.