时间上下文服务

基于NestJS和LangChain.js的微服务架构,提供时间上下文功能,适用于需要实时时间信息的LLM应用。

  • by LiusDev
  • TypeScript
  • 本地部署
  • 11 星标
  • 更新于
在 GitHub 查看 LiusDev/nestjs-mcp-server-langchainjs-demo

使用说明

NestJS MCP服务器-模型上下文协议示例

通过: @刘德夫

此存储库演示了具有微服务架构的模型上下文协议(MCP)的NestJS实现。它由两个主要服务组成:

  1. mcp服务器:提供获取LLM当前时间上下文的函数
  2. mcp后端:使用LangChain.js并与MCP客户端SDK集成以连接到MCP服务器的客户端

入门指南

先决条件

  • Node.js(v20或更高版本)
  • npm

安装

  1. 克隆存储库
  2. 安装依赖项:
npm install
  1. 重命名 .env.example 向 .env 并添加您的OpenAI API密钥:
cp .env.example .env

然后编辑 .env 文件以包含您的OpenAI API密钥:

OPENAI_API_KEY=your_openai_api_key_here
OPENAI_API_URL=https://api.openai.com/v1
PORT=3001

运行服务

您需要运行这两个服务才能获得完整的功能:

启动MCP服务器

npm run start:dev mcp-server

这将启动端口3000上的MCP服务器(默认)。

启动MCP后端

npm run start:dev mcp-backend

这将启动端口3001上的MCP后端(默认)。

用法示例

两个服务都运行后,您可以通过向MCP后端发送POST请求来测试功能:

样品申请

向发送POST请求 http://localhost:3001 具有以下JSON正文:

{
  "message": "What time is it in Viet Nam?"
}

使用cURL

curl -X POST http://localhost:3001 -H "Content-Type: application/json" -d "{\"message\": \"What time is it in Viet Nam?\"}"

使用邮递员

  1. 创建一个新的POST请求 http://localhost:3001
  2. 将Content-Type标头设置为 application/json
  3. 在请求正文中,选择“raw”和“JSON”,然后输入:
    {
      "message": "What time is it in Viet Nam?"
    }
    
  4. 发送请求

响应将包含通过MCP服务器的时间上下文功能检索到的越南当前时间。

连接到多个MCP服务器

后端可以同时连接到多个MCP服务器。要添加其他服务器,请修改 McpClientModule.register 配置在 apps/mcp-backend/src/mcp-backend.module.ts:

McpClientModule.register({
  throwOnLoadError: true,
  prefixToolNameWithServerName: false,  // Set to true to prefix tool names with server names
  additionalToolNamePrefix: '',
  mcpServers: {
    myServer: {
      transport: 'sse',
      url: 'http://localhost:3000/sse',
      useNodeEventSource: true,
      reconnect: {
        enabled: true,
        maxAttempts: 5,
        delayMs: 2000,
      },
    },
    // Add additional servers here
    anotherServer: {
      transport: 'sse',
      url: 'http://localhost:4000/sse',  // Different port for another server
      useNodeEventSource: true,
      reconnect: {
        enabled: true,
        maxAttempts: 5,
        delayMs: 2000,
      },
    },
  },
}),

连接到多个服务器时:

  • 考虑设置 prefixToolNameWithServerName: true 避免工具名称冲突
  • 确保每台服务器在 mcpServers 对象
  • 确保每台服务器都在不同的端口上运行

MCP客户端将自动从所有配置的服务器中获取工具,并使其可供LLM使用。

建筑

  • mcp服务器:通过模型上下文协议公开工具,包括获取当前时间的函数
  • mcp后端:连接到MCP服务器,检索可用工具,并将其与LangChain.js一起使用来处理用户查询

使用的技术

  • NestJS
  • LangChain.js
  • 模型上下文协议(MCP)
  • @langchain/mcp适配器:用于langchain.js的mcp客户端适配器
  • @rekog/mcp-nest:NestJS的mcp服务器实现

项目结构

mcp-server/
├── apps/
│   ├── mcp-server/       # MCP server implementation
│   └── mcp-backend/      # MCP client implementation
├── dist/                 # Compiled output
├── node_modules/
├── .env                  # Environment variables
└── package.json

许可证

此项目根据未授权许可证授权-有关详细信息,请参阅许可证文件。