Production-ready NestJS boilerplate with Model Context Protocol (MCP) server, RAG capabilities, and comprehensive developer tooling
Features β’ Quick Start β’ Documentation β’ License
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.
- π€ 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
- β 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
- β
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
- β 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
- β REST API: Versioned endpoints with Swagger documentation
- β GraphQL API: Apollo Server with type-safe schema
- β WebSocket: Socket.io with Redis adapter for clustering
- β BullMQ: Redis-based job queue with retry logic
- β Worker Process: Dedicated worker for heavy computations
- β Bull Board: Web UI for monitoring jobs and queues
- β React Email: Beautiful, responsive email templates
- β MailPit: Local SMTP server for testing
- β Auto-compilation: TSX to HTML at build time
- β 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
- β 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
- β ESLint + Prettier: Code formatting and linting
- β Husky + Commitlint: Git hooks for quality enforcement
- β Jest: Unit and E2E testing
- β SWC: Fast compilation (faster than Webpack)
- β 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
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
- Node.js 18+ or Bun
- Docker & Docker Compose
- pnpm (recommended) or npm
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 installcp .env.example .env
cp .env.docker.example .env.dockerEdit .env files with your configuration.
# Start all services (PostgreSQL, Redis, MailPit, etc.)
pnpm docker:dev:up
# Run database migrations
docker exec -it nestjs-server sh
pnpm migration:up
exit- 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)
Visit Swagger UI and use:
POST /api/auth/sign-up/emailto create an accountPOST /api/auth/sign-in/emailto login
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 β
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
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
Generate type-safe API clients from your Swagger spec:
# On your frontend project
pnpm codegenThis 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.
}Optional Prometheus + Grafana setup for production monitoring:
Enable monitoring:
# In .env
COMPOSE_PROFILES=monitoringMetrics tracked:
- HTTP request duration/rate
- Database connection pool stats
- Queue job latency and throughput
- Memory and CPU usage
- Custom business metrics
Dashboards:
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:buildMailPit 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
# Start all services
pnpm docker:dev:up
# Stop all services
pnpm docker:dev:down
# View logs
docker logs nestjs-server -f# Build and start production containers
pnpm docker:prod:up
# Stop production containers
pnpm docker:prod:down# Quick deploy script
sh ./bin/deploy.sh
# Or use GitHub Actions
# Workflow: .github/workflows/main.ymlVisualize module dependencies and detect circular references:
# Requires Graphviz: brew install graphviz
# All dependencies
pnpm graph:app
# Only circular dependencies
pnpm graph:circularGenerate entity relationship diagrams:
pnpm erd:generate.
βββ 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
# Unit tests
pnpm test
# E2E tests
pnpm test:e2e
# Coverage
pnpm test:cov
# Watch mode
pnpm test:watchThis 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 migrationsOr 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
# Generate new module
nest g module features/my-feature
nest g service features/my-feature
nest g controller features/my-featureAdd OAuth providers (edit src/auth/better-auth.service.ts):
plugins: [
oauth({
github: {
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
},
}),
],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: {
/* ... */
},
},
};| 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 |
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
This project is licensed under the MIT License - see the LICENSE file for details.
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.
- 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
If you find this template useful, please consider giving it a star β
Built with β€οΈ by Branch42 Team
Based on ultimate-nestjs-boilerplate by @niraj-khatiwada





