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)**を使用して、NestJS アプリケーションから AI 用のツール、リソース、プロンプトを簡単に公開できる NestJS モジュールです。

@rekog/mcp-nest 、MCP サーバーのセットアップに伴う複雑な作業を処理します。NestJS で馴染みのある方法でツール、リソース、プロンプトを定義し、依存性注入の力を最大限に活用して既存のサービスを利用できます。

特徴

  • 🚀 HTTP+SSE とストリーミング可能な HTTP トランスポート
  • 🔍 自動toolresourceprompt検出と登録
  • 💯 Zodベースのリクエスト検証
  • 📊 進捗通知
  • 🔒 ガードベースの認証
  • ⏱️ 長時間の接続を維持するための自動 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接続の長時間維持を可能にする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