MCP服务器模块

一个用于创建支持服务器发送事件(SSE)传输的模型上下文协议(MCP)服务器的NestJS模块。

  • by rahosung
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 rahosung/mcp_server

使用说明

NestJS MCP服务器模块

NestJS模块,用于创建具有服务器发送事件(SSE)传输的MCP(模型上下文协议)服务器。

特性

  • 🚀 用于流媒体和工具执行的SSE传输
  • 🔍 自动 tool 和 resource 发现和注册
  • 💯 基于Zod的请求验证
  • 📊 进度通知
  • 🔒 基于警卫的身份验证

安装

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, 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相同。