@hmake98/nest-mcp
v1.0.7
Published
NestJS library for integrating Model Context Protocol (MCP) server capabilities
Downloads
865
Maintainers
Readme
nest-mcp
A NestJS library for integrating Model Context Protocol (MCP) server capabilities into existing or new NestJS applications.
Features
- 🚀 Easy Integration — Add MCP server capabilities to any NestJS app with minimal configuration
- 🎯 Decorator-Based API — Use
@Prompt,@Resource, and@Tooldecorators to expose MCP primitives - 🔌 Multiple Transports — WebSocket (
ws) and Redis pub/sub transports - 💉 Dependency Injection — Full support for NestJS DI; handlers are discovered automatically via
DiscoveryService - 🛝 Built-in Playground — Interactive UI served at
/mcp/playgroundfor testing all registered prompts, resources, and tools - 📝 TypeScript — Written in strict TypeScript with full type safety
Installation
npm install nest-mcpPeer Dependencies
npm install @nestjs/common @nestjs/core rxjs reflect-metadataNode.js ≥ 20.0.0 is required.
Quick Start
1. Import the Module
import { Module } from '@nestjs/common';
import { McpModule } from 'nest-mcp';
@Module({
imports: [
McpModule.register({
transport: 'websocket',
serverName: 'my-mcp-server',
serverVersion: '1.0.0',
websocket: {
port: 3001,
host: 'localhost',
},
}),
],
})
export class AppModule {}2. Create MCP Handlers
Decorate any @Injectable() provider with @Prompt, @Resource, or @Tool. The library discovers them automatically at startup.
import { Injectable } from '@nestjs/common';
import {
Prompt,
PromptParam,
Resource,
ResourceParam,
Tool,
ToolParam,
} from 'nest-mcp';
@Injectable()
export class McpHandlersService {
// --- Prompt ---
@Prompt({ name: 'greeting', description: 'Generates a personalised greeting' })
greet(
@PromptParam('name', { description: 'User name', required: true })
name: string,
): string {
return `Hello, ${name}!`;
}
// --- Resource ---
@Resource({
uri: 'config://app-settings',
name: 'Application Settings',
description: 'Current application configuration',
mimeType: 'application/json',
})
getAppSettings(): string {
return JSON.stringify({ version: '1.0.0', environment: process.env.NODE_ENV });
}
// --- Tool ---
@Tool({ name: 'add', description: 'Adds two numbers' })
add(
@ToolParam('a', { description: 'First number', type: 'number', required: true })
a: number,
@ToolParam('b', { description: 'Second number', type: 'number', required: true })
b: number,
): number {
return a + b;
}
}3. Register the Provider
@Module({
imports: [McpModule.register({ transport: 'websocket', websocket: { port: 3001 } })],
providers: [McpHandlersService],
})
export class AppModule {}4. Start Your Application
npm run startThe MCP server is now reachable at ws://localhost:3001 and the playground UI is available at http://localhost:3000/mcp/playground.
Configuration
McpModule.register(options)
Synchronous registration.
McpModule.register({
transport: 'websocket', // required: 'websocket' | 'redis'
serverName: 'my-server', // optional, default: 'nest-mcp-server'
serverVersion: '1.0.0', // optional, default: '1.0.0'
enablePlayground: true, // optional, default: true
websocket: {
port: 3001, // optional, default: 3001
host: 'localhost', // optional, default: 'localhost'
path: '/mcp', // optional
},
});McpModule.registerAsync(options)
Asynchronous registration — useful with ConfigService or any other async factory.
import { ConfigModule, ConfigService } from '@nestjs/config';
McpModule.registerAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
transport: configService.get<'websocket' | 'redis'>('MCP_TRANSPORT'),
serverName: configService.get('MCP_SERVER_NAME'),
websocket: {
port: configService.get<number>('MCP_WS_PORT'),
},
}),
inject: [ConfigService],
});registerAsync also accepts useClass and useExisting via the McpModuleOptionsFactory interface.
WebSocket Transport Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| port | number | 3001 | Port the WebSocket server listens on |
| host | string | 'localhost' | Host to bind to |
| path | string | — | Optional WebSocket path |
Redis Transport Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| host | string | — | Redis host |
| port | number | — | Redis port |
| password | string | — | Redis password |
| db | number | — | Redis database index |
| channelPrefix | string | — | Prefix for pub/sub channel names |
Playground UI
The playground is enabled by default and mounted at /mcp/playground using a raw Express route that bypasses NestJS global prefixes, guards, and middleware. It supports interactive testing of all registered prompts, resources, and tools.
To disable it:
McpModule.register({
transport: 'websocket',
enablePlayground: false,
websocket: { port: 3001 },
});Note: The playground only works with the default Express HTTP adapter (
@nestjs/platform-express). Fastify is not supported.
Using with Helmet
If your NestJS application uses Helmet for security headers (e.g., Content Security Policy), you must configure it to skip CSP for playground routes. The playground sets its own permissive CSP headers.
import helmet from 'helmet';
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:'],
},
// Skip CSP for playground routes - they have their own CSP
skip: (req) => req.path.startsWith('/mcp/playground'),
},
}),
);This ensures:
- ✅ Playground routes use permissive CSP for full functionality
- ✅ All other routes remain protected by Helmet's security headers
- ✅ No CSP conflicts or console errors
API Reference
Decorators
@Prompt(options: PromptOptions)
Marks a method as an MCP prompt handler.
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| name | string | ✅ | Unique prompt name |
| description | string | — | Human-readable description |
@PromptParam(name: string, options?: PromptParamOptions)
Decorates a parameter within a @Prompt method.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| description | string | — | Parameter description |
| required | boolean | true | Whether the parameter is required |
@Resource(options: ResourceOptions)
Marks a method as an MCP resource handler.
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| uri | string | ✅ | Unique resource URI (e.g. config://settings) |
| name | string | — | Resource display name |
| description | string | — | Human-readable description |
| mimeType | string | — | MIME type of the returned content |
@ResourceParam(name: string, options?: ResourceParamOptions)
Decorates a parameter within a @Resource method.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| description | string | — | Parameter description |
| required | boolean | true | Whether the parameter is required |
@Tool(options: ToolOptions)
Marks a method as an MCP tool handler.
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| name | string | ✅ | Unique tool name |
| description | string | — | Human-readable description |
| inputSchema | Record<string, unknown> | — | Custom JSON schema; auto-generated from @ToolParam if omitted |
@ToolParam(name: string, options?: ToolParamOptions)
Decorates a parameter within a @Tool method.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| description | string | — | Parameter description |
| type | 'string' \| 'number' \| 'boolean' \| 'object' \| 'array' | 'string' | Parameter type used in the generated JSON schema |
| required | boolean | true | Whether the parameter is required |
McpService
Exported from nest-mcp and injectable in any provider.
| Method | Return type | Description |
|--------|-------------|-------------|
| getServer() | Server \| undefined | Returns the underlying @modelcontextprotocol/sdk Server instance |
| listPrompts() | { prompts: PromptInfo[] } | Lists all registered prompts with their argument schemas |
| listResources() | { resources: ResourceInfo[] } | Lists all registered resources |
| listTools() | { tools: ToolInfo[] } | Lists all registered tools with their input schemas |
| getPrompt(name, args?) | Promise<{ messages: [...] }> | Executes a prompt handler and returns the MCP message format |
| readResource(uri, args?) | Promise<{ contents: [...] }> | Reads a resource and returns the MCP contents format |
| callTool(name, args?) | Promise<{ content: [...] }> | Calls a tool and returns the MCP content format |
Provider Discovery
The library uses NestJS's DiscoveryService to scan all registered providers at module init. Any @Injectable() class that has methods decorated with @Prompt, @Resource, or @Tool is picked up automatically — there is no manual registration step.
MCP Protocol Primitives
| Primitive | Decorator | Purpose |
|-----------|-----------|---------|
| Prompt | @Prompt | Templated messages/instructions for an LLM |
| Resource | @Resource | Data sources the client can read |
| Tool | @Tool | Functions the client can execute |
See the MCP specification for the full protocol details.
Development
Build
npm run buildTest
# Run all tests with coverage
npm test
# Watch mode
npm run test:watch
# Coverage report only
npm run test:covLint
# Check
npm run lint
# Auto-fix
npm run lint:fixFormat
# Check
npm run format:check
# Fix
npm run formatAPI Docs
npm run docsContributing
Contributions are welcome. Please read CONTRIBUTING.md and open a pull request against main.
Commit Convention
This project follows Conventional Commits:
type(scope): subjectAllowed types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
Allowed scopes: module, service, decorator, transport, playground, config, deps, release
License
MIT — see LICENSE.
Repository
Acknowledgments
- Built on NestJS
- Implements Model Context Protocol via @modelcontextprotocol/sdk
- WebSocket transport powered by ws
- Redis transport powered by redis
