@cazvid-ai/nestjs-mcp
v0.4.1
Published
NestJS integration for declaring Model Context Protocol tools with decorators.
Readme
@cazvid-ai/nestjs-mcp
NestJS utilities for exposing Model Context Protocol tools without hand-rolling a server in every project. Decorate any injectable with @McpTool(), import McpModule, and you get a streamable HTTP endpoint backed by the official MCP TypeScript SDK.
🚧 This package is pre-1.0. Expect breaking changes while the API stabilizes and please send feedback.
Installation
- Node.js ≥ 18.18 with ES module support (
"type": "module"in yourpackage.json). - Nest app using
@nestjs/platform-express. - Peer dependencies:
@nestjs/common,@nestjs/core,reflect-metadata,zod, and@modelcontextprotocol/sdk.
# Stable release
pnpm add @cazvid-ai/nestjs-mcp @modelcontextprotocol/sdk zod reflect-metadata
# Preview channel (optional)
pnpm add @cazvid-ai/nestjs-mcp@next @modelcontextprotocol/sdk zod reflect-metadataEnsure your tsconfig.json enables decorators and NodeNext module resolution (see docs/getting-started.md for the full example).
Quick Start
// app.module.ts
import { Module } from '@nestjs/common';
import { McpModule } from '@cazvid-ai/nestjs-mcp';
import { DataTools } from './data.tools.js';
@Module({
imports: [
McpModule.forRoot({
auth: { mode: 'service', key: process.env.MCP_SERVICE_KEY! },
path: '/mcp', // optional, defaults to '/mcp'
}),
],
providers: [DataTools],
})
export class AppModule {}// data.tools.ts
import { Injectable } from '@nestjs/common';
import { McpTool, McpExecutionContext } from '@cazvid-ai/nestjs-mcp';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
const PingInput = z.object({ message: z.string().default('ping') });
const PingOutput = z.object({
reply: z.string(),
});
@Injectable()
export class DataTools {
@McpTool({
name: 'ping',
description: 'Simple health check',
inputSchema: PingInput,
outputSchema: PingOutput,
})
async ping(
input: z.infer<typeof PingInput>,
ctx: McpExecutionContext
): Promise<CallToolResult> {
const ua = ctx.headers['user-agent'];
const base = input.message === 'ping' ? 'pong' : `echo:${input.message}`;
const reply = typeof ua === 'string' ? `${base} (from ${ua})` : base;
return {
structuredContent: { reply },
content: [
{
type: 'text',
text: reply,
},
],
};
}
}// main.ts
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();Need separate endpoints with different auth or tool groups? Import the module once with forRoot() and use McpModule.register() for each additional route:
@Module({
imports: [
McpModule.forRoot({
auth: { mode: 'service', key: process.env.MCP_SERVICE_KEY! },
path: '/mcp',
groups: ['public'],
}),
McpModule.register({
auth: { mode: 'bearer', verifier: AdminBearerVerifier },
path: '/mcp-admin',
groups: ['admin'],
}),
],
providers: [AdminBearerVerifier],
})
export class AppModule {}Heads up: Router registration is enabled by default. Only set
registerRouter: falseif you intend to mount the controller manually—the module will otherwise fall back to mounting at/mcpwhen no explicit path is provided.
Async callers can return path or registerRouter from forRootAsync()/registerAsync() factories and the router will align once the factory resolves.
By default the HTTP controller is mounted at /mcp. Override the path option or provide an array when you need additional aliases. Run the app and probe the endpoint:
PORT=3000 MCP_SERVICE_KEY=xyz pnpm start
curl -i -X POST http://localhost:3000/mcp \
-H 'content-type: application/json' \
-H 'x-api-key: xyz' \
--data '{"method":"ping","params":{"message":"ping"}}'If you configure
outputSchema, success results should return aCallToolResultwithstructuredContentthat matches the schema. Error results (isError: true) may omitstructuredContent; the server will pass the error through without validating it. Non-string outputs without a schema are JSON‑stringified into a text item, so prefer the structured MCP shape for production handlers.
Documentation
- docs/getting-started.md — installation prerequisites, TypeScript setup, and a full walkthrough.
- docs/authentication.md — service keys, bearer auth, and async configuration patterns.
- docs/module-options.md —
McpModuleOptions, tool grouping, multi-server setups, and observability hooks. - docs/tools-and-context.md —
@McpToolmetadata, request guards, execution context, and error handling. - docs/dev-experience.md — MCP Inspector usage plus the verification checklist.
Verification Checklist
Before submitting changes (or when picking up the repo), make sure the following commands succeed and fix implementations rather than muting tests:
pnpm lint
pnpm typecheck
pnpm testRoadmap
- Optional JWT/OAuth guard
- Schema-to-docs utilities
- More granular error mapping and logging helpers
License
MIT © Cazvid AI
