MCP爆火了!Nodejs用户也不能落后

MCP概述

什么是MCP

MCP (Model Context Protocol) 是Anthropic开源的模块化控制协议,为AI应用开发提供标准化接口规范。它类似于计算机中的USB标准,定义了不同组件间的交互方式。
在这里插入图片描述

设计理念

  • 模块化架构:功能解耦为独立单元
  • 协议优先:标准化接口定义
  • 类型安全:完善的TypeScript支持
  • 可观测性:内置监控指标

应用场景

场景类型典型案例MCP优势
智能客服自动问答系统提示模板+资源管理
电商推荐个性化推荐采样+资源组合
IoT平台设备管理工具+传输层
数据分析实时看板采样+资源

核心概念解析

六大核心组件

  1. Resources (资源)
    作用:静态数据提供者,类似REST API的GET端点
    特点
  • 只读访问
  • 无副作用
  • 支持URI模式匹配

实战案例:产品目录查询

server.resource(
  "products",
  new ResourceTemplate("products://{category}/{id}"),
  async (uri, { category, id }) => {
    const product = await db.products.find({ category, id });
    return { contents: [{ uri: uri.href, ...product }] };
  }
);
  1. Prompts (提示)
    作用:结构化对话模板
    特点
  • 可复用对话模式
  • 支持变量插值
  • 多轮对话管理

实战案例:客服对话模板

server.prompt(
  "customer-service",
  { issue: z.string(), userId: z.string() },
  ({ issue, userId }) => ({
    messages: [{
      role: "system",
      content: `用户${userId}反馈问题:${issue}。请用专业礼貌的语气回复`
    }]
  })
);
  1. Tools (工具)
    作用:执行具体操作
    特点
  • 允许副作用
  • 需要权限控制
  • 同步/异步执行

实战案例:邮件发送工具

server.tool(
  "send-email",
  { 
    to: z.string().email(),
    subject: z.string(),
    body: z.string() 
  },
  async ({ to, subject, body }) => {
    await emailService.send({ to, subject, body });
    return { content: [{ type: "text", text: "邮件发送成功" }] };
  }
);
  1. Sampling (采样)
    作用:数据抽样与分析
    特点
  • 多种采样算法
  • 实时数据分析
  • 概率控制

实战案例:AB测试分流

import { Sampling } from '@modelcontextprotocol/sdk';

// 用户分组采样
const userGroup = Sampling.weighted(
  ['groupA', 'groupB'], 
  [0.3, 0.7],  // 30%进入A组,70%进入B组
  1
)[0];
  1. Roots (根服务)
    作用:服务发现与目录
    特点
  • 全局服务注册
  • 依赖解析
  • 版本管理

实战案例:微服务协调

const paymentService = await Roots.resolve(
  "payment-service", 
  { version: "1.2.0" }
);
  1. Transports (传输层)
    作用:通信协议抽象
    支持协议
  • HTTP/REST
  • WebSocket
  • 自定义二进制协议

实战案例:多协议适配

// 同时暴露HTTP和WebSocket接口
const httpTransport = new HTTPServerTransport({ port: 8080 });
const wsTransport = new WebSocketTransport({ port: 8081 });

await server.connect(httpTransport);
await server.connect(wsTransport);

组件交互流程

Client Transport Router Resource Tool 请求 路由分发 数据请求 返回数据 执行操作 操作结果 组合响应 最终响应 Client Transport Router Resource Tool

TypeScript实战

开发环境搭建

初始化项目
# 创建项目
npm init -y

# 安装依赖
pnpm i @modelcontextprotocol/sdk zod -S
pnpm i @types/node typescript -D

# TS初始化
npx tsc --init
配置详解

tsconfig.json 关键配置:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true
  }
}

package.json 脚本配置:

{
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "mcp": "npx @modelcontextprotocol/inspector node dist/index.js"
  }
}

基础服务搭建

import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from 'zod';

const server = new McpServer({
    name: "MCP Demo",
    version: "0.0.1",
})

// 注册资源
// 资源是向 LLM 公开数据的方式。它们类似于 REST API 中的 GET 端点 - 它们提供数据,但不应执行大量计算或有副作用。
server.resource(
    "echo",
    new ResourceTemplate("echo://{message}", { list: undefined }),
    async (uri, { message }) => ({
        contents: [{
            uri: uri.href,
            text: `Resource echo: ${message}`
        }]
    })
);

// 注册工具
// 工具允许 LLM 通过您的服务器执行作。与资源不同,工具需要执行计算并具有副作用。
server.tool(
    "echo",
    { message: z.string() },
    async ({ message }) => ({
        content: [{ type: "text", text: `Tool echo: ${message}` }]
    })
);

// 注册提示
// 提示是可重用的模板,可帮助 LLM 有效地与您的服务器交互。
server.prompt(
    "echo",
    { message: z.string() },
    ({ message }) => ({
        messages: [{
            role: "user",
            content: {
                type: "text",
                text: `Please process this message: ${message}`
            }
        }]
    })
);

// 启动服务
const main = async () => {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.log("服务已启动");
}
main().catch(err => {
    console.error("服务启动失败", err);
})

测试与调试

本地测试

# 编译运行
pnpm build && pnpm start

# 使用官方检查器
pnpm mcp

调试技巧

  1. 使用mcp dashboard启动可视化调试
  2. 日志分级配置:
    server.setLogLevel('debug');
    
  3. 性能监控:
    mcp monitor --port 3000
    

学习资源

官方文档

国内平台

  • B站:有很多手把手搭建MCP服务器的视频教程
  • 掘金/CSDN/雀语:相关文章和笔记

优质资源网站

  1. Smithery - 收藏2000+ MCP Servers,可直接复制Install Command
  2. PulseMCP - 整理MCP Servers和Clients,每周更新新闻
  3. Awesome MCP Servers - 分类清晰,方便查找
  4. mcp.so - 将MCP分为三类收集,支持提交自己的Server
  5. Glama MCP - 收集1600+ MCP Servers
  6. Cursor Directory - 收集1800+ MCP Servers
  7. portkey.ai - 通过统一接口管理AI应用
  8. Cline MCP Marketplace - VSCode插件,简化MCP配置

通过本文的系统性学习,您已经掌握了MCP从理论到实践的全套知识。建议从官方Starter Kit开始,逐步构建您的第一个MCP应用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值