NestJS MCP 服务器模块
NestJS 模块可使用**模型上下文协议 (MCP)**从 NestJS 应用程序轻松公开 AI 的工具、资源和提示。
使用@rekog/mcp-nest您可以按照 NestJS 中熟悉的方式定义工具、资源和提示,并充分利用依赖注入的全部功能,利用现有代码库构建复杂的企业级 MCP 服务器。
特征
🚀 支持所有运输类型:
可流式传输的 HTTP
HTTP+SSE
标准输出
🔍 自动
tool、resource和prompt发现和注册💯 基于 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对象来配置服务器。可用的选项如下:
选项 | 描述 | 默认 |
| **必填项。**您的 MCP 服务器的名称。 | - |
| **必填项。**您的 MCP 服务器版本。 | - |
| 可选的 MCP 服务器功能可供宣传。请参阅@modelcontextprotocol/sdk 。 |
|
| 客户端如何与服务器交互的可选说明。 |
|
| 指定要启用的传输类型。 |
|
| SSE 连接的端点路径(与 |
|
| 发送消息的端点路径(与 |
|
| MCP 操作的基本端点路径(与 |
|
| 所有 MCP 端点的全局前缀。在集成到现有应用程序时非常有用。 |
|
| 一组 NestJS Guards,应用于 MCP 端点进行身份验证/授权。 |
|
| 应用于生成的 MCP 控制器的 NestJS 类装饰器数组。 |
|
| 特定于 |
|
| 是否启用定期 SSE ping 消息来保持连接处于活动状态。 |
|
| 发送 SSE ping 消息的间隔(以毫秒为单位)。 |
|
| 特定于 |
|
| 如果为 |
|
| 在有状态模式下运行时生成唯一会话 ID 的函数。当 |
|
| 如果为 |
|
This server cannot be installed
Resources
Looking for Admin?
Admins can modify the Dockerfile, update the server description, and track usage metrics. If you are the server author, to access the admin panel.