NestJS MongoDB MCP Server
A NestJS-based Model Context Protocol (MCP) server with Clean Architecture for MongoDB operations. This server allows AI assistants like Claude to interact with MongoDB databases through standardized MCP tools, resources, and prompts.
Features
- Clean Architecture: Full separation of concerns with Domain, Application, Infrastructure, and Presentation layers
- MCP Protocol Support: Complete implementation of MCP with tools, resources, and prompts
- MongoDB Integration: Full CRUD operations and aggregation support
- Dual Transport: STDIO mode for local Claude Desktop integration and HTTP/SSE for remote access
- Structured Logging: Winston-based logging with daily rotation
- Type Safety: Full TypeScript with Zod schema validation
- Testing: Unit, integration, and e2e test setup with Jest
- Docker Support: Docker Compose for local development with MongoDB and Mongo Express
Architecture
src/
├── domain/ # Business entities and rules
│ ├── entities/ # Domain entities
│ ├── value-objects/ # Value objects with validation
│ └── repositories/ # Repository interfaces
├── application/ # Use cases and DTOs
│ └── use-cases/ # Business logic implementation
├── infrastructure/ # External services and frameworks
│ ├── persistence/mongodb/ # MongoDB implementation
│ ├── mcp/ # MCP server implementation
│ │ ├── tools/ # MCP tools (CRUD operations)
│ │ ├── resources/ # MCP resources (read-only data)
│ │ ├── prompts/ # MCP prompts (templates)
│ │ └── validators/ # Zod schemas for validation
│ ├── config/ # Configuration modules
│ └── logging/ # Logging service
└── presentation/ # Controllers
└── health/ # Health check endpoint
Prerequisites
- Node.js 20+
- MongoDB 7.0+
- npm or yarn
Installation
- Clone the repository:
git clone <repository-url>
cd nestjs-mcp-server
- Install dependencies:
npm install
- Create environment file:
cp .env.example .env
- Configure environment variables in
.env:
NODE_ENV=development
PORT=3000
MONGODB_URI=mongodb://localhost:27017
MONGODB_DATABASE=mcp_default
MCP_TRANSPORT=STDIO
LOG_LEVEL=debug
Running the Application
Development Mode
- Start MongoDB with Docker Compose:
docker-compose up -d mongodb
- Run in development mode:
npm run start:dev
Production Mode
npm run build
npm run start:prod
Docker Compose (Full Stack)
docker-compose up -d
This will start:
- MongoDB on port 27017
- Mongo Express UI on port 8081 (http://localhost:8081)
- NestJS MCP Server on port 3000
MCP Tools Available
The server exposes the following MCP tools for MongoDB operations:
- mongodb-find: Query documents with filters, projection, sorting, and limits
- mongodb-insert: Insert a single document
- mongodb-insert-many: Insert multiple documents
- mongodb-update-many: Update documents matching a filter
- mongodb-delete-many: Delete documents matching a filter
- mongodb-count: Count documents in a collection
- mongodb-aggregate: Execute aggregation pipelines
MCP Resources Available
- mongodb-collections: List all collections in a database
MCP Prompts Available
- mongodb-query-builder: Help build MongoDB queries from natural language
Integration with Claude Desktop
STDIO Mode (Recommended for Local Use)
- Build the project:
npm run build
-
Configure Claude Desktop by editing:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
- macOS:
-
Add the server configuration:
{
"mcpServers": {
"nestjs-mongodb": {
"command": "node",
"args": ["dist/main.js"],
"cwd": "/absolute/path/to/nestjs-mcp-server",
"env": {
"MONGODB_URI": "mongodb://localhost:27017",
"MONGODB_DATABASE": "your_database",
"MCP_TRANSPORT": "STDIO",
"LOG_LEVEL": "info"
}
}
}
}
-
Restart Claude Desktop
-
Verify the connection by asking Claude:
- "List all collections in my MongoDB database"
- "Find all documents in the users collection"
HTTP/SSE Mode (For Remote Access)
- Set environment variables:
export MCP_TRANSPORT=SSE
export PORT=3000
- Start the server:
npm run start:prod
- The MCP endpoint will be available at:
http://localhost:3000/api/mcp
Testing
Run Unit Tests
npm run test
Run Integration Tests
npm run test:integration
Run E2E Tests
npm run test:e2e
Run All Tests with Coverage
npm run test:cov
Example Usage with Claude
Once integrated with Claude Desktop, you can use natural language commands:
Query Documents:
Find all users where age is greater than 25 in the mydb database
Insert Document:
Insert a document { "name": "John", "age": 30 } into the users collection in mydb
Update Documents:
Update all documents where status is "pending" to set status to "completed" in the orders collection
Count Documents:
How many documents are in the products collection?
Aggregate Data:
Run an aggregation to group users by city and count them
Project Structure Details
Domain Layer
- Entities: Core business objects (Document, Collection, QueryResult)
- Value Objects: Validated objects (DatabaseName, CollectionName, QueryFilter)
- Repository Interfaces: Abstractions for data access
Application Layer
- Use Cases: Business logic for each operation
- DTOs: Data transfer objects with class-validator decorators
- Services: Application services (e.g., query validation)
Infrastructure Layer
- MongoDB Repository: Concrete implementation of repository interface
- MCP Tools: Decorators-based MCP tool implementations
- Logging: Winston-based structured logging
- Configuration: Environment-based configuration modules
Configuration
Database Configuration
MONGODB_URI: MongoDB connection stringMONGODB_DATABASE: Default database name
MCP Configuration
MCP_TRANSPORT: Transport mode (STDIO or SSE)MCP_PORT: Port for SSE mode (default: 3000)MCP_READ_ONLY_MODE: Restrict to read-only operations
Logging Configuration
LOG_LEVEL: Logging level (debug, info, warn, error)LOG_DIR: Directory for log files (default: ./logs)NODE_ENV: Environment (development, production)
Security Considerations
- Read-Only Mode: Enable with
MCP_READ_ONLY_MODE=trueto prevent write operations - Environment Variables: Use environment variables for sensitive configuration
- Validation: All inputs are validated with class-validator and Zod
- Logging: In STDIO mode, logs go to stderr to avoid corrupting JSON-RPC messages
API Endpoints
When running in HTTP/SSE mode:
GET /health: Health check endpointPOST /api/mcp: MCP JSON-RPC endpointGET /api/mcp: SSE endpoint for server-to-client messages
Development
Code Style
npm run lint
npm run format
Adding New Tools
- Create use case in
src/application/use-cases/ - Define Zod schema in
src/infrastructure/mcp/validators/mongodb-schemas.ts - Create tool in
src/infrastructure/mcp/tools/ - Register in
src/infrastructure/mcp/mcp.module.ts
Adding New Resources
- Create resource in
src/infrastructure/mcp/resources/ - Register in
src/infrastructure/mcp/mcp.module.ts
Troubleshooting
Claude Desktop Not Connecting
- Check that the path in
claude_desktop_config.jsonis absolute - Verify the project is built:
npm run build - Check logs in stderr when running in STDIO mode
- Restart Claude Desktop after configuration changes
MongoDB Connection Issues
- Verify MongoDB is running:
docker-compose ps - Check MONGODB_URI in your environment
- Ensure MongoDB port (27017) is accessible
Tool Execution Errors
- Check logs in the configured LOG_DIR
- Verify database and collection names are valid
- Ensure proper MongoDB permissions
Contributing
- Fork the repository
- Create a feature branch
- Implement your changes with tests
- Submit a pull request
License
MIT
Support
For issues and questions:
- Create an issue in the repository
- Check the MCP documentation: https://modelcontextprotocol.io
Acknowledgments
- Built with NestJS
- MCP integration using @modelcontextprotocol/sdk
- MongoDB driver: Mongoose
- Logging: Winston
- Validation: Zod and class-validator