返回教程列表
入门
入门 · 15 分钟 · MCP / 入门 / Node.js / TypeScript

从 0 到 1 搭建你的第一个 MCP Skill

手把手教你创建一个能跑通的 MCP Server,并注册到 AI IDE

15 分钟从零搭建一个完整的 MCP Skill —— 包含项目初始化、Schema 设计、工具实现、调试测试,最后注册到 Trae / Cursor 中真正用起来。

什么是 MCP

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。

Step 1 — 初始化项目

先创建一个 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/。

Step 2 — 定义你的第一个工具

创建 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` }] }; });

Step 3 — 启动 Server

添加启动代码让 Server 在 stdio 上监听: const transport = new StdioServerTransport(); await server.connect(transport); 然后用 npx tsx src/server.ts 启动它。这是一个长驻进程,会一直等待 AI Agent 的调用请求。

Step 4 — 注册到 Trae

打开 Trae → 设置 → 搜索 "MCP" → 添加 Server: - 名称:weather-mcp - 命令:npx - 参数:["tsx", "/path/to/my-first-mcp/src/server.ts"] 保存后重启 Trae,你的 AI 对话中就能调用 get-weather 工具了!

Step 5 — 注册到 Cursor

在项目根目录创建 .cursor/mcp.json: { "mcpServers": { "weather": { "command": "npx", "args": ["tsx", "src/server.ts"] } } } 重新打开 Cursor,Agent 自动发现新工具,你就可以在 Chat 或 Composer 里使用了。

完成检查清单

  • 有一个能跑通的 MCP Server 进程
  • AI Agent 能发现并调用你的工具
  • 工具返回正确的结构化结果
  • 错误处理完备(API 挂了也不崩)

难度信息

难度:入门

预计用时:15 分钟

标签:MCP · 入门 · Node.js · TypeScript

相关 MCP Skills

需要手把手带?

读完教程还是搞不定?我们提供一对一远程辅导服务。

预约辅导