第 02 章进阶15 分钟

第 2 章:搭建第一个 MCP Server

用最小代码定义一个工具,理解 Server 如何声明能力并响应调用。

作者:AI 工具组 · 更新:2026-06-02 · 阅读:762

学习目标

这一章动手写一个最小的 MCP Server,暴露一个 add 工具。

定义工具

使用官方 SDK 时,注册工具通常是声明名称、输入 schema 和处理函数:

from mcp.server import Server
import mcp.types as types

app = Server("demo")

@app.list_tools()
async def list_tools():
    return [types.Tool(
        name="add",
        description="两数相加",
        inputSchema={
            "type": "object",
            "properties": {
                "a": {"type": "number"},
                "b": {"type": "number"}
            },
            "required": ["a", "b"]
        },
    )]

@app.call_tool()
async def call_tool(name, arguments):
    if name == "add":
        return [types.TextContent(type="text", text=str(arguments["a"] + arguments["b"]))]

要点

  • inputSchema 用标准 JSON Schema 描述参数,模型据此填参。
  • 返回值是结构化内容块,不是裸字符串。

练习任务

给这个 Server 再加一个 multiply 工具,并补全输入校验。