MCP HubMCP Hub
furey

mongodb-lens

by: furey

πŸƒπŸ”Ž MongoDB Lens: Full Featured MCP Server for MongoDB Databases

89created 09/03/2025
Visit
MongoDB
Database

πŸ“ŒOverview

Purpose: MongoDB Lens aims to facilitate access to MongoDB databases using natural language, allowing users to perform queries, manage data, and optimize performance seamlessly.

Overview: MongoDB Lens operates as a local Model Context Protocol (MCP) server, enabling comprehensive interaction with MongoDB through everyday language. It enhances user experience by replacing traditional database commands with natural language queries, making data management more intuitive.

Key Features:

  • Natural Language Queries: Users can execute database operations simply by typing their requests in plain language, streamlining user interaction and reducing the learning curve associated with SQL.

  • Multiple Tools for Data Management: The framework offers a variety of built-in tools such as aggregate-data for executing aggregation pipelines, analyze-query-patterns for performance optimization, and bulk-operations for handling multiple transactions efficiently.

  • Data Protection Mechanisms: MongoDB Lens incorporates safeguards for destructive operations with a two-step confirmation process, ensuring users are aware of potentially irreversible actions before they occur.


MongoDB Lens

MongoDB Lens is a local Model Context Protocol (MCP) server with full featured access to MongoDB databases using natural language via LLMs to perform queries, run aggregations, optimize performance, and more.

Contents

  • Quick Start
  • Features
  • Installation
  • Configuration
  • Client Setup
  • Data Protection
  • Tutorial
  • Test Suite
  • Disclaimer
  • Support

Quick Start

  • Install MongoDB Lens
  • Configure MongoDB Lens
  • Set up your MCP Client (e.g. Claude Desktop, Cursor, etc)
  • Explore your MongoDB databases with natural language queries

Features

Tools

  • add-connection-alias: Add a new MongoDB connection alias
  • aggregate-data: Execute aggregation pipelines
  • analyze-query-patterns: Analyze live queries and suggest optimizations
  • analyze-schema: Automatically infer collection schemas
  • bulk-operations: Perform multiple operations efficiently (requires confirmation for destructive operations)
  • clear-cache: Clear memory caches to ensure fresh data
  • collation-query: Find documents with language-specific collation rules
  • compare-schemas: Compare schemas between two collections
  • connect-mongodb: Connect to a different MongoDB URI
  • connect-original: Connect back to the original MongoDB URI used at startup
  • count-documents: Count documents matching specified criteria
  • create-collection: Create new collections with custom options
  • create-database: Create a new database with option to switch to it
  • create-index: Create new indexes for performance optimization
  • create-timeseries: Create time series collections for temporal data
  • create-user: Create new database users with specific roles
  • current-database: Show the current database context
  • delete-document: Delete documents matching specified criteria (requires confirmation)
  • distinct-values: Extract unique values for any field
  • drop-collection: Remove collections from the database (requires confirmation)
  • drop-database: Drop a database (requires confirmation)
  • drop-index: Remove indexes from collections (requires confirmation)
  • drop-user: Remove database users (requires confirmation)
  • explain-query: Analyze query execution plans
  • export-data: Export query results in JSON or CSV format
  • find-documents: Run queries with filters, projections, and sorting
  • generate-schema-validator: Generate JSON Schema validators
  • geo-query: Perform geospatial queries with various operators
  • get-stats: Retrieve database or collection statistics
  • gridfs-operation: Manage large files with GridFS buckets
  • insert-document: Insert one or more documents into collections
  • list-collections: Explore collections in the current database
  • list-connections: View all available MongoDB connection aliases
  • list-databases: View all accessible databases
  • rename-collection: Rename existing collections (requires confirmation when dropping targets)
  • shard-status: View sharding configuration for databases and collections
  • text-search: Perform full-text search across text-indexed fields
  • transaction: Execute multiple operations in a single ACID transaction
  • update-document: Update documents matching specified criteria
  • use-database: Switch to a specific database context
  • validate-collection: Check for data inconsistencies
  • watch-changes: Monitor real-time changes to collections

Resources

  • collection-indexes: Index information for a collection
  • collection-schema: Schema information for a collection
  • collection-stats: Performance statistics for a collection
  • collection-validation: Validation rules for a collection
  • collections: List of collections in the current database
  • database-triggers: Database change streams and event triggers configuration
  • database-users: Database users and roles in the current database
  • databases: List of all accessible databases
  • performance-metrics: Real-time performance metrics and profiling data
  • replica-status: Replica set status and configuration
  • server-status: Server status information
  • stored-functions: Stored JavaScript functions in the current database

