mongodb lens

Local 2025-08-31 23:54:52 0
Developer Tools @furey/mongodb-lens

Full featured MCP Server for MongoDB database analysis.


License Docker Hub Version NPM Version Buy Me a Coffee

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

Tools

Resources

Prompts

Other Features

Other Features: Overview

MongoDB Lens includes numerous other features:

  • Config File: Custom configuration via ~/.mongodb-lens.[jsonc|json]
  • Env Var Overrides: Override config settings via process.env.CONFIG_*
  • Confirmation System: Two-step verification for destructive operations
  • Multiple Connections: Define and switch between named URI aliases
  • Component Disabling: Selectively disable tools, prompts or resources
  • Connection Resilience: Auto-reconnection with exponential backoff
  • Query Safeguards: Configurable limits and performance protections
  • Error Handling: Comprehensive JSONRPC error codes and messages
  • Schema Inference: Efficient schema analysis with intelligent sampling
  • Credential Protection: Connection string password obfuscation in logs
  • Memory Management: Auto-monitoring and cleanup for large operations
  • Smart Caching: Optimized caching for schema, indexes, fields and collections
  • Backwards Compatible: Support both modern and legacy MongoDB versions

Other Features: New Database Metadata

MongoDB Lens inserts a metadata collection into each database it creates.

This metadata collection stores a single document containing contextual information serving as a permanent record of the database's origin while ensuring the new and otherwise empty database persists in MongoDB's storage system.

Example metadata document
{
    "_id" : ObjectId("67d5284463788ec38aecee14"),
    "created" : {
        "timestamp" : ISODate("2025-03-15T07:12:04.705Z"),
        "tool" : "MongoDB Lens v5.0.7",
        "user" : "anonymous"
    },
    "mongodb" : {
        "version" : "3.6.23",
        "connectionInfo" : {
            "host" : "unknown",
            "readPreference" : "primary"
        }
    },
    "database" : {
        "name" : "example_database",
        "description" : "Created via MongoDB Lens"
    },
    "system" : {
        "hostname" : "unknown",
        "platform" : "darwin",
        "nodeVersion" : "v22.14.0"
    },
    "lens" : {
        "version" : "5.0.7",
        "startTimestamp" : ISODate("2025-03-15T07:10:06.084Z")
    }
}

Once you've added your own collections to your new database, you can safely remove the metadata collection via the drop-collection tool:

  • "Drop the new database's metadata collection"
    ➥ Uses drop-collection tool (with confirmation)

Installation

MongoDB Lens can be installed and run in several ways:

Installation: NPX

[!NOTE]
NPX requires Node.js installed and running on your system (suggestion: use Volta).

The easiest way to run MongoDB Lens is using NPX.

First, ensure Node.js is installed:

node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible

Then, run MongoDB Lens via NPX:

# Using default connection string mongodb://localhost:27017
npx -y mongodb-lens

# Using custom connection string
npx -y mongodb-lens mongodb://your-connection-string

# Using "@latest" to keep the package up-to-date
npx -y mongodb-lens@latest

[!TIP]
If you encounter permissions errors with npx try running npx clear-npx-cache prior to running npx -y mongodb-lens (this clears the cache and re-downloads the package).

Installation: Docker Hub

[!NOTE]
Docker Hub requires Docker installed and running on your system.

First, ensure Docker is installed:

docker --version # Ideally >= v27.x

Then, run MongoDB Lens via Docker Hub:

# Using default connection string mongodb://localhost:27017
docker run --rm -i --network=host furey/mongodb-lens

# Using custom connection string
docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string

# Using "--pull" to keep the Docker image up-to-date
docker run --rm -i --network=host --pull=always furey/mongodb-lens

Installation: Node.js from Source

[!NOTE]
Node.js from source requires Node.js installed and running on your system (suggestion: use Volta).

  1. Clone the MongoDB Lens repository:
    git clone https://github.com/furey/mongodb-lens.git
  2. Navigate to the cloned repository directory:
    cd /path/to/mongodb-lens
  3. Ensure Node.js is installed:
    node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
  4. Install Node.js dependencies:
    npm ci
  5. Start the server:
    # Using default connection string mongodb://localhost:27017
    node mongodb-lens.js
    
    # Using custom connection string
    node mongodb-lens.js mongodb://your-connection-string

Installation: Docker from Source

