手把手教你创建一个能跑通的 MCP Server,并注册到 AI IDE
15 分钟从零搭建一个完整的 MCP Skill —— 包含项目初始化、Schema 设计、工具实现、调试测试,最后注册到 Trae / Cursor 中真正用起来。
MCP(Model Context Protocol)是 Anthropic 发起的开放协议,让 AI Agent 能以统一的方式调用外部工具。你可以把 MCP Server 理解为一个"给 AI 用的 API"—— 它通过 JSON-RPC 协议暴露一组工具(Tools)、资源(Resources)和提示(Prompts),AI Agent 可以自动发现和调用。 一个 MCP Server 本质上就是一个进程,它在 stdio 上监听 JSON-RPC 请求。你可以用任何语言实现,但社区最成熟的 SDK 在 TypeScript 和 Python。
先创建一个 Node.js + TypeScript 项目,然后安装 MCP SDK: mkdir my-first-mcp && cd my-first-mcp npm init -y npm install @modelcontextprotocol/sdk @modelcontextprotocol/server-node npm install -D typescript @types/node tsx 接着写 tsconfig.json,配置 TypeScript 编译输出到 dist/。
创建 src/server.ts,注册一个"天气查询"工具作为示例: import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; const server = new McpServer({ name: "weather-mcp", version: "1.0.0" }); server.tool("get-weather", { city: z.string() }, async ({ city }) => { // 这里调用真实的天气 API return { content: [{ type: "text", text: `${city}: 晴, 25°C` }] }; });
添加启动代码让 Server 在 stdio 上监听: const transport = new StdioServerTransport(); await server.connect(transport); 然后用 npx tsx src/server.ts 启动它。这是一个长驻进程,会一直等待 AI Agent 的调用请求。
打开 Trae → 设置 → 搜索 "MCP" → 添加 Server: - 名称:weather-mcp - 命令:npx - 参数:["tsx", "/path/to/my-first-mcp/src/server.ts"] 保存后重启 Trae,你的 AI 对话中就能调用 get-weather 工具了!
在项目根目录创建 .cursor/mcp.json: { "mcpServers": { "weather": { "command": "npx", "args": ["tsx", "src/server.ts"] } } } 重新打开 Cursor,Agent 自动发现新工具,你就可以在 Chat 或 Composer 里使用了。