Sponsored by Deepsite.site

NestJS MCP Server Module

Created By
rekog-labs8 months ago
A NestJS module to effortlessly create Model Context Protocol (MCP) servers for exposing AI tools, resources, and prompts.
Content

NestJS MCP Server Module

CI Code Coverage NPM Version NPM Downloads NPM License

A NestJS module to effortlessly expose tools, resources, and prompts for AI, from your NestJS applications using the Model Context Protocol (MCP).

With @rekog/mcp-nest you define tools, resources, and prompts in a way that's familiar in NestJS and leverage the full power of dependency injection to utilize your existing codebase in building complex enterprise ready MCP servers.

Features

  • 🚀 Support for all Transport Types:
    • Streamable HTTP
    • HTTP+SSE
    • STDIO
  • 🔍 Automatic tool, resource, and prompt discovery and registration
  • 💯 Zod-based tool call validation
  • 📊 Progress notifications
  • 🔒 Guard-based authentication
  • 🌐 Access to HTTP Request information within MCP Resources (Tools, Resources, Prompts)

Installation

npm install @rekog/mcp-nest @modelcontextprotocol/sdk zod

Quick Start

1. Import Module

// 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. Define Tools and Resource

// 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',
        },
      ],
    };
  }
}

You are done!

TIP

The above example shows how HTTP Request headers are accessed within MCP Tools. This is useful for identifying users, adding client-specific logic, and many other use cases. For more examples, see the Authentication Tests.

Quick Start for STDIO

The main difference is that you need to provide the transport option when importing the module.

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

The rest is the same, you can define tools, resources, and prompts as usual. An example of a standalone NestJS application using the STDIO transport is the following:

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

void bootstrap();

Next, you can use the MCP server with an MCP Stdio Client (see example), or after building your project you can use it with the following MCP Client configuration:

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

API Endpoints

HTTP+SSE transport exposes two endpoints:

  • GET /sse: SSE connection endpoint (Protected by guards if configured)
  • POST /messages: Tool execution endpoint (Protected by guards if configured)

Streamable HTTP transport exposes the following endpoints:

  • POST /mcp: Main endpoint for all MCP operations (tool execution, resource access, etc.). In stateful mode, this creates and maintains sessions.
  • GET /mcp: Establishes Server-Sent Events (SSE) streams for real-time updates and progress notifications. Only available in stateful mode.
  • DELETE /mcp: Terminates MCP sessions. Only available in stateful mode.

Tips

It's possible to use the module with global prefix, but the recommended way is to exclude those endpoints with:

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

Authentication

You can secure your MCP endpoints using standard NestJS Guards.

1. Create a Guard

Implement the CanActivate interface. The guard should handle request validation (e.g., checking JWTs, API keys) and optionally attach user information to the request object.

Nothing special, check the NestJS documentation for more details.

2. Apply the Guard

Pass your guard(s) to the McpModule.forRoot configuration. The guard(s) will be applied to both the /sse and /messages endpoints.

// 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 {}

That's it! The rest is the same as NestJS Guards.

Playground

The playground directory contains examples to quickly test MCP and @rekog/mcp-nest features. Refer to the playground/README.md for more details.

Configuration

The McpModule.forRoot() method accepts an McpOptions object to configure the server. Here are the available options:

OptionDescriptionDefault
nameRequired. The name of your MCP server.-
versionRequired. The version of your MCP server.-
capabilitiesOptional MCP server capabilities to advertise. See @modelcontextprotocol/sdk.undefined
instructionsOptional instructions for the client on how to interact with the server.undefined
transportSpecifies the transport type(s) to enable.[McpTransportType.SSE, McpTransportType.STREAMABLE_HTTP, McpTransportType.STDIO]
sseEndpointThe endpoint path for the SSE connection (used with SSE transport).'sse'
messagesEndpointThe endpoint path for sending messages (used with SSE transport).'messages'
mcpEndpointThe base endpoint path for MCP operations (used with STREAMABLE_HTTP transport).'mcp'
globalApiPrefixA global prefix for all MCP endpoints. Useful if integrating into an existing application.''
guardsAn array of NestJS Guards to apply to the MCP endpoints for authentication/authorization.[]
decoratorsAn array of NestJS Class Decorators to apply to the generated MCP controllers.[]
sseConfiguration specific to the SSE transport.{ pingEnabled: true, pingIntervalMs: 30000 }
sse.pingEnabledWhether to enable periodic SSE ping messages to keep the connection alive.true
sse.pingIntervalMsThe interval (in milliseconds) for sending SSE ping messages.30000
streamableHttpConfiguration specific to the STREAMABLE_HTTP transport.{ enableJsonResponse: true, sessionIdGenerator: undefined, statelessMode: true }
streamableHttp.enableJsonResponseIf true, allows the /mcp endpoint to return JSON responses for non-streaming requests (like listTools).true
streamableHttp.sessionIdGeneratorA function to generate unique session IDs when running in stateful mode. Required if statelessMode is false.undefined
streamableHttp.statelessModeIf true, the STREAMABLE_HTTP transport operates statelessly (no sessions). If false, it operates statefully, requiring a sessionIdGenerator.true
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
DeepChatYour AI Partner on Desktop
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Playwright McpPlaywright MCP server
WindsurfThe new purpose-built IDE to harness magic
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Tavily Mcp
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
ChatWiseThe second fastest AI chatbot™
Serper MCP ServerA Serper MCP Server
CursorThe AI Code Editor
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Amap Maps高德地图官方 MCP Server