Prompts

  • aggregation-builder: Step-by-step creation of aggregation pipelines
  • backup-strategy: Customized backup and recovery recommendations
  • data-modeling: Expert advice on MongoDB schema design for specific use cases
  • database-health-check: Comprehensive database health assessment and recommendations
  • index-recommendation: Get personalized index suggestions based on query patterns
  • migration-guide: Step-by-step MongoDB version migration plans
  • mongo-shell: Generate MongoDB shell commands with explanations
  • multi-tenant-design: Design MongoDB multi-tenant database architecture
  • query-builder: Interactive guidance for constructing MongoDB queries
  • query-optimizer: Optimization recommendations for slow queries
  • schema-analysis: Detailed collection schema analysis with recommendations
  • schema-versioning: Manage schema evolution in MongoDB applications
  • security-audit: Database security analysis and improvement recommendations
  • sql-to-mongodb: Convert SQL queries to MongoDB aggregation pipelines

Other Features

  • Custom configuration via config file
  • Environment variable overrides for configuration
  • Two-step confirmation for destructive operations
  • Multiple named MongoDB connection aliases
  • Selectively disable tools, prompts or resources
  • Auto-reconnection with exponential backoff
  • Configurable query limits and safeguards
  • Comprehensive error handling
  • Efficient schema inference with intelligent sampling
  • Obfuscation of passwords in logs
  • Auto-monitoring and cleanup of memory
  • Optimized caching for schema, indexes, fields and collections
  • Backwards compatibility with modern and legacy MongoDB versions

New Database Metadata

MongoDB Lens inserts a metadata collection into each database it creates containing contextual information about the database's origin. Once you have your own data, you can safely remove this metadata collection using the drop-collection tool with confirmation.

Installation

MongoDB Lens can be installed and run in several ways:

  • NPX (Easiest)
  • Docker Hub
  • Node.js from Source
  • Docker from Source
  • Installation verification method
  • Support for older MongoDB versions

Installation: NPX

Requires Node.js installed (recommendation: use Volta).

Run MongoDB Lens with:

npx -y mongodb-lens
npx -y mongodb-lens mongodb://your-connection-string
npx -y mongodb-lens@latest

If you encounter permission errors, run:

npx clear-npx-cache

Installation: Docker Hub

Requires Docker installed.

Run MongoDB Lens with:

docker run --rm -i --network=host furey/mongodb-lens
docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string
docker run --rm -i --network=host --pull=always furey/mongodb-lens

Installation: Node.js from Source

  1. Clone the repository:
git clone https://github.com/furey/mongodb-lens.git
  1. Navigate to the directory:
cd /path/to/mongodb-lens
  1. Ensure Node.js is installed.

  2. Install dependencies:

npm ci
  1. Start the server:
node mongodb-lens.js
node mongodb-lens.js mongodb://your-connection-string

Installation: Docker from Source

  1. Clone the repository:
git clone https://github.com/furey/mongodb-lens.git
  1. Navigate to the directory:
cd /path/to/mongodb-lens
  1. Build the Docker image:
docker build -t mongodb-lens .
  1. Run the container:
docker run --rm -i --network=host mongodb-lens
docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string

Installation Verification

Send this JSONRPC message to the server's stdio:

{"method":"resources/read","params":{"uri":"mongodb://databases"},"jsonrpc":"2.0","id":1}

The server should respond with a list of databases in your MongoDB instance.

Installation: Older MongoDB Versions

For MongoDB versions < 4.0, you need MongoDB Node.js driver 3.x series compatibility. Modify package.json to set "mongodb": "^3.7.4" (or an appropriate version), then install and run MongoDB Lens.

For NPX or Docker, use older MongoDB Lens version (e.g., 8.3.0):

npx -y mongodb-lens@8.3.0
docker run --rm -i --network=host furey/mongodb-lens:8.3.0

Configuration

MongoDB Connection String

The server accepts a MongoDB connection string as its only argument.

Format:

mongodb://[username:password@]host[:port][/database][?options]

Examples:

  • mongodb://localhost:27017
  • mongodb://username:password@hostname:27017/mydatabase?authSource=admin

If no connection string is provided, defaults to local connection.

Config File

Extensive customization via optional JSON or JSONC config file, default paths:

  • ~/.mongodb-lens.jsonc
  • fallback: ~/.mongodb-lens.json

Set custom config file path with the environment variable CONFIG_PATH.

You only need to customize settings you want; others use defaults.

The config supports settings such as connection options, caching, logging, and tool-specific parameters.

Config File Generation

Generate a config file automatically with:

npx -y mongodb-lens@latest config:create
npm run config:create

Use --force to overwrite existing files.

Specify custom path with CONFIG_PATH env variable.

Multiple MongoDB Connections

Config file supports multiple named MongoDB connection URIs:

{
  "mongoUri": {
    "main": "mongodb://localhost:27017",
    "backup": "mongodb://localhost:27018",
    "atlas": "mongodb+srv://user:pass@cluster.mongodb.net/db"
  }
}

Switch connections by alias name or full URI. Use add-connection-alias tool to add aliases at runtime.

Environment Variable Overrides

Use environment variables to override config settings, prefix CONFIG_ followed by uppercase snake_cased setting path. Examples:

  • CONFIG_MONGO_URI
  • CONFIG_LOG_LEVEL
  • CONFIG_DEFAULT_DB_NAME

