Skip to main content
Glama
MongoDB That Works - MCP Server

MongoDB That Works - MCP Server

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 withfull 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

Related MCP server: Mongo-MCP

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:pass@cluster.mongodb.net/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: "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:

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: 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.

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

Available Tools

10 tools
aggregateB
Read-onlyIdempotent

Run an aggregation pipeline on a MongoDB collection

Inputs: pipeline (required), collection (required), limit.

countA
Read-onlyIdempotent

Count documents in a MongoDB collection

Inputs: collection (required), filter.

deleteOneA
DestructiveIdempotent

Delete a single document from a MongoDB collection

Inputs: filter (required), collection (required).

distinctB
Read-onlyIdempotent

Get distinct values for a field in a MongoDB collection

Inputs: field (required), collection (required), filter.

findA
Read-onlyIdempotent

Find documents in a MongoDB collection

Inputs: collection (required), skip, sort, limit, +2 more.

findOneB
Read-onlyIdempotent

Find a single document in a MongoDB collection

Inputs: collection (required), filter, projection.

getSchemaA
Read-onlyIdempotent

Analyze collection structure and return field names with types

Inputs: collection (required), sampleSize.

insertOneB

Insert a single document into a MongoDB collection

Inputs: document (required), collection (required).

listCollectionsA
Read-onlyIdempotent

List all collections in the database

Inputs: filter.

updateOneC
Destructive

Update a single document in a MongoDB collection

Inputs: filter (required), update (required), collection (required), upsert.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    A3.7/5.0

    Scored across 10 tools

    Disambiguation5/5

    Each tool targets a distinct MongoDB operation: find vs findOne are clearly differentiated (multiple vs single document), and aggregate, count, distinct, listCollections, insertOne, updateOne, deleteOne, and getSchema have no overlapping responsibilities. The descriptions clarify the purpose of each, leaving no ambiguity for an agent.

    Naming Consistency5/5

    All tool names follow a consistent lowerCamelCase convention with a verb-first pattern (find, findOne, aggregate, count, distinct, listCollections, insertOne, updateOne, deleteOne, getSchema). The style is uniform and predictable, making it easy to infer tool behavior from the name.

    Tool Count5/5

    With 10 tools, the server is well-scoped for a MongoDB interface. It covers querying, aggregation, schema inspection, and basic CRUD operations without unnecessary bloat. Each tool serves a clear purpose, and the count is ideal for an MCP server of this domain.

    Completeness4/5

    The tool surface covers the core CRUD operations (insertOne, updateOne, deleteOne, find, findOne) and includes useful extras like aggregate, count, distinct, and getSchema. However, it lacks bulk operations (insertMany, updateMany, deleteMany) and collection management (createCollection, dropCollection), which are common in MongoDB workflows. These are minor gaps that an agent can work around by composing single-document calls, but they are noticeable.

    Maintenance

    ActivityStale
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables interaction with MongoDB databases through complete CRUD operations including connecting, creating, reading, updating, and deleting documents with support for filtering, pagination, and automatic ObjectId serialization.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables LLMs to interact with MongoDB databases through a complete suite of CRUD operations, administrative tasks, and index management tools. It supports database and collection handling, aggregation pipelines, and comprehensive server monitoring via the Model Context Protocol.
      142 PyPI
      3
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables interaction with MongoDB databases through the Model Context Protocol, supporting CRUD operations, secure connections, and easy IDE integration.
      2 npm
      3
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to interact natively with MongoDB databases, including schema discovery, CRUD operations, aggregation pipelines, and index management via natural language.
      21 npm
      MIT