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 서버 모듈

MCP(Model Context Protocol)를 사용하여 NestJS 애플리케이션에서 AI를 위한 도구, 리소스 및 프롬프트를 손쉽게 노출할 수 있는 NestJS 모듈입니다.

@rekog/mcp-nest MCP 서버 설정의 복잡성을 해결합니다. NestJS에 익숙한 방식으로 도구, 리소스 및 프롬프트를 정의하고, 의존성 주입의 모든 기능을 활용하여 기존 서비스를 활용할 수 있습니다.

특징

  • 🚀 HTTP+SSE 및 스트리밍 가능한 HTTP 전송
  • 🔍 자동 tool , resource , prompt 검색 및 등록
  • 💯 Zod 기반 요청 검증
  • 📊 진행 상황 알림
  • 🔒 가드 기반 인증
  • ⏱️ 장시간 연결을 유지하기 위한 자동 SSE ping

설치

지엑스피1

빠른 시작

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 연결을 장기적으로 유지하는 데 도움이 되는 SSE ping 서비스가 포함되어 있습니다. 이는 특히 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

서비스가 Server-Sent Events 전송을 통해 MCP 서버로 노출될 수 있도록 하는 NestJS 모듈로, 클라이언트가 도구를 검색하고 실행할 수 있도록 돕습니다.

  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