MCP服务器开发教程:5步构建自己的AI Agent工具

📘 AI教程 💬 🔥 Trending

🩺 摘要

MCP协议让Agent工具开发标准化了。写一个MCP服务器就像写一个简单的API——定义工具、暴露接口、让Agent自动发现。

📝 详情

MCP服务器是什么?

MCP(Model Context Protocol)是Agent工具的"USB-C接口"。你的工具只需要实现MCP协议,任何兼容的Agent框架都能自动使用它。

5步构建MCP服务器

Step 1:初始化项目

mkdir my-mcp-server
cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk

Step 2:定义工具

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

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

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: "get_weather",
    description: "获取城市天气",
    inputSchema: {
      type: "object",
      properties: {
        city: { type: "string" }
      }
    }
  }]
}));

Step 3:实现工具逻辑

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "get_weather") {
    const city = request.params.arguments?.city;
    return {
      content: [{ type: "text", text: `${city}天气:晴,25°C` }]
    };
  }
});

Step 4:启动服务

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

Step 5:在Agent框架中配置 在CrewAI或LangChain中配置MCP服务器地址即可。

MCP的工作原理

Agent(客户端)→ MCP协议请求 → MCP服务器
              ← 工具列表/结果 ←
  • Transport层:stdio(本地)或SSE(远程)
  • 协议层:JSON-RPC 2.0
  • 工具层:你的业务逻辑

总结

MCP服务器的核心价值是一次开发、到处使用。你写一个MCP服务器,所有兼容MCP的Agent框架都能自动发现和调用你的工具。2026年,新工具不提供MCP接口就像新设备不支持USB-C。