MCP 服务器实战指南:什么是 MCP,为什么它是 2026 年 AI 开发者的必学技能

📘 AI教程 💬 🔥 Trending

🩺 摘要

📝 详情

如果你还没听说过 MCP——Model Context Protocol,那你可能错过了 2025-2026 年 AI 领域最重要的一次协议标准化。

简单说:MCP 是 AI 模型的「USB 接口」。以前每个 AI 工具都要自己写一套 API 跟模型对接,一地鸡毛。MCP 统一了这个接口——你写一个 MCP Server,所有支持 MCP 的 AI 客户端都能用它。


MCP 到底是什么

MCP 由 Anthropic 在 2024 年底提出,开源协议(GitHub Stars 88,599 ⭐,modelcontextprotocol/servers 仓库),目标是给 LLM 一个标准化的「工具调用」协议。

没有 MCP 之前,你想让 AI 读取文件、查数据库、发邮件,需要: 1. 写自定义 Function Calling 函数 2. 按各家 API 格式注册工具 3. 每次换 AI 模型都要重写适配层

有了 MCP 之后: 1. 写一个 MCP Server 2. 任何 MCP 客户端(Claude Desktop、VS Code 插件、Open WebUI、Cline 等)自动发现并可用

MCP 的核心概念

┌──────────────────┐     MCP 协议      ┌──────────────────┐
│                  │ ◄─────────────► │                  │
│  MCP Client      │                  │  MCP Server      │
│  (Claude, Cline, │   JSON-RPC      │  (文件系统、      │
│   Open WebUI等)  │   2.0 over      │  数据库、API、    │
│                  │   stdio/SSE      │  自定义工具等)    │
└──────────────────┘                  └──────────────────┘

MCP Server 能干啥? 说白了就是一个给 AI 用的「工具箱」——每个 MCP Server 暴露一组工具(tools),AI 客户端可以在对话中自动调用这些工具。

现有 MCP Server 生态

官方 + 社区已经有一百多个 MCP Server 了。按使用频率排序(截至 2026 年 7 月):

类型 MCP Server 用途 推荐度
🔧 开发者工具
文件系统 filesystem 读写本地文件 ⭐⭐⭐⭐⭐
Git git 管理 Git 仓库 ⭐⭐⭐⭐⭐
GitHub github PR/Issue/代码管理 ⭐⭐⭐⭐
数据库 sqlite/postgres 查询数据库 ⭐⭐⭐⭐⭐
🛠 实用工具
浏览器 playwright 网页截图/操作 ⭐⭐⭐⭐
搜索 brave-search/web 网络搜索 ⭐⭐⭐⭐
代码 execute-code 运行代码 ⭐⭐⭐⭐
🎨 创意工具
图像 sequential-thinking 复杂推理 ⭐⭐⭐
记忆 memory 持久化记忆 ⭐⭐⭐⭐

实战:搭建你的第一个 MCP Server

方案 A:直接用社区现成的(最快)

如果你用的是 VS Code + Cline 或 Claude Desktop,配置 MCP Server 只需改一行 JSON:

配置方式(Claude Desktop 为例):

// ~/AppData/Roaming/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "C:\\projects",
        "D:\\documents"
      ]
    },
    "sqlite": {
      "command": "uvx",
      "args": ["mcp-server-sqlite", "--db-path", "C:\\data\\test.db"]
    },
    "github": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-github"
      ],
      "env": {
        "GITHUB_TOKEN": "ghp_xxx"
      }
    }
  }
}

重启 Claude Desktop,你的 AI 助手就能直接读你的文件、查数据库、管理 GitHub 仓库了。

方案 B:用 Python 写一个自定义 MCP Server

如果你的场景比较特殊(比如查询公司内部 API),自己写一个 MCP Server 其实很简单:

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import json

app = Server("my-custom-server")

# 1. 声明提供哪些工具
@app.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="get_weather",
            description="查询指定城市的天气",
            inputSchema={
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名"}
                },
                "required": ["city"]
            }
        ),
        Tool(
            name="calculate",
            description="执行数学计算",
            inputSchema={
                "type": "object",
                "properties": {
                    "expression": {"type": "string", "description": "数学表达式"}
                },
                "required": ["expression"]
            }
        )
    ]

# 2. 实现工具逻辑
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    if name == "get_weather":
        city = arguments["city"]
        # 这里可以调真实天气 API
        return [TextContent(
            type="text",
            text=f"{city} 当前温度:28°C,晴"
        )]
    elif name == "calculate":
        expr = arguments["expression"]
        try:
            result = eval(expr)  # 注意:生产环境不要用 eval
            return [TextContent(type="text", text=str(result))]
        except Exception as e:
            return [TextContent(type="text", text=f"错误:{str(e)}")]

# 3. 启动
if __name__ == "__main__":
    import asyncio
    asyncio.run(stdio_server(app))

然后配置你的客户端指向这个脚本:

{
  "mcpServers": {
    "my-custom-server": {
      "command": "python",
      "args": ["path/to/my_server.py"]
    }
  }
}

方案 C:用 TypeScript 写

MCP 官方推荐用 TypeScript 写(生态最完善):

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";

const server = new Server({ name: "my-server", version: "1.0.0" }, {
  capabilities: { tools: {} }
});

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: "hello",
    description: "Say hello",
    inputSchema: { type: "object", properties: { name: { type: "string" } }, required: ["name"] }
  }]
}));

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "hello") {
    return { content: [{ type: "text", text: `Hello, ${request.params.arguments?.name}!` }] };
  }
  throw new Error("Unknown tool");
});

const transport = new StdioServerTransport();
await server.connect(transport);

MCP 的通信方式

MCP 支持两种传输层:

  1. stdio(标准输入输出):最常用。客户端启动一个子进程,通过 stdin/stdout 通信
  2. SSE(Server-Sent Events):远程 MCP Server,通过 HTTP 通信

对于本地开发,99% 的情况用 stdio 就够了。远程部署时(比如把 MCP Server 部署到服务器上给多个客户端用),才需要 SSE 模式。

常见问题

Q:MCP 和 Function Calling / Tool Use 什么关系? A:MCP 是 Function Calling 的「上层标准」。Function Calling 定义了「单个模型如何调用工具」,MCP 定义了「整个生态系统如何发现和调用工具」。你可以理解为 HTTP 协议 vs 具体的 REST API。

Q:哪些客户端支持 MCP? A:Claude Desktop(原生支持)、VS Code 插件(Cline, Continue)、Open WebUI、Windsurf、Cursor 等。截至 2026 年 7 月,几乎所有主流 AI 编程工具都支持了。

Q:MCP Server 安全吗? A:MCP Server 以子进程运行,有自己的权限边界。理论上它只能做你赋予它的操作——比如 filesystem MCP 只读你指定的目录。但还是要小心:别给 AI 一个「可以执行任意命令」的 MCP Server。

总结

MCP 是 2026 年 AI 开发者的必备技能。你不需要从一开始就写自己的 MCP Server——先安装几个现成的(filesystem, sqlite, github),体验一下 AI 助手「突然变能干」的感觉。然后等你有「AI 要是能调这个 API 就好了」的想法时,花 20 分钟写一个自定义 MCP Server。

📊 数据来源:GitHub API 查询时间 2026-07-18。MCP 协议版本基于 2026 年 6 月最新规范。

🔗 相关文章: Open WebUI 深度使用指南:搭建你的私人 AI 助手