Skip to main content
Glama
rekog-labs

NestJS MCP Server Module

by rekog-labs

NestJS MCP 服务器模块

CI 代码覆盖率 NPM 版本 NPM 下载 NPM 许可证

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

使用@rekog/mcp-nest您可以按照 NestJS 中熟悉的方式定义工具、资源和提示,并充分利用依赖注入的全部功能,利用现有代码库构建复杂的企业级 MCP 服务器。

特征

  • 🚀 支持所有运输类型:

    • 可流式传输的 HTTP

    • HTTP+SSE

    • 标准输出

  • 🔍 自动toolresourceprompt发现和注册

  • 💯 基于 Zod 的工具调用验证

  • 📊 进度通知

  • 🔒 基于 Guard 的身份验证

  • 🌐 访问 MCP 资源(工具、资源、提示)中的 HTTP 请求信息

Related MCP server: SSE MCP Server

安装

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 type { Request } from 'express'; 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, request: Request) { const userAgent = request.get('user-agent') || 'Unknown'; const greeting = `Hello, ${name}! Your user agent is: ${userAgent}`; const totalSteps = 5; for (let i = 0; i < totalSteps; i++) { await new Promise((resolve) => setTimeout(resolve, 100)); // 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', }, ], }; } }

您已完成!

以上示例展示了如何在 MCP 工具中访问 HTTP Request标头。这对于识别用户、添加客户端特定逻辑以及许多其他用例非常有用。更多示例,请参阅身份验证测试

STDIO 快速入门

主要区别在于您需要在导入模块时提供transport选项。

McpModule.forRoot({ name: 'playground-stdio-server', version: '0.0.1', transport: McpTransportType.STDIO, });

其余部分相同,您可以像往常一样定义工具、资源和提示。使用 STDIO 传输的独立 NestJS 应用程序示例如下:

async function bootstrap() { const app = await NestFactory.createApplicationContext(AppModule, { logger: false, }); return app.close(); } void bootstrap();

接下来,您可以将 MCP 服务器与 MCP Stdio 客户端一起使用(参见示例),或者在构建项目后,您可以使用以下 MCP 客户端配置:

{ "mcpServers": { "greeting": { "command": "node", "args": [ "<path to dist js file>", ] } } }

API 端点

HTTP+SSE 传输公开两个端点:

  • GET /sse :SSE 连接端点(如果配置,则受保护)

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

可流式传输的 HTTP 传输公开以下端点:

  • POST /mcp :所有 MCP 操作(工具执行、资源访问等)的主端点。在状态模式下,此端点用于创建并维护会话。

  • GET /mcp :建立服务器发送事件 (SSE) 流,用于实时更新和进度通知。仅在状态模式下可用。

  • DELETE /mcp :终止 MCP 会话。仅在状态模式下可用。

尖端

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

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

验证

您可以使用标准 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 相同。

操场

playground目录包含快速测试 MCP 和@rekog/mcp-nest功能的示例。更多详细信息,请参阅playground/README.md

配置

McpModule.forRoot()方法接受一个McpOptions对象来配置服务器。可用的选项如下:

选项

描述

默认

name

**必填项。**您的 MCP 服务器的名称。

-

version

**必填项。**您的 MCP 服务器版本。

-

capabilities

可选的 MCP 服务器功能可供宣传。请参阅

@modelcontextprotocol/sdk

undefined

instructions

客户端如何与服务器交互的可选说明。

undefined

transport

指定要启用的传输类型。

[McpTransportType.SSE, McpTransportType.STREAMABLE_HTTP, McpTransportType.STDIO]

sseEndpoint

SSE 连接的端点路径(与

SSE

传输一起使用)。

'sse'

messagesEndpoint

发送消息的端点路径(与

SSE

传输一起使用)。

'messages'

mcpEndpoint

MCP 操作的基本端点路径(与

STREAMABLE_HTTP

传输一起使用)。

'mcp'

globalApiPrefix

所有 MCP 端点的全局前缀。在集成到现有应用程序时非常有用。

''

guards

一组 NestJS Guards,应用于 MCP 端点进行身份验证/授权。

[]

decorators

应用于生成的 MCP 控制器的 NestJS 类装饰器数组。

[]

sse

特定于

SSE

传输的配置。

{ pingEnabled: true, pingIntervalMs: 30000 }

sse.pingEnabled

是否启用定期 SSE ping 消息来保持连接处于活动状态。

true

sse.pingIntervalMs

发送 SSE ping 消息的间隔(以毫秒为单位)。

30000

streamableHttp

特定于

STREAMABLE_HTTP

传输的配置。

{ enableJsonResponse: true, sessionIdGenerator: undefined, statelessMode: true }

streamableHttp.enableJsonResponse

如果为

true

,则允许

/mcp

端点对非流式请求(如

listTools

)返回 JSON 响应。

true

streamableHttp.sessionIdGenerator

在有状态模式下运行时生成唯一会话 ID 的函数。当

statelessMode

false

时,此函数为必需。

undefined

streamableHttp.statelessMode

如果为

true

,则

STREAMABLE_HTTP

传输无状态运行(无会话)。如果为

false

,则传输有状态运行,需要

sessionIdGenerator

true

-
security - not tested
A
license - permissive license
-
quality - not tested

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/rekog-labs/MCP-Nest'

If you have feedback or need assistance with the MCP directory API, please join our Discord server