使用 MCP(模型上下文协议)和 Claude 在 Node.js 中构建聊天应用程序

大家好,这里是架构资源栈 !点击上方关注,添加"星标",一起学习大厂前沿架构!

使用 Node.js 中的 MCP(模型上下文协议)构建聊天应用程序

我最近开发了一个简单的聊天应用程序,允许 Claude 使用模型上下文协议 (MCP) 调用外部工具。你也可以按照以下方法构建一个。

什么是 MCP?

模型上下文协议 (MCP) 是 Claude 等 AI 模型与外部工具交互的标准化方式。它提供了以下结构化格式:

  • 定义人工智能可以使用的工具
  • 从人工智能向工具发送请求
  • 将结果返回给人工智能

项目结构

该应用程序主要有三个部分:

  1. Express 服务器 (server.js):处理 Web 请求和用户会话
  2. MCP 客户端 (mcpClient.js):连接到 Claude 和 MCP 服务器
  3. MCP 服务器 (mcpServer.js):定义并实现工具

聊天界面


建筑学


如何向 MCP 服务器添加工具

MCP 服务器是定义 Claude 可以使用的工具的地方。以下是如何创建天气工具的基本示例:
登录后复制

html 复制代码
// In mcpServer.js
import { Server } from "@modelcontextprotocol/sdk/server/index.js";

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

// Define a weather tool
server.defineTool({
  name: "getCurrentWeather",
  description: "Get the current weather for a location",
  inputSchema: {
    type: "object",
    properties: {
      location: {
        type: "string",
        description: "The city and state, e.g. San Francisco, CA",
      },
      unit: {
        type: "string",
        enum: ["celsius", "fahrenheit"],
        description: "The unit of temperature to use",
      },
    },
    required: ["location"],
  },
  handler: async function (args) {
    const { location, unit = "celsius" } = args;

    // Here you would typically call a weather API
    // For demo purposes, we're returning mock data
    return {
      location: location,
      temperature: unit === "celsius" ? 22 : 72,
      conditions: "Sunny",
      humidity: "45%",
      windSpeed: "10 km/h",
    };
  },
});

// Start the server
server.start();

Enter fullscreen mode Exit fullscreen mode

可用的工具类型

您可以创建不同类型的工具供 Claude 使用:

  1. 数据检索工具:获取天气、新闻、股票价格等。
  2. 计算工具:执行复杂的计算或数据分析
  3. 数据库工具:查询或更新数据库
  4. API 集成工具:连接外部服务
  5. 文件处理工具:读取、写入或分析文件

MCP 客户端的工作原理

MCP 客户端将 Claude 连接到您的工具:
登录后复制

html 复制代码
async processQuery(query) {
  // Add user message to history
  this.chatHistory.push({ role: 'user', content: query });

  // Send to Claude with tool definitions
  const response = await this.anthropic.messages.create({
    model: "claude-3-5-sonnet-20241022",
    max_tokens: 1000,
    messages: this.chatHistory,
    tools: this.tools,
  });

  // Process the response
  for (const content of response.content) {
    if (content.type === "tool_use") {
      // Claude wants to use a tool
      const result = await this.mcp.callTool({
        name: content.name,
        arguments: content.input,
      });

      // Send tool result back to Claude
      this.chatHistory.push({
        role: "user",
        content: JSON.stringify(result.content),
      });
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

设置你的项目

要构建您自己的 MCP 聊天应用程序:

  1. 克隆存储库:git clone https://github.com/RajeshRenato/mcp-node
  2. 安装依赖项:npm install
  3. 将您的 Anthropic API 密钥添加到.env文件
  4. 在中创建您的工具mcpServer.js
  5. 启动服务器:node server.js

您可以构建的示例工具

以下是一些您可以添加的工具的想法:

  • 新闻搜索:获取有关某个主题的最新新闻文章
  • 维基百科查找:搜索并总结维基百科内容
  • 日历集成:检查或创建日历事件
  • 语言翻译:在多种语言之间翻译文本
  • 图像生成:根据文本描述生成图像(使用 DALL-E 或类似工具)

结论

模型上下文协议 (MCP) 为 AI 应用开辟了激动人心的可能性。通过授予 Claude 访问外部工具的权限,您可以构建功能强大的交互式应用程序,将 AI 与实时数据和功能相结合。

想亲自尝试一下吗?在GitHub上获取完整代码。

原文地址:

本文由博客一文多发平台 OpenWrite 发布!

相关推荐
wno70410 小时前
node.js中使用jquery
前端·node.js·jquery
damoluomu1 天前
Node 的 Headless 出厂没有前台,Java 的 Headless 是从门户里长出来的
java·开发语言·node.js
Dumbness1 天前
一个手机号验证码登录接口的五个坑:无限发码、无限试码,传个数字就让 Express 进程退出
node.js·express
怒放的生命19911 天前
本地用 pnpm 省磁盘,团队继续用 npm:极简实践
前端·npm·node.js
Hone2 天前
我把「自动发文章到掘金」做成了一个 Agent 技能:juejin-skills
node.js·ai编程·前端工程化
Dumbness2 天前
二十行手写的 SKILL.md 头部解析,遇到 YAML 的折叠写法、单引号和嵌套键就读错:和 js-yaml 逐条对照
node.js·ai编程
只睡四小时3 天前
MCP 弃用 SSE?Node 分帧漏 81.7% 事件
node.js·webassembly·实时通信·mcp·streamable http
hey you~3 天前
个体户门店办理400电话,如何对接订单系统实现来电弹窗
node.js·webhook·400电话·门店数字化·来电弹窗·订单系统对接
YIAN4 天前
RAG 学到最后,我真正学会的不是“检索”,而是让系统知道自己缺什么
langchain·node.js·llm