NestJS MCP Server Module

remote-capable server

The server can be hosted and run remotely because it primarily relies on remote services or has no dependency on the local environment.

Integrations

  • Provides a module for NestJS to create an MCP (Model Context Protocol) server with Server-Sent Events (SSE) transport, allowing services to be exposed as tools that clients can discover and execute.

  • Enables sending continuous progress updates from tools to clients, allowing for tracking of long-running operations with percentage completion indicators.

  • Integrates Zod schema validation for tool requests, enabling type-safe parameter validation for tools exposed through the MCP server.

NestJS MCP 服务器模块

NestJS 模块可使用**模型上下文协议 (MCP)**从 NestJS 应用程序轻松公开 AI 的工具、资源和提示。

@rekog/mcp-nest简化了 MCP 服务器的搭建。您可以用 NestJS 中熟悉的方式定义工具、资源和提示符,并充分利用依赖注入的强大功能来利用现有服务。

特征

  • 🚀 HTTP+SSE 和可流式传输的 HTTP 传输
  • 🔍 自动toolresourceprompt发现和注册
  • 💯 基于 Zod 的请求验证
  • 📊 进度通知
  • 🔒 基于 Guard 的身份验证
  • ⏱️ 自动 SSE ping 以维持长连接

安装

npm install @rekog/mcp-nest @modelcontextprotocol/sdk zod

快速入门

1.导入模块

// app.module.ts import { Module } from '@nestjs/common'; import { McpModule } from '@rekog/mcp-nest'; import { GreetingTool } from './greeting.tool'; @Module({ imports: [ McpModule.forRoot({ name: 'my-mcp-server', version: '1.0.0', }), ], providers: [GreetingTool], }) export class AppModule {}

2. 定义工具和资源

// greeting.tool.ts import { Injectable } from '@nestjs/common'; import { Tool, Resource, Context } from '@rekog/mcp-nest'; import { z } from 'zod'; import { Progress } from '@modelcontextprotocol/sdk/types'; @Injectable() export class GreetingTool { constructor() {} @Tool({ name: 'hello-world', description: 'Returns a greeting and simulates a long operation with progress updates', parameters: z.object({ name: z.string().default('World'), }), }) async sayHello({ name }, context: Context) { const greeting = `Hello, ${name}!`; const totalSteps = 5; for (let i = 0; i < totalSteps; i++) { await new Promise((resolve) => setTimeout(resolve, 500)); // Send a progress update. await context.reportProgress({ progress: (i + 1) * 20, total: 100, } as Progress); } return { content: [{ type: 'text', text: greeting }], }; } @Resource({ uri: 'mcp://hello-world/{userName}', name: 'Hello World', description: 'A simple greeting resource', mimeType: 'text/plain', }) // Different from the SDK, we put the parameters and URI in the same object. async getCurrentSchema({ uri, userName }) { return { content: [ { uri, text: `User is ${userName}`, mimeType: 'text/plain', }, ], }; } }

您已完成!

API 端点

  • GET /sse :SSE 连接端点(如果配置,则受保护)
  • POST /messages :工具执行端点(如果配置,则受保护)

尖端

可以使用带有全局前缀的模块,但建议使用以下方法排除这些端点:

app.setGlobalPrefix('/api', { exclude: ['sse', 'messages'] });

验证

您可以使用标准 NestJS Guards 保护您的 MCP 端点。

1. 创建一个守卫

实现CanActivate接口。该守卫应该处理请求验证(例如,检查 JWT、API 密钥),并可选地将用户信息附加到请求对象。

没什么特别的,请查看 NestJS 文档了解更多详细信息。

2. 应用防护

将您的防护传递给McpModule.forRoot配置。防护将同时应用于/sse/messages端点。

// app.module.ts import { Module } from '@nestjs/common'; import { McpModule } from '@rekog/mcp-nest'; import { GreetingTool } from './greeting.tool'; import { AuthGuard } from './auth.guard'; @Module({ imports: [ McpModule.forRoot({ name: 'my-mcp-server', version: '1.0.0', guards: [AuthGuard], // Apply the guard here }), ], providers: [GreetingTool, AuthGuard], // Ensure the Guard is also provided }) export class AppModule {}

就是这样!其余部分与 NestJS Guards 相同。

SSE Ping 服务

该模块包含一个 SSE ping 服务,可通过防止浏览器/客户端超时来帮助维持长效的 SSE 连接。这对于远程使用 MCP 服务器的客户端(例如 IDE)尤其有用。

配置

您可以在导入模块时配置 SSE ping 行为:

// app.module.ts import { Module } from '@nestjs/common'; import { McpModule } from '@rekog/mcp-nest'; @Module({ imports: [ McpModule.forRoot({ name: 'my-mcp-server', version: '1.0.0', sse: { pingEnabled: true, // Default is true pingIntervalMs: 30000, // Default is 30 seconds (30000ms) }, }), ], }) export class AppModule {}
-
security - not tested
A
license - permissive license
-
quality - not tested

NestJS 模块允许将服务公开为具有服务器发送事件传输的 MCP 服务器,从而方便客户端发现和执行工具。

  1. Features
    1. Installation
      1. Quick Start
        1. 1. Import Module
        2. 2. Define Tools and Resource
      2. API Endpoints
        1. Tips
      3. Authentication
        1. 1. Create a Guard
        2. 2. Apply the Guard
      4. SSE Ping Service
        1. Configuration
      ID: lh2oqhrntb