使用 MCP(模型上下文協(xié)議)和 Claude 在 Node.js 中構(gòu)建聊天應(yīng)用程序

大家好,這里是架構(gòu)資源棧!點(diǎn)擊上方關(guān)注,添加“星標(biāo)”,一起學(xué)習(xí)大廠前沿架構(gòu)!

使用 Node.js 中的 MCP(模型上下文協(xié)議)構(gòu)建聊天應(yīng)用程序

我最近開發(fā)了一個(gè)簡單的聊天應(yīng)用程序,允許 Claude 使用模型上下文協(xié)議 (MCP) 調(diào)用外部工具。你也可以按照以下方法構(gòu)建一個(gè)。

什么是 MCP?

模型上下文協(xié)議 (MCP) 是 Claude 等 AI 模型與外部工具交互的標(biāo)準(zhǔn)化方式。它提供了以下結(jié)構(gòu)化格式:

  • 定義人工智能可以使用的工具
  • 從人工智能向工具發(fā)送請求
  • 將結(jié)果返回給人工智能

項(xiàng)目結(jié)構(gòu)

該應(yīng)用程序主要有三個(gè)部分:

  1. Express 服務(wù)器server.js):處理 Web 請求和用戶會(huì)話
  2. MCP 客戶端mcpClient.js):連接到 Claude 和 MCP 服務(wù)器
  3. MCP 服務(wù)器mcpServer.js):定義并實(shí)現(xiàn)工具

聊天界面

建筑學(xué)

如何向 MCP 服務(wù)器添加工具

MCP 服務(wù)器是定義 Claude 可以使用的工具的地方。以下是如何創(chuàng)建天氣工具的基本示例:

// 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

可用的工具類型

您可以創(chuàng)建不同類型的工具供 Claude 使用:

  1. 數(shù)據(jù)檢索工具:獲取天氣、新聞、股票價(jià)格等。
  2. 計(jì)算工具:執(zhí)行復(fù)雜的計(jì)算或數(shù)據(jù)分析
  3. 數(shù)據(jù)庫工具:查詢或更新數(shù)據(jù)庫
  4. API 集成工具:連接外部服務(wù)
  5. 文件處理工具:讀取、寫入或分析文件

MCP 客戶端的工作原理

MCP 客戶端將 Claude 連接到您的工具:

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

設(shè)置你的項(xiàng)目

要構(gòu)建您自己的 MCP 聊天應(yīng)用程序:

  1. 克隆存儲(chǔ)庫:git clone https://github.com/RajeshRenato/mcp-node
  2. 安裝依賴項(xiàng):npm install
  3. 將您的 Anthropic API 密鑰添加到.env文件
  4. 在中創(chuàng)建您的工具mcpServer.js
  5. 啟動(dòng)服務(wù)器:node server.js

您可以構(gòu)建的示例工具

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

  • 新聞搜索:獲取有關(guān)某個(gè)主題的最新新聞文章
  • 維基百科查找:搜索并總結(jié)維基百科內(nèi)容
  • 日歷集成:檢查或創(chuàng)建日歷事件
  • 語言翻譯:在多種語言之間翻譯文本
  • 圖像生成:根據(jù)文本描述生成圖像(使用 DALL-E 或類似工具)

結(jié)論

模型上下文協(xié)議 (MCP) 為 AI 應(yīng)用開辟了激動(dòng)人心的可能性。通過授予 Claude 訪問外部工具的權(quán)限,您可以構(gòu)建功能強(qiáng)大的交互式應(yīng)用程序,將 AI 與實(shí)時(shí)數(shù)據(jù)和功能相結(jié)合。

想親自嘗試一下嗎?在GitHub上獲取完整代碼。

原文地址:
本文由博客一文多發(fā)平臺(tái) OpenWrite 發(fā)布!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容