[!NOTE]
Docker from source requires Docker installed and running on your system.

  1. Clone the MongoDB Lens repository:
    git clone https://github.com/furey/mongodb-lens.git
  2. Navigate to the cloned repository directory:
    cd /path/to/mongodb-lens
  3. Ensure Docker is installed:
    docker --version # Ideally >= v27.x
  4. Build the Docker image:
    docker build -t mongodb-lens .
  5. Run the container:
    # Using default connection string mongodb://localhost:27017
    docker run --rm -i --network=host mongodb-lens
    
    # Using custom connection string
    docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string

Installation Verification

To verify the installation, paste and run the following JSONRPC message into 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, for example:

{"result":{"contents":[{"uri":"mongodb://databases","text":"Databases (12):
- admin (180.00 KB)
- config (108.00 KB)
- local (40.00 KB)
- sample_airbnb (51.88 MB)
- sample_analytics (9.46 MB)
- sample_geospatial (980.00 KB)
- sample_guides (40.00 KB)
- sample_mflix (108.90 MB)
- sample_restaurants (7.73 MB)
- sample_supplies (968.00 KB)
- sample_training (40.85 MB)
- sample_weatherdata (2.69 MB)"}]},"jsonrpc":"2.0","id":1}

MongoDB Lens is now installed and ready to accept MCP requests.

Installation: Older MongoDB Versions

If connecting to a MongoDB instance with a version < 4.0, the MongoDB Node.js driver used by the latest version of MongoDB Lens will not be compatible. Specifically, MongoDB Node.js driver versions 4.0.0 and above require MongoDB version 4.0 or higher.

To use MongoDB Lens with older MongoDB instances, you need to use a MongoDB Node.js driver version from the 3.x series (e.g. 3.7.4 which is compatible with MongoDB 3.6).

Older MongoDB Versions: Running from Source

  1. Clone the MongoDB Lens repository:
    git clone https://github.com/furey/mongodb-lens.git
  2. Navigate to the cloned repository directory:
    cd /path/to/mongodb-lens
  3. Modify package.json:
    "dependencies": {
      ...
    -  "mongodb": "^6.15.0",  // Or whatever newer version is listed
    +  "mongodb": "^3.7.4",   // Or whatever 3.x version is compatible with your older MongoDB instance
      ...
    }
  4. Install Node.js dependencies:
    npm install
  5. Start MongoDB Lens:
    node mongodb-lens.js mongodb://older-mongodb-instance

This will use the older driver version compatible with your MongoDB instance.

[!NOTE]
You may also need to revert this commit to add back useNewUrlParser and useUnifiedTopology MongoDB configuration options.

Older MongoDB Versions: Using NPX or Docker

If you prefer to use NPX or Docker, you'll need to use an older version of MongoDB Lens that was published with a compatible driver.

For example, MongoDB Lens 8.3.0 uses MongoDB Node.js driver 3.7.4 (see: package-lock.json).

To run an older version of MongoDB Lens using NPX, specify the version tag:

npx -y [email protected]

Similarly for Docker:

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

Configuration

Configuration: MongoDB Connection String

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

Example NPX usage:

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

MongoDB connection strings have the following format:

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

Example connection strings:

  • Local connection:
    mongodb://localhost:27017
  • Connection to mydatabase with credentials from admin database:
    mongodb://username:password@hostname:27017/mydatabase?authSource=admin
  • Connection to mydatabase with various other options:
    mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority

If no connection string is provided, the server will attempt to connect via local connection.

Configuration: Config File

MongoDB Lens supports extensive customization via JSON configuration file.

[!NOTE]
The config file is optional. MongoDB Lens will run with default settings if no config file is provided.

[!TIP]
You only need to include the settings you want to customize in the config file. MongoDB Lens will use default settings for any omitted values.

[!TIP]
MongoDB Lens supports both .json and .jsonc (JSON with comments) config file formats.

Example configuration file
{
  "mongoUri": "mongodb://localhost:27017",         // Default MongoDB connection string or object of alias-URI pairs
  "connectionOptions": {
    "maxPoolSize": 20,                             // Maximum number of connections in the pool
    "retryWrites": false,                          // Whether to retry write operations
    "connectTimeoutMS": 30000,                     // Connection timeout in milliseconds
    "socketTimeoutMS": 360000,                     // Socket timeout in milliseconds
    "heartbeatFrequencyMS": 10000,                 // How often to ping servers for status
    "serverSelectionTimeoutMS": 30000              // Timeout for server selection
  },
  "defaultDbName": "admin",                        // Default database if not specified in URI
  "connection": {
    "maxRetries": 5,                               // Maximum number of initial connection attempts
    "maxRetryDelayMs": 30000,                      // Maximum delay between retries
    "reconnectionRetries": 10,                     // Maximum reconnection attempts if connection lost
    "initialRetryDelayMs": 1000                    // Initial delay between retries
  },
  "disabled": {
    "tools": [],                                   // Array of tools to disable or true to disable all
    "prompts": [],                                 // Array of prompts to disable or true to disable all
    "resources": []                                // Array of resources to disable or true to disable all
  },
  "enabled": {
    "tools": true,                                 // Array of tools to enable or true to enable all
    "prompts": true,                               // Array of prompts to enable or true to enable all
    "resources": true                              // Array of resources to enable or true to enable all
  },
  "cacheTTL": {
    "stats": 15000,                                // Stats cache lifetime in milliseconds
    "fields": 30000,                               // Fields cache lifetime in milliseconds
    "schemas": 60000,                              // Schema cache lifetime in milliseconds
    "indexes": 120000,                             // Index cache lifetime in milliseconds
    "collections": 30000,                          // Collections list cache lifetime in milliseconds
    "serverStatus": 20000                          // Server status cache lifetime in milliseconds
  },
  "enabledCaches": [                               // List of caches to enable
    "stats",                                       // Statistics cache
    "fields",                                      // Collection fields cache
    "schemas",                                     // Collection schemas cache
    "indexes",                                     // Collection indexes cache
    "collections",                                 // Database collections cache
    "serverStatus"                                 // MongoDB server status cache
  ],
  "memory": {
    "enableGC": true,                              // Whether to enable garbage collection
    "warningThresholdMB": 1500,                    // Memory threshold for warnings
    "criticalThresholdMB": 2000                    // Memory threshold for cache clearing
  },
  "logLevel": "info",                              // Log level (info or verbose)
  "disableDestructiveOperationTokens": false,      // Whether to skip confirmation for destructive ops
  "watchdogIntervalMs": 30000,                     // Interval for connection monitoring
  "defaults": {
    "slowMs": 100,                                 // Threshold for slow query detection
    "queryLimit": 10,                              // Default limit for query results
    "allowDiskUse": true,                          // Allow operations to use disk for large datasets
    "schemaSampleSize": 100,                       // Sample size for schema inference
    "aggregationBatchSize": 50                     // Batch size for aggregation operations
  },
  "security": {
    "tokenLength": 4,                              // Length of confirmation tokens
    "tokenExpirationMinutes": 5,                   // Expiration time for tokens
    "strictDatabaseNameValidation": true           // Enforce strict database name validation
  },
  "tools": {
    "transaction": {
      "readConcern": "snapshot",                   // Read concern level for transactions
      "writeConcern": {
        "w": "majority"                            // Write concern for transactions
      }
    },
    "bulkOperations": {
      "ordered": true                              // Whether bulk operations execute in order
    },
    "export": {
      "defaultLimit": -1,                          // Default limit for exports (-1 = no limit)
      "defaultFormat": "json"                      // Default export format (json or csv)
    },
    "watchChanges": {
      "maxDurationSeconds": 60,                    // Maximum duration for change streams
      "defaultDurationSeconds": 10                 // Default duration for change streams
    },
    "queryAnalysis": {
      "defaultDurationSeconds": 10                 // Default duration for query analysis
    }
  }
}

By default, MongoDB Lens looks for the config file at:

  • ~/.mongodb-lens.jsonc first, then falls back to
  • ~/.mongodb-lens.json if the former doesn't exist

To customize the config file path, set the environment variable CONFIG_PATH to the desired file path.

Example NPX usage:

CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest

Example Docker Hub usage:

docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens

Configuration: Config File Generation

You can generate a configuration file automatically using the config:create script:

# NPX Usage (recommended)
npx -y mongodb-lens@latest config:create

# Node.js Usage
npm run config:create

# Force overwrite existing files
npx -y mongodb-lens@latest config:create -- --force
npm run config:create -- --force

This script extracts the example configuration file above and saves it to: ~/.mongodb-lens.jsonc

Config File Generation: Custom Path

You can specify a custom output location using the CONFIG_PATH environment variable.

  • If CONFIG_PATH has no file extension, it's treated as a directory an