MongoDB That Works

A MongoDB MCP server with schema discovery and field validation. Requires a MONGODB_URI environment variable.

Documentation

MongoDB MCP That Works

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:

VariableRequiredDescription
MONGODB_URIYesMongoDB connection string, e.g. mongodb+srv://user:pass@cluster.mongodb.net/database
MONGODB_DATABASENoDefault 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: "user@example.com" }
})

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: "john@example.com" }
})

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": ["user@example.com"],
      "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:

ToolreadOnlyHintidempotentHintdestructiveHintNotes
listCollectionstrue––Pure read
findtrue––Pure read
findOnetrue––Pure read
aggregatetrue––Pure read (may also run write stages)
counttrue––Pure read
distincttrue––Pure read
getSchematrue––Pure read
insertOnefalsefalsefalseAdditive; retrying inserts a new document
updateOnefalsefalsetrueModifies existing docs; $inc/$push are non-idempotent
deleteOnefalsetruetrueDeleting an already-absent document is a no-op

Note: aggregate is annotated read-only, but it can contain write stages (e.g. $out, $merge) β€” inspect pipelines before running.

Best Practices

  1. Use Schema Discovery First: Before querying, run getSchema to understand field names
  2. Handle ObjectIds: The server automatically converts string IDs to ObjectIds
  3. Use Projections: Limit returned fields to improve performance
  4. 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 getSchema to 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 limit parameter
  • 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.

VersionnpmGitHub ReleaseHighlights
0.1.8npmv0.1.8Automated unit + e2e MongoDB test suite
0.1.7npmv0.1.7ToolAnnotations, SDK 1.30, repo-standard docs
0.1.6npmv0.1.6CI/CD, changelog, and repo badges
0.1.5npmv0.1.5Post-migration metadata & ownership fixes
0.1.3npmv0.1.3Published with @latest install docs
0.1.2npmv0.1.2Repo URLs updated to mongodb-mcp-that-works
0.1.0npmv0.1.0Initial 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