nestjs-mcp-server
A production-ready NestJS backend template with built-in MCP server enabling AI agents to query your data via standardized protocol, featuring RAG pipeline, semantic search, and comprehensive developer tooling.
README
NestJS MCP Server Template
<div align="center">
Production-ready NestJS boilerplate with Model Context Protocol (MCP) server, RAG capabilities, and comprehensive developer tooling
Features โข Quick Start โข Documentation โข License
</div>
๐ Overview
A comprehensive, production-ready NestJS template that combines modern backend architecture with AI capabilities through the Model Context Protocol (MCP). Perfect for building intelligent applications, LMS platforms, content management systems, or any project requiring semantic search and AI integration.
Note: This template extends ultimate-nestjs-boilerplate by @niraj-khatiwada with MCP server, RAG pipeline, and AI capabilities. All credits for the excellent foundation go to the original author.
What Makes This Different?
- ๐ค Built-in MCP Server: Expose your data to AI agents with standardized protocol
- ๐ RAG Pipeline: Semantic search with pgvector and local embeddings (no API costs)
- ๐ Modern Auth: Better Auth with support for OAuth, 2FA, magic links, and more
- โก High Performance: Fastify adapter (2x faster than Express)
- ๐ฏ Production Ready: Docker, monitoring, graceful shutdown, health checks
- ๐ ๏ธ Developer Experience: Swagger, GraphQL playground, hot reload, Bull Board UI
โจ Features
Core Framework
- โ NestJS with Fastify adapter for high performance
- โ TypeScript for type safety and better DX
- โ PostgreSQL with TypeORM for robust data management
- โ Redis for caching and queue management
Authentication & Security
- โ
Better Auth: Complete auth solution supporting:
- Email/Password, OAuth, Magic Links, Passkeys
- Two-Factor Authentication (2FA)
- Role-based access control (RBAC)
- Session management
- โ API Key Management: Secure programmatic access with SHA-256 hashing
- โ Rate Limiting: Redis-backed request throttling
- โ Input Validation: class-validator with custom decorators
AI & Search Capabilities
- โ MCP Server: Model Context Protocol implementation for AI agents
- โ RAG Pipeline: Retrieval-Augmented Generation with semantic search
- โ pgvector: PostgreSQL extension for vector similarity search
- โ Local Embeddings: Hugging Face Transformers (no API costs)
- โ Content Chunking: Intelligent text splitting for better search accuracy
API Protocols
- โ REST API: Versioned endpoints with Swagger documentation
- โ GraphQL API: Apollo Server with type-safe schema
- โ WebSocket: Socket.io with Redis adapter for clustering
Background Processing
- โ BullMQ: Redis-based job queue with retry logic
- โ Worker Process: Dedicated worker for heavy computations
- โ Bull Board: Web UI for monitoring jobs and queues
Email System
- โ React Email: Beautiful, responsive email templates
- โ MailPit: Local SMTP server for testing
- โ Auto-compilation: TSX to HTML at build time
Developer Tools
- โ Swagger UI: Interactive API documentation
- โ OpenAPI Codegen: Auto-generate frontend API clients
- โ Dependency Graph: Visualize module dependencies
- โ ERD Generator: Database schema visualization
- โ Hot Reload: Fast development iteration
DevOps & Monitoring
- โ Docker: Dev and prod configurations with docker-compose
- โ Prometheus + Grafana: Optional monitoring dashboards
- โ Pino Logging: Structured JSON logs
- โ Health Checks: Kubernetes-ready endpoints
- โ Graceful Shutdown: Zero downtime deployments
- โ GitHub Actions: CI/CD pipeline included
Code Quality
- โ ESLint + Prettier: Code formatting and linting
- โ Husky + Commitlint: Git hooks for quality enforcement
- โ Jest: Unit and E2E testing
- โ SWC: Fast compilation (faster than Webpack)
Other Features
- โ i18n: Internationalization support
- โ File Uploads: Local and AWS S3 support
- โ Pagination: Offset and cursor-based
- โ Sentry Integration: Error tracking (ready to configure)
- โ pnpm: Fast, disk-efficient package manager
๐ฏ Use Cases
This template is perfect for:
- ๐ Learning Management Systems (LMS): Course content with semantic search
- ๐ค AI-Powered Applications: Chat agents, document search, RAG systems
- ๐ Content Management: Blog, documentation, knowledge bases
- ๐ข SaaS Platforms: Multi-tenant apps with auth and API keys
- ๐ง Internal Tools: Admin dashboards, background job processing
- ๐ Startup MVPs: Production-ready foundation to move fast
๐ Quick Start
Prerequisites
- Node.js 18+ or Bun
- Docker & Docker Compose
- pnpm (recommended) or npm
1. Use This Template
Click the "Use this template" button on GitHub or:
git clone https://github.com/branch42-team/nestjs-mcp-server.git my-project
cd my-project
pnpm install
2. Environment Setup
cp .env.example .env
cp .env.docker.example .env.docker
Edit .env files with your configuration.
3. Start Development Environment
# Start all services (PostgreSQL, Redis, MailPit, etc.)
pnpm docker:dev:up
# Run database migrations
docker exec -it nestjs-server sh
pnpm migration:up
exit
4. Access Your Services
- API Swagger: http://localhost:3000/swagger
- GraphQL Playground: http://localhost:3000/graphql
- Bull Board (Queue UI): http://localhost:3000/bullboard
- MailPit (Email Testing): http://localhost:18025
- Prometheus (Monitoring): http://localhost:9090 (if enabled)
- Grafana (Dashboards): http://localhost:3001 (if enabled)
5. Create Your First User
Visit Swagger UI and use:
POST /api/auth/sign-up/emailto create an accountPOST /api/auth/sign-in/emailto login
๐ Documentation
Core Features
๐ Better Auth
Modern authentication framework handling all auth patterns out of the box:
- Email/Password: Traditional auth with secure password hashing
- OAuth: Google, GitHub, and more (easily extensible)
- Magic Links: Passwordless authentication
- Passkeys: WebAuthn support for biometric auth
- Two-Factor Authentication: TOTP-based 2FA
- Role-Based Access Control: Admin/User roles with guards
- Session Management: Redis-backed sessions with auto-refresh
Learn more about Better Auth โ
๐ค MCP Server
Model Context Protocol server implementation enabling AI agents to query your data:
Key Features:
- 6 pre-built tools for course/content management
- API key authentication with user-scoped permissions
- Enrollment-based authorization (example use case)
- Semantic search with RAG pipeline
- Interactive CLI client included
Quick Example:
- Create API key via Swagger:
POST /api/v1/user/api-keys - Setup CLI:
cd mcp-client echo "MCP_API_KEY=your-key" > .env pnpm install && pnpm dev - Query naturally:
> list courses > find lessons about variables > search typescript
Documentation:
- MCP Server Guide - Complete implementation details
- API Key Management - Security best practices
- CLI Client - Interactive terminal guide
๐ API Key Management
Secure programmatic access for integrations and MCP clients:
Endpoints:
POST /api/v1/user/api-keys- Create new keyGET /api/v1/user/api-keys- List your keysGET /api/v1/user/api-keys/:id- Get key detailsDELETE /api/v1/user/api-keys/:id- Revoke key
Security Features:
- SHA-256 hashed storage (raw key shown once)
- Optional expiration dates
- Usage tracking (
lastUsedAt) - Instant revocation
- User-scoped permissions
๐ Automatic Frontend API Generation
Generate type-safe API clients from your Swagger spec:
# On your frontend project
pnpm codegen
This auto-generates all API calls with TanStack Query hooks. Import and use immediately:
import { useGetUserProfile } from '@/api/generated';
function Profile() {
const { data, isLoading } = useGetUserProfile();
// Fully typed, with caching, refetching, etc.
}

