MongoDB MCP Server
A Model Context Protocol (MCP) server for MongoDB operations, enabling AI assistants to interact with MongoDB databases through a standardized interface.
README
MongoDB MCP Server
A Model Context Protocol (MCP) server for MongoDB operations, enabling AI assistants to interact with MongoDB databases through a standardized interface.
Features
Core Operations
- Database Operations: List, stats, drop databases
- Collection Operations: Create, drop, rename, list collections
- Document Operations: Full CRUD (find, insert, update, delete), aggregation
- Index Operations: Create, list, drop indexes
Security & Access Control
- Permission System: Role-based access control with allowed/denied databases and collections
- Read-Only Mode: Prevent all write operations
- Query Result Limits: Configurable maximum results per query
- Bulk Operation Limits: Control maximum bulk operations
Monitoring & Auditing
- Audit Logging: Track all operations with timestamps, success/failure status
- Rate Limiting: Prevent abuse with configurable request limits
- Health Check: Monitor MongoDB connection and server status
Data Protection
- Data Masking: Automatically mask sensitive fields (passwords, tokens, etc.)
- Confirmation Prompts: Require confirmation for dangerous operations (drop database/collection)
Configuration
- Configuration File: Support for JSON configuration files
- Environment Variables: All settings configurable via environment variables
- Connection Pooling: MongoDB driver connection pooling
Installation
npm install mongodb-mcp
Or from source:
git clone https://github.com/az-coder-123/mongodb-mcp.git
cd mongodb-mcp
npm install
npm run build
Configuration
Configuration File
Create a mcp-settings.json file in your project root or home directory:
{
"connectionString": "mongodb://localhost:27017",
"permissions": {
"readOnly": false,
"allowedDatabases": ["myapp", "analytics"],
"deniedDatabases": ["admin", "config"],
"allowedCollections": {
"myapp": ["users", "orders", "products"]
},
"deniedTools": ["drop_database"],
"maxQueryResults": 1000,
"maxBulkOperations": 1000
},
"auditLog": {
"enabled": true,
"logFilePath": "./logs/audit.log",
"maxEntries": 10000,
"logSuccess": true,
"logFailure": true
},
"rateLimit": {
"enabled": true,
"maxRequests": 100,
"windowMs": 60000
},
"dataMasking": true,
"maskedFields": ["password", "secret", "token", "apiKey"]
}
Environment Variables
| Variable | Description | Default |
|---|---|---|
MONGODB_URI |
MongoDB connection string | mongodb://localhost:27017 |
MCP_READ_ONLY |
Enable read-only mode | false |
MCP_ALLOWED_DATABASES |
Comma-separated list of allowed databases | (all allowed) |
MCP_DENIED_DATABASES |
Comma-separated list of denied databases | (none) |
MCP_DENIED_TOOLS |
Comma-separated list of denied tools | (none) |
MCP_MAX_QUERY_RESULTS |
Maximum query results | 1000 |
MCP_MAX_BULK_OPERATIONS |
Maximum bulk operations | 1000 |
MCP_AUDIT_LOG_ENABLED |
Enable audit logging | true |
MCP_AUDIT_LOG_PATH |
Audit log file path | (console only) |
MCP_RATE_LIMIT_ENABLED |
Enable rate limiting | true |
MCP_RATE_LIMIT_MAX_REQUESTS |
Max requests per window | 100 |
MCP_RATE_LIMIT_WINDOW_MS |
Rate limit window (ms) | 60000 |
MCP_DATA_MASKING_ENABLED |
Enable data masking | true |
MCP_MASKED_FIELDS |
Comma-separated masked fields | password,secret,token,apiKey |
Usage with Claude Desktop
Add to your Claude Desktop configuration:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"mongodb": {
"command": "node",
"args": ["/path/to/mongodb-mcp/dist/index.js"],
"env": {
"MONGODB_URI": "mongodb://localhost:27017"
}
}
}
}
Available Tools
Database Operations
list_databases
List all databases in the MongoDB instance.
{}
database_stats
Get statistics for a specific database.
{
"database": "mydb"
}
drop_database
⚠️ Drop a database (requires confirmation).
{
"database": "test_db",
"confirm": true
}
Collection Operations
list_collections
List all collections in a database.
{
"database": "mydb"
}
create_collection
Create a new collection.
{
"database": "mydb",
"collection": "users",
"options": {
"capped": true,
"size": 1048576,
"max": 1000
}
}
drop_collection
⚠️ Drop a collection (requires confirmation).
{
"database": "mydb",
"collection": "temp_data",
"confirm": true
}
Document Operations
find
Find documents with filters, projections, sorting, and pagination.
{
"database": "mydb",
"collection": "users",
"filter": { "age": { "$gte": 18 } },
"projection": { "name": 1, "email": 1 },
"sort": { "name": 1 },
"limit": 10,
"skip": 0
}
insert_one
Insert a single document.
{
"database": "mydb",
"collection": "users",
"document": {
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
}
insert_many
Insert multiple documents.
{
"database": "mydb",
"collection": "users",
"documents": [
{ "name": "User 1", "email": "user1@example.com" },
{ "name": "User 2", "email": "user2@example.com" }
]
}
update_one
Update a single document.
{
"database": "mydb",
"collection": "users",
"filter": { "email": "john@example.com" },
"update": { "$set": { "age": 31 } },
"upsert": false
}
delete_one
Delete a single document.
{
"database": "mydb",
"collection": "users",
"filter": { "email": "john@example.com" }
}
aggregate
Run an aggregation pipeline.
{
"database": "mydb",
"collection": "orders",
"pipeline": [
{ "$match": { "status": "completed" } },
{ "$group": { "_id": "$customerId", "total": { "$sum": "$amount" } } },
{ "$sort": { "total": -1 } },
{ "$limit": 10 }
]
}
Index Operations
create_index
Create an index on a collection.
{
"database": "mydb",
"collection": "users",
"keys": { "email": 1 },
"options": {
"unique": true,
"name": "email_unique_idx"
}
}
Monitoring Tools
health_check
Check MongoDB connection health and server status.
{}
get_audit_log
Get audit log entries.
{
"limit": 100,
"toolName": "insert_one",
"failuresOnly": false
}
get_server_config
Get current server configuration.
{}
set_read_only
Enable or disable read-only mode.
{
"enabled": true
}
Security Features
Permission System
Control access to databases and collections:
{
"permissions": {
"allowedDatabases": ["myapp"],
"deniedDatabases": ["admin"],
"allowedCollections": {
"myapp": ["users", "orders"]
},
"deniedTools": ["drop_database", "drop_collection"]
}
}
Read-Only Mode
Prevent all write operations:
MCP_READ_ONLY=true node dist/index.js
Or via tool call:
{
"name": "set_read_only",
"arguments": { "enabled": true }
}
Confirmation Prompts
Dangerous operations require explicit confirmation:
drop_databaserequires"confirm": truedrop_collectionrequires"confirm": true
Data Masking
Sensitive fields are automatically masked in responses:
{
"dataMasking": true,
"maskedFields": ["password", "secret", "token", "apiKey", "creditCard"]
}
Rate Limiting
Prevent abuse with configurable limits:
{
"rateLimit": {
"enabled": true,
"maxRequests": 100,
"windowMs": 60000
}
}
Error Handling
The server implements a comprehensive error handling system with structured error classes, automatic categorization, and actionable recovery suggestions.
Error Format
The server returns errors in the following format:
{
"content": [
{
"type": "text",
"text": "VALIDATION_ERROR: Invalid value for 'collection': expected string, got number\n\nSuggestions:\n 1. Check 'collection' parameter\n 2. Refer to documentation for valid values\n\nContext: {\n \"field\": \"collection\",\n \"value\": 123,\n \"expectedType\": \"string\"\n}"
}
],
"isError": true
}
Error Categories
All errors are categorized for proper handling:
| Category | Description |
|---|---|
VALIDATION |
Invalid input parameters |
PERMISSION |
Access denied |
RATE_LIMIT |
Too many requests |
CONNECTION |
MongoDB connection issues |
OPERATION |
Database operation failures |
NOT_FOUND |
Resource not found |
CONFIGURATION |
Invalid configuration |
Error Types
The server provides specific error types with recovery suggestions:
- ValidationError - Input validation errors
- PermissionError - Access denied errors
- RateLimitError - Rate limit exceeded
- ConnectionError - MongoDB connection failures
- OperationError - Database operation failures
- NotFoundError - Resource not found
- ConfigurationError - Configuration errors
- ReadOnlyError - Read-only mode violations
- BulkLimitError - Bulk operation limits
- QueryLimitError - Query result limits
- ConfirmationRequiredError - Dangerous operations without confirmation
Documentation
For comprehensive error handling documentation, see docs/error-handling.md.
This guide includes:
- Complete error classes reference
- Error handling utilities
- Best practices
- Error recovery patterns
- Common troubleshooting scenarios
Development
Running in development mode
npm run dev
This will watch for file changes and automatically rebuild.
Building
npm run build
Cleaning
npm run clean
Architecture
src/
├── types/
│ └── index.ts # TypeScript interfaces and types
├── validators/
│ └── index.ts # Input validation functions
├── handlers/
│ ├── database.ts # Database operation handlers
│ ├── collection.ts # Collection operation handlers
│ ├── document.ts # Document CRUD handlers
│ ├── index-operations.ts # Index operation handlers
│ └── index.ts # Handler exports
├── resources/
│ └── index.ts # MCP resource handlers
├── tools/
│ └── index.ts # Tool definitions
├── utils/
│ ├── permission-checker.ts # Permission system
│ ├── audit-logger.ts # Audit logging
│ ├── rate-limiter.ts # Rate limiting
│ ├── data-masker.ts # Data masking
│ ├── config-loader.ts # Configuration loading
│ └── index.ts # Utility exports
├── server.ts # Main server class
└── index.ts # Entry point
License
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。