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.
- 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
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- Node.js 20+
- MongoDB 7.0+
- npm or yarn
- 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- Start MongoDB with Docker Compose:
docker-compose up -d mongodb- Run in development mode:
npm run start:devnpm run build
npm run start:proddocker-compose up -dThis will start:
- MongoDB on port 27017
- Mongo Express UI on port 8081 (http://localhost:8081)
- NestJS MCP Server on port 3000
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
- mongodb-collections: List all collections in a database
- mongodb-query-builder: Help build MongoDB queries from natural language
- 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"
- 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
npm run testnpm run test:integrationnpm run test:e2enpm run test:covOnce 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
- Entities: Core business objects (Document, Collection, QueryResult)
- Value Objects: Validated objects (DatabaseName, CollectionName, QueryFilter)
- Repository Interfaces: Abstractions for data access
- Use Cases: Business logic for each operation
- DTOs: Data transfer objects with class-validator decorators
- Services: Application services (e.g., query validation)
- MongoDB Repository: Concrete implementation of repository interface
- MCP Tools: Decorators-based MCP tool implementations
- Logging: Winston-based structured logging
- Configuration: Environment-based configuration modules
MONGODB_URI: MongoDB connection stringMONGODB_DATABASE: Default database name
MCP_TRANSPORT: Transport mode (STDIO or SSE)MCP_PORT: Port for SSE mode (default: 3000)MCP_READ_ONLY_MODE: Restrict to read-only operations
LOG_LEVEL: Logging level (debug, info, warn, error)LOG_DIR: Directory for log files (default: ./logs)NODE_ENV: Environment (development, production)
- 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
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
npm run lint
npm run format- 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
- Create resource in
src/infrastructure/mcp/resources/ - Register in
src/infrastructure/mcp/mcp.module.ts
- 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
- Verify MongoDB is running:
docker-compose ps - Check MONGODB_URI in your environment
- Ensure MongoDB port (27017) is accessible
- Check logs in the configured LOG_DIR
- Verify database and collection names are valid
- Ensure proper MongoDB permissions
- Fork the repository
- Create a feature branch
- Implement your changes with tests
- Submit a pull request
MIT
For issues and questions:
- Create an issue in the repository
- Check the MCP documentation: https://modelcontextprotocol.io
- Built with NestJS
- MCP integration using @modelcontextprotocol/sdk
- MongoDB driver: Mongoose
- Logging: Winston
- Validation: Zod and class-validator