Build Model Context Protocol servers with NestJS. Expose tools, resources, prompts, and completions to AI clients through decorators, with built-in auth, resilience, middleware, and multiple transport options.
npm install @nest-mcp/server @nest-mcp/common
# peer dependencies
npm install @modelcontextprotocol/sdk @nestjs/common @nestjs/core reflect-metadata rxjs zodOr with pnpm:
pnpm add @nest-mcp/server @nest-mcp/common
pnpm add @modelcontextprotocol/sdk @nestjs/common @nestjs/core reflect-metadata rxjs zodimport { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { McpModule } from '@nest-mcp/server';
import { McpTransportType } from '@nest-mcp/common';
import { ToolsService } from './tools.service';
@Module({
imports: [
McpModule.forRoot({
name: 'my-mcp-server',
version: '1.0.0',
transport: McpTransportType.STREAMABLE_HTTP,
}),
],
providers: [ToolsService],
})
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();// tools.service.ts
import { Injectable } from '@nestjs/common';
import { Tool } from '@nest-mcp/server';
import { z } from 'zod';
@Injectable()
export class ToolsService {
@Tool({
name: 'greet',
description: 'Say hello',
parameters: z.object({ name: z.string() }),
})
async greet(args: { name: string }) {
return `Hello, ${args.name}!`;
}
}- Decorator-driven --
@Tool,@Resource,@ResourceTemplate,@Prompt,@Completion - Multiple transports -- Streamable HTTP, SSE, and STDIO
- OAuth 2.1 auth -- Built-in JWT, PKCE, dynamic client registration
- Resilience -- Rate limiting, circuit breaker, retry, timeout
- Middleware -- Global and per-tool request pipeline
- Dynamic registration -- Add/remove tools, resources, prompts at runtime
- Session management -- Per-session state, resource subscriptions, task tracking
- Testing utilities --
createMcpTestAppandmockMcpContext
| Topic | Description |
|---|---|
| Getting Started | Minimal working example |
| Module | McpModule.forRoot / forRootAsync / forFeature |
| Decorators | @Tool, @Resource, @ResourceTemplate, @Prompt, @Completion |
| Auth Decorators | @Public, @Scopes, @Roles, @Guards |
| Resilience Decorators | @RateLimit, @Retry, @CircuitBreaker, @Timeout |
| Transports | SSE, Streamable HTTP, STDIO |
| Auth | McpAuthModule, OAuth resource server, verifiers, guards |
| Recipe: better-auth | better-auth mcp plugin as the authorization server |
| Resilience | Rate limiter, circuit breaker, retry services |
| Middleware | @UseMiddleware, MiddlewareService |
| Dynamic Builders | McpToolBuilder, McpResourceBuilder, McpPromptBuilder |
| Execution Pipeline | Request lifecycle |
| Sessions | SessionManager, ResourceSubscriptionManager, TaskManager |
| Testing | createMcpTestApp, mockMcpContext |
@nest-mcp/common-- Shared interfaces and utilities@nest-mcp/client-- MCP client for NestJS@nest-mcp/gateway-- MCP gateway/aggregator