Booleans as 'true'/'false', numbers as strings, complex types as JSON strings.

Example:

CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest

Cross-Platform Environment Variables

Use cross-env to set env vars consistently across OSes:

cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest

Client Setup

Claude Desktop

Install Claude Desktop and add MongoDB Lens as MCP server by editing claude_desktop_config.json. Four options to set command:

  • NPX (Recommended)
  • Docker Hub Image
  • Local Node.js Installation
  • Local Docker Image

Example (NPX):

{
  "mcpServers": {
    "mongodb-lens": {
      "command": "/path/to/npx",
      "args": [
        "-y",
        "mongodb-lens@latest",
        "mongodb://your-connection-string"
      ]
    }
  }
}

Include env vars as shown in examples for customization.

MCP Inspector

MCP Inspector is a tool for testing and debugging MCP servers.

Run it as:

npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest

Default ports: proxy at 3000, web client at 5173.

Open browser at http://localhost:5173.

Other MCP Clients

MongoDB Lens should be usable with any MCP-compatible client.

Data Protection

Read-Only User Accounts

Use read-only MongoDB user accounts for safer querying that prevents writes or deletes.

Create users with the read role scoped to target databases.

Working with Database Backups

Use a backup MongoDB instance to safely test complex or destructive operations.

Create backups with mongodump and restore with mongorestore in another instance.

Point MongoDB Lens to the backup instance.

Data Flow Considerations

When using a remote LLM provider, your exact requests and some database data flow to the LLM.

Sensitive data can be exposed unless you filter it locally:

  • Use projections to exclude sensitive fields in queries.
  • Avoid adding aliases with passwords for remote LLM providers; define them in local config files.
  • For maximum safety, use a local MCP client with a local LLM model to keep data on your machine.

Confirmation for Destructive Operations

Destructive tools require a two-step confirmation with a 4-digit token that expires after 5 minutes.

Confirmed tools include:

  • drop-user, drop-index, drop-database, drop-collection
  • delete-document, bulk-operations (with delete)
  • rename-collection (when dropping targets)

You can bypass confirmation by setting:

CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS=true

Only do this in controlled, non-production environments.

Disabling Destructive Operations

Disable high-risk tools in config to ensure safety:

Example disable list for potentially destructive tools:

{
  "disabled": {
    "tools": [
      "drop-user",
      "drop-index",
      "drop-database",
      "drop-collection",
      "delete-document",
      "bulk-operations",
      "rename-collection"
    ]
  }
}

For read-only setup, disable all tools that modify data.

Use the enabled setting to explicitly allow certain tools only.

Tutorial

1. Start Sample Data Container

Run MongoDB sample data container with Docker:

docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6

Stop any container already using port 27017 before starting.

2. Import Sample Data

Download and import MongoDB sample datasets:

curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive
docker cp sampledata.archive mongodb-sampledata:/tmp/
docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive

The import includes multiple sample databases like sample_airbnb, sample_mflix, etc.

3. Connect MongoDB Lens

Install MongoDB Lens and configure your MCP client to connect via:

mongodb://localhost:27017

Example Claude Desktop configuration with NPX:

{
  "mcpServers": {
    "mongodb-lens": {
      "command": "/path/to/npx",
      "args": [
        "-y",
        "mongodb-lens@latest"
      ]
    }
  }
}

4. Example Queries

Try example natural language queries:

  • List all databases
  • What is the current database in use?
  • Switch to the sample_mflix database
  • Create a new database named test_db
  • Drop test_db (with confirmation)
  • List collections in the current database
  • Create and rename collections
  • Count documents, find documents with filters, and aggregate data
  • Perform schema analysis and generate validators
  • Insert, update, and delete documents (with confirmation)
  • Manage indexes and explain queries
  • Perform geospatial queries
  • Export data in JSON or CSV
  • Manage connections and aliases

5. Working With Confirmation Protection

For destructive commands, MongoDB Lens responds first with a confirmation token. You must resend the token to confirm the operation. This prevents accidental data loss.

Example:

  • Request: "Drop the collection named test_collection"
  • Response: Warning with confirmation code "9876"
  • Confirm by sending: "9876"
  • Operation completes.

Test Suite

Run tests to verify MongoDB Lens functionality.

Requires CONFIG_MONGO_URI environment variable with either a MongoDB URI or mongodb-memory-server.

Run tests with:

CONFIG_MONGO_URI=mongodb://localhost:27017 node mongodb-lens.test.js
CONFIG_MONGO_URI=mongodb-memory-server node mongodb-lens.test.js

Useful scripts:

  • npm test
  • npm run test:localhost
  • npm run test:in-memory
  • plus options to filter tests by name or group.

Disclaimer

MongoDB Lens is licensed under the MIT License.

It is not affiliated with or endorsed by MongoDB, Inc.

The software is provided as-is, for educational and experimental purposes only, and may contain errors. Use at your own risk.

Support

If you find MongoDB Lens useful, consider supporting development via:

Contributions help maintain and improve the project.