MongoDB That Works Server
БесплатноНе проверенEnables interaction with MongoDB databases through CRUD operations, aggregation, and schema discovery, with automatic field validation and ObjectId conversion.
Описание
Enables interaction with MongoDB databases through CRUD operations, aggregation, and schema discovery, with automatic field validation and ObjectId conversion.
README
npm version npm downloads npm weekly downloads CI GitHub release license GitHub stars node
A reliable MongoDB MCP (Model Context Protocol) server with built-in schema discovery and field validation. It's a standard MCP server over stdio, so it connects to any MCP client — Claude Desktop, Claude Code, OpenAI Codex, Cursor, VS Code / GitHub Copilot, Zed, and more.
Published on npm: @sourabhshegane/mongodb-mcp-that-works · Install with
npx -y @sourabhshegane/mongodb-mcp-that-works
[!CAUTION] This server connects to your MongoDB with full read/write access to whatever user and database you supply via
MONGODB_URI, and it exposes write tools (insertOne,updateOne,deleteOne) to any connected client. Only register it with MCP clients you trust. For high-risk environments, use a read-only MongoDB user or a dedicated database.
Features
- 🔍 Schema Discovery: Automatically analyze collection structures
- ✅ Field Validation: Prevent field name mistakes
- 📊 Full MongoDB Support: Find, aggregate, insert, update, delete operations
- 🚀 High Performance: Efficient connection pooling and query optimization
- 🔐 Secure: Support for MongoDB Atlas and authentication
- 🎯 Type-Safe: Built with TypeScript and Zod validation
Installation
Install from npm
npm install -g @sourabhshegane/mongodb-mcp-that-works
Configuration
This is a standard stdio MCP server. Any MCP client launches it with npx and passes two environment variables:
| Variable | Required | Description |
|---|---|---|
MONGODB_URI |
Yes | MongoDB connection string, e.g. mongodb+srv://user:[email protected]/database |
MONGODB_DATABASE |
No | Default database name (falls back to the URI's database) |
Every client below uses the same launch command:
npx -y @sourabhshegane/mongodb-mcp-that-works@latest
The -y flag auto-confirms the install so the client never hangs on an interactive prompt.
Security: never commit a real connection string. The examples use placeholders, or reference environment variables (
${env:...},env_vars,${input:...}) so credentials stay out of version control.
Claude Desktop
Edit your Claude Desktop config:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "mongodb+srv://<user>:<password>@cluster.mongodb.net/<database>",
"MONGODB_DATABASE": "your_database_name"
}
}
}
}
Claude Code
Add it with the CLI (anything after -- is the server command):
claude mcp add mongodb --scope user \
--env MONGODB_URI=mongodb+srv://<user>:<password>@cluster.mongodb.net/<database> \
-- npx -y @sourabhshegane/mongodb-mcp-that-works@latest
Or commit a project-scoped .mcp.json (secrets referenced with ${VAR}):
{
"mcpServers": {
"mongodb": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "${MONGODB_URI}",
"MONGODB_DATABASE": "${MONGODB_DATABASE:-your_database_name}"
}
}
}
}
Scopes: local → ~/.claude.json, project → .mcp.json, user → ~/.claude.json. Verify with claude mcp list.
OpenAI Codex
Codex uses TOML (not JSON). Add to ~/.codex/config.toml (or project-scoped .codex/config.toml):
[mcp_servers.mongodb]
command = "npx"
args = ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"]
env = { MONGODB_URI = "mongodb+srv://<user>:<password>@cluster.mongodb.net/<database>", MONGODB_DATABASE = "your_database_name" }
startup_timeout_sec = 30
Or forward variables from your shell instead of inlining them:
[mcp_servers.mongodb]
command = "npx"
args = ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"]
env_vars = ["MONGODB_URI", "MONGODB_DATABASE"]
Or add it with the CLI: codex mcp add mongodb -- npx -y @sourabhshegane/mongodb-mcp-that-works@latest. Verify with codex mcp list.
Cursor
Project scope — .cursor/mcp.json (commit it to share with your team). Global scope — ~/.cursor/mcp.json.
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "${env:MONGODB_URI}",
"MONGODB_DATABASE": "${env:MONGODB_DATABASE}"
}
}
}
}
VS Code / GitHub Copilot
For quick installation, click the buttons below. After install, replace the placeholder connection string in your config:
Install with NPX in VS Code Install with NPX in VS Code Insiders
Note: VS Code's root key is servers (other clients use mcpServers), and type is required. .vscode/mcp.json:
{
"servers": {
"mongodb": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "${input:mongodb-uri}"
}
}
},
"inputs": [
{
"id": "mongodb-uri",
"type": "promptString",
"description": "MongoDB connection string",
"password": true
}
]
}
Zed
Add to settings.json (~/.config/zed/settings.json or .zed/settings.json):
{
"mcp": {
"mongodb": {
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "mongodb+srv://<user>:<password>@cluster.mongodb.net/<database>"
}
}
}
}
Available Tools
1. listCollections
List all collections in the database.
// Example
mcp.listCollections({ filter: {} })
2. find
Find documents in a collection with filtering, sorting, and pagination.
// Example
mcp.find({
collection: "users",
filter: { status: "active" },
sort: { createdAt: -1 },
limit: 10
})
3. findOne
Find a single document.
// Example
mcp.findOne({
collection: "users",
filter: { email: "[email protected]" }
})
4. aggregate
Run aggregation pipelines.
// Example
mcp.aggregate({
collection: "orders",
pipeline: [
{ $match: { status: "completed" } },
{ $group: { _id: "$userId", total: { $sum: "$amount" } } }
]
})
5. count
Count documents matching a filter.
// Example
mcp.count({
collection: "products",
filter: { inStock: true }
})
6. distinct
Get distinct values for a field.
// Example
mcp.distinct({
collection: "orders",
field: "status"
})
7. insertOne
Insert a single document.
// Example
mcp.insertOne({
collection: "users",
document: { name: "John Doe", email: "[email protected]" }
})
8. updateOne
Update a single document.
// Example
mcp.updateOne({
collection: "users",
filter: { _id: "123" },
update: { $set: { status: "active" } }
})
9. deleteOne
Delete a single document.
// Example
mcp.deleteOne({
collection: "users",
filter: { _id: "123" }
})
10. getSchema
Analyze collection structure and discover field names.
// Example
mcp.getSchema({
collection: "users",
sampleSize: 100
})
// Returns:
{
"collection": "users",
"sampleSize": 100,
"fields": {
"_id": {
"types": ["ObjectId"],
"examples": ["507f1f77bcf86cd799439011"],
"frequency": "100/100",
"percentage": 100
},
"email": {
"types": ["string"],
"examples": ["[email protected]"],
"frequency": "100/100",
"percentage": 100
}
}
}
Tool annotations (MCP hints)
Tools are annotated with MCP ToolAnnotations so clients can distinguish read-only tools from write-capable tools and flag operations that are destructive:
| Tool | readOnlyHint | idempotentHint | destructiveHint | Notes |
|---|---|---|---|---|
listCollections |
true |
– | – | Pure read |
find |
true |
– | – | Pure read |
findOne |
true |
– | – | Pure read |
aggregate |
true |
– | – | Pure read (may also run write stages) |
count |
true |
– | – | Pure read |
distinct |
true |
– | – | Pure read |
getSchema |
true |
– | – | Pure read |
insertOne |
false |
false |
false |
Additive; retrying inserts a new document |
updateOne |
false |
false |
true |
Modifies existing docs; $inc/$push are non-idempotent |
deleteOne |
false |
true |
true |
Deleting an already-absent document is a no-op |
Note:
aggregateis annotated read-only, but it can contain write stages (e.g.$out,$merge) — inspect pipelines before running.
Best Practices
- Use Schema Discovery First: Before querying, run
getSchemato understand field names - Handle ObjectIds: The server automatically converts string IDs to ObjectIds
- Use Projections: Limit returned fields to improve performance
- Batch Operations: Use aggregation pipelines for complex queries
Examples
Basic Usage
// Get schema first to avoid field name mistakes
const schema = await mcp.getSchema({ collection: "reports" });
// Use correct field names from schema
const reports = await mcp.find({
collection: "reports",
filter: { organization_id: "64ba7374f8b63db2083b2665" },
limit: 10
});
Advanced Aggregation
const analytics = await mcp.aggregate({
collection: "orders",
pipeline: [
{ $match: { createdAt: { $gte: new Date("2024-01-01") } } },
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$createdAt" } },
revenue: { $sum: "$amount" },
count: { $sum: 1 }
}},
{ $sort: { _id: 1 } }
]
});
Debugging
You can use the MCP Inspector to debug the server, inspect tool schemas, and call tools interactively:
npx @modelcontextprotocol/inspector npx -y @sourabhshegane/mongodb-mcp-that-works@latest
Set MONGODB_URI (and optionally MONGODB_DATABASE) in your environment before launching the inspector.
Troubleshooting
Connection Issues
- Verify your MongoDB URI is correct
- Check network connectivity to MongoDB Atlas
- Ensure IP whitelist includes your current IP
Field Name Errors
- Always use
getSchemato discover correct field names - Remember MongoDB is case-sensitive
- Check for typos in nested field paths (e.g., "user.profile.name")
Performance
- Use indexes for frequently queried fields
- Limit result sets with
limitparameter - Use projections to return only needed fields
Testing
The repo ships an automated test suite (node:test, no extra framework):
npm test
This first builds, then runs:
- Unit tests (
tests/unit.test.mjs) — MCP protocol: negotiated version, the 10 tool schemas, ToolAnnotations, and error handling. No database required. - End-to-end tests (
tests/e2e.test.mjs) — full CRUD tour against a real MongoDB (insertOne→find/findOne/count/distinct/aggregate→updateOne→getSchema→deleteOne), plus ObjectId auto-conversion and idempotency checks. Auto-skips with a note when no MongoDB is reachable.
The suite connects to MongoDB at MONGODB_URI (default mongodb://127.0.0.1:27017) and uses a throwaway database it deletes afterward, so it's safe against any existing data. CI runs both suites against a real MongoDB (Docker mongo:7) on every push/PR.
Contributing
Contributions are welcome — new tools, bug fixes, examples, and documentation improvements. Pull requests and issues are appreciated. See CHANGELOG.md for release history. For examples of other MCP servers, see the reference implementations.
License
MIT License - see LICENSE file for details
Changelog
See CHANGELOG.md for the full history.
| Version | npm | GitHub Release | Highlights |
|---|---|---|---|
| 0.1.8 | npm | v0.1.8 | Automated unit + e2e MongoDB test suite |
| 0.1.7 | npm | v0.1.7 | ToolAnnotations, SDK 1.30, repo-standard docs |
| 0.1.6 | npm | v0.1.6 | CI/CD, changelog, and repo badges |
| 0.1.5 | npm | v0.1.5 | Post-migration metadata & ownership fixes |
| 0.1.3 | npm | v0.1.3 | Published with @latest install docs |
| 0.1.2 | npm | v0.1.2 | Repo URLs updated to mongodb-mcp-that-works |
| 0.1.0 | npm | v0.1.0 | Initial release |
Releases
All versions published to npm also have tagged GitHub Releases with build checks. The repo uses GitHub Actions for continuous integration and automated publishing:
- Tag pushes (
v*) trigger lint/build checks and, once checks pass, an automated npm publish - Every published version has a matching GitHub Release
Made out of pain since the official MongoDB MCP didn't work for me
Установка MongoDB That Works Server
У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.
▸ github.com/sourabhfb/mongodb-mcp-that-worksFAQ
MongoDB That Works Server MCP бесплатный?
Да, MongoDB That Works Server MCP бесплатный — установка в пару кликов через Unyly без оплаты.
Нужен ли API-ключ для MongoDB That Works Server?
Нет, MongoDB That Works Server работает без API-ключей и переменных окружения.
MongoDB That Works Server — hosted или self-hosted?
Доступен hosted-вариант: Unyly запускает сервер в облаке, локальная установка не обязательна.
Как установить MongoDB That Works Server в Claude Desktop, Claude Code или Cursor?
Открой MongoDB That Works Server на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.
Похожие MCP
GitHub
PRs, issues, code search, CI status
автор: GitHubFilesystem
Secure file operations with configurable access controls.
Memory
Knowledge graph-based persistent memory system.
Template MCP Server
A CLI tool to create a new Model Context Protocol server project with TypeScript support, dual transport options, and an extensible structure
автор: mcpdotdirectAmap Maps Mcp Server
MCP server for using the AMap Maps API
автор: duxiaohuiSupabase
Database, auth and storage
автор: SupabaseEverything
Reference / test server with prompts, resources, and tools.
Git
Tools to read, search, and manipulate Git repositories.
Sequential Thinking
Dynamic and reflective problem-solving through thought sequences.
Time
Time and timezone conversion capabilities.
Compare MongoDB That Works Server with
Не уверен что выбрать?
Найди свой стек за 60 секунд
Автор?
Embed-бейдж для README
Похожее
Все в категории development
