# 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
```bash
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
1. Clone the repository:
```bash
git clone <repository-url>
cd nestjs-mcp-server
```
1. Install dependencies:
```bash
npm install
```
1. Create environment file:
```bash
cp .env.example .env
```
1. Configure environment variables in `.env`:
```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
1. Start MongoDB with Docker Compose:
```bash
docker-compose up -d mongodb
```
1. Run in development mode:
```bash
npm run start:dev
```
### Production Mode
```bash
npm run build
npm run start:prod
```
### Docker Compose (Full Stack)
```bash
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)
1. Build the project:
```bash
npm run build
```
1. Configure Claude Desktop by editing:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
2. Add the server configuration:
```json
{
"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"
}
}
}
}
```
1. Restart Claude Desktop
2. 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)
1. Set environment variables:
```bash
export MCP_TRANSPORT=SSE
export PORT=3000
```
1. Start the server:
```bash
npm run start:prod
```
1. The MCP endpoint will be available at: `http://localhost:3000/api/mcp`
## Testing
### Run Unit Tests
```bash
npm run test
```
### Run Integration Tests
```bash
npm run test:integration
```
### Run E2E Tests
```bash
npm run test:e2e
```
### Run All Tests with Coverage
```bash
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 string
- `MONGODB_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=true` to 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 endpoint
- `POST /api/mcp`: MCP JSON-RPC endpoint
- `GET /api/mcp`: SSE endpoint for server-to-client messages
## Development
### Code Style
```bash
npm run lint
npm run format
```
### Adding New Tools
1. Create use case in `src/application/use-cases/`
2. Define Zod schema in `src/infrastructure/mcp/validators/mongodb-schemas.ts`
3. Create tool in `src/infrastructure/mcp/tools/`
4. Register in `src/infrastructure/mcp/mcp.module.ts`
### Adding New Resources
1. Create resource in `src/infrastructure/mcp/resources/`
2. Register in `src/infrastructure/mcp/mcp.module.ts`
## Troubleshooting
### Claude Desktop Not Connecting
1. Check that the path in `claude_desktop_config.json` is absolute
2. Verify the project is built: `npm run build`
3. Check logs in stderr when running in STDIO mode
4. Restart Claude Desktop after configuration changes
### MongoDB Connection Issues
1. Verify MongoDB is running: `docker-compose ps`
2. Check MONGODB_URI in your environment
3. Ensure MongoDB port (27017) is accessible
### Tool Execution Errors
1. Check logs in the configured LOG_DIR
2. Verify database and collection names are valid
3. Ensure proper MongoDB permissions
## Contributing
1. Fork the repository
2. Create a feature branch
3. Implement your changes with tests
4. 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](https://nestjs.com/)
- MCP integration using [@modelcontextprotocol/sdk](https://www.npmjs.com/package/@modelcontextprotocol/sdk)
- MongoDB driver: [Mongoose](https://mongoosejs.com/)
- Logging: [Winston](https://github.com/winstonjs/winston)
- Validation: [Zod](https://zod.dev/) and [class-validator](https://github.com/typestack/class-validator)