๐จ Server & Database Monitoring
Optional Prometheus + Grafana setup for production monitoring:
Enable monitoring:
# In .env
COMPOSE_PROFILES=monitoring
Metrics tracked:
- HTTP request duration/rate
- Database connection pool stats
- Queue job latency and throughput
- Memory and CPU usage
- Custom business metrics
Dashboards:
Server Monitoring:

Database Monitoring:

๐ฌ Email Management
React Email for beautiful, testable email templates:
- Design emails in React with type safety
- Preview all templates in local web UI
- Automatic compilation to HTML at build time
- Spam, accessibility, and responsiveness checks
Commands:
# Preview templates in browser
pnpm email:dev
# Auto-compiled during build (handled automatically)
pnpm email:build
MailPit for local testing:
- SMTP server runs automatically in dev mode
- Web UI at http://localhost:18025
- Catch all outgoing emails
- No real emails sent during development

๐ณ Docker Commands
Development
# Start all services
pnpm docker:dev:up
# Stop all services
pnpm docker:dev:down
# View logs
docker logs nestjs-server -f
Production
# Build and start production containers
pnpm docker:prod:up
# Stop production containers
pnpm docker:prod:down
Deployment
# Quick deploy script
sh ./bin/deploy.sh
# Or use GitHub Actions
# Workflow: .github/workflows/main.yml
๐ ๏ธ Development Tools
Dependency Graph
Visualize module dependencies and detect circular references:
# Requires Graphviz: brew install graphviz
# All dependencies
pnpm graph:app
# Only circular dependencies
pnpm graph:circular

Database ERD
Generate entity relationship diagrams:
pnpm erd:generate

๐๏ธ Project Structure
.
โโโ src/
โ โโโ api/ # API modules (courses, users, etc.)
โ โโโ auth/ # Authentication (Better Auth integration)
โ โโโ mcp/ # MCP server implementation
โ โโโ config/ # Configuration modules
โ โโโ database/ # TypeORM setup and migrations
โ โโโ services/ # Shared services (embeddings, AWS, etc.)
โ โโโ worker/ # Background job processors
โ โโโ main.ts # Application entry point
โโโ mcp-client/ # Interactive CLI client for MCP
โโโ docker-compose.yml # Base Docker configuration
โโโ docker-compose.dev.yml # Development overrides
โโโ docker-compose.prod.yml # Production overrides
โโโ docs/ # Additional documentation
๐งช Testing
# Unit tests
pnpm test
# E2E tests
pnpm test:e2e
# Coverage
pnpm test:cov
# Watch mode
pnpm test:watch
๐ง Customization Guide
1. Remove Example Features
This template includes a course management system as an example. To adapt for your use case:
Remove course-related code:
# Delete course modules
rm -rf src/api/courses
# Remove from app.module.ts imports
# Update database migrations
Or keep and modify:
- Rename entities to match your domain
- Adjust the MCP tools in
src/mcp/tools/ - Update RAG pipeline in
src/api/courses/courses-rag.service.ts
2. Add Your Own Modules
# Generate new module
nest g module features/my-feature
nest g service features/my-feature
nest g controller features/my-feature
3. Configure Authentication
Add OAuth providers (edit src/auth/better-auth.service.ts):
plugins: [
oauth({
github: {
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
},
}),
],
4. Customize MCP Tools
Add your own tools in src/mcp/tools/:
export const myCustomTool: Tool = {
name: 'my_custom_tool',
description: 'Description for AI agents',
inputSchema: {
type: 'object',
properties: {
/* ... */
},
},
};
๐ฆ Tech Stack
| Category | Technology | Purpose |
|---|---|---|
| Runtime | Node.js + TypeScript | Server runtime with type safety |
| Framework | NestJS + Fastify | Enterprise architecture, 2x Express performance |
| Database | PostgreSQL 16 | ACID-compliant relational database |
| Vector Store | pgvector | Native Postgres vector extension |
| ORM | TypeORM | Mature ORM with migrations |
| Cache/Queue | Redis + BullMQ | In-memory cache and job queue |
| Auth | Better Auth | Modern authentication framework |
| API | REST + GraphQL + WebSocket | Multiple protocol support |
| Embeddings | Hugging Face Transformers | Local, cost-free embeddings |
| React Email + MailPit | Template management + testing | |
| Monitoring | Prometheus + Grafana | Metrics and dashboards |
| Logging | Pino | Structured JSON logging |
| Testing | Jest | Unit and E2E tests |
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
This template is built upon the excellent foundation of:
- ultimate-nestjs-boilerplate by @niraj-khatiwada - Advanced Nest.js boilerplate for scalable startups. This template extends the original boilerplate with MCP server, RAG pipeline, and AI capabilities.
Additional Credits
- NestJS - Progressive Node.js framework
- Better Auth - Modern authentication
- Model Context Protocol - AI agent protocol
- React Email - Email templates
- Hugging Face - ML models and embeddings
๐ Star History
If you find this template useful, please consider giving it a star โญ
<div align="center">
Built with โค๏ธ by Branch42 Team
Based on ultimate-nestjs-boilerplate by @niraj-khatiwada
Report Bug โข Request Feature
</div>
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.