logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

mongo-lens-mcp-interface

A local Model Context Protocol (MCP) engine providing comprehensive interaction with MongoDB deployments via natural language processing, facilitating database querying, aggregation execution, performance tuning, and administrative tasks.

Author

mongo-lens-mcp-interface logo

furey

MIT License

Quick Info

GitHub GitHub Stars 187
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

mongodbapisdatabasesmongodb lensfurey mongodbmongodb databases

MongoDB Lens Interface for MCP

License Docker Hub Version NPM Version Buy Me a Coffee

MongoDB Lens functions as an accessible, local MCP server, offering full-spectrum access to operational MongoDB datasets. It leverages Large Language Models (LLMs) to interpret user intent, executing complex operations like data retrieval, pipeline construction, optimization analysis, and general administration.

Table of Contents

Initial Setup Guide

  • Deployment: Install MongoDB Lens via the instructions in the Installation section.
  • Configuration: Adjust initial settings as detailed in the Configuration chapter.
  • Client Linking: Configure your preferred MCP Client (e.g., Claude Desktop or clients supporting the protocol specifications like Cursor) to communicate with this server instance.
  • Exploration: Begin interacting with your MongoDB clusters using intuitive, human-readable requests via the Tutorial section.

Core Capabilities

This server exposes three main interaction vectors:

Execution Tools

Resources

  • collection-indexes: Metadata detailing index definitions for a collection.
  • collection-schema: The inferred or explicit schema structure of a collection.
  • collection-stats: Performance metrics and storage footprint for a collection.
  • collection-validation: Rules configured for document validation on write operations.
  • collections: A current inventory of collections in the active database.
  • database-triggers: Configuration details for change stream listeners and event handlers.
  • database-users: Listing of user accounts and their assigned roles within the current database scope.
  • databases: Full catalog of databases accessible to the connected user.
  • performance-metrics: Live telemetry and profiling data from the database server.
  • replica-status: Operational health and configuration of the replica set members.
  • server-status: Summary statistics and state of the MongoDB server process.
  • stored-functions: JavaScript functions persisted directly within the current database.

LLM Prompts

  • aggregation-builder: Guided, iterative construction of complex aggregation pipelines.
  • backup-strategy: Generates bespoke plans for data safeguarding and restoration.
  • data-modeling: Expert consultation on schema design tailored to specific application requirements.
  • database-health-check: Conducts a thorough assessment of database operational fitness and suggests improvements.
  • index-recommendation: Provides personalized index suggestions based on observed query load.
  • migration-guide: Step-by-step plans for upgrading MongoDB server versions.
  • mongo-shell: Generates idiomatic MongoDB shell commands complete with explanations.
  • multi-tenant-design: Architectural blueprints for scalable multi-tenant MongoDB deployments.
  • query-builder: Interactive coaching for constructing precise MongoDB retrieval statements.
  • query-optimizer: Targeted advice for accelerating sluggish queries.
  • schema-analysis: Deep-dive structural review of collections with suggested improvements.
  • schema-versioning: Strategies for managing iterative schema evolution in application code.
  • security-audit: Review of database security posture and hardening recommendations.
  • sql-to-mongodb: Translation service converting SQL queries into MongoDB aggregation syntax.

Ancillary Functions

Ancillary Functions: General Feature Overview

MongobDB Lens incorporates several supplementary utilities:

  • Configuration Interface (config-file): Customization via ~/.mongodb-lens.[jsonc|json] file location.
  • Runtime Parameterization (env-var-overrides): Settings can be altered through environment variables: process.env.CONFIG_*.
  • Safety Confirmation (confirmation-system): Mandatory dual-step verification for operations tagged as data-destructive.
  • Connection Pooling (multi-connections): Define and dynamically switch between named connection endpoints.
  • Component Exclusion (disabling-components): Fine-grained control over which tools, prompts, or resources are active.
  • Connection Stability: Automated recovery logic employing exponential backoff for connection failures.
  • Operation Guardrails: Configurable limits imposed on queries and operations to safeguard system resources.
  • Error Reporting: Adherence to standardized JSONRPC error codes and descriptive messaging.
  • Schema Deduction: High-efficiency, sampling-based schema inference engine.
  • Credential Sanitization: Obfuscation of sensitive password data within operational logs.
  • Memory Management: Proactive monitoring and resource reclamation during memory-intensive tasks.
  • Intelligent State Retention: Optimized caching strategy for collection metadata, indices, field names, and schema definitions.
  • Version Compatibility: Support maintained for both contemporary and legacy MongoDB server releases.

Ancillary Functions: Automatic Database Metadata

When MongoDB Lens provisions a new database structure, it injects a special collection named metadata. This collection houses a singular document detailing the context of the database's creation. This ensures that newly instantiated, otherwise empty databases persist within the MongoDB storage hierarchy.

Illustrative Metadata Record Structure
{
    "_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")
    }
}

After populating the database, the metadata collection can be safely purged using the drop-collection execution tool:

  • "Eliminate the metadata object from the newly created database"
    ➥ Invokes the drop-collection tool (requires confirmation)

Deployment Instructions

MongDB Lens deployment offers multiple paths:

Deployment: NPX

[!NOTE]
Requires a functional Node.js environment (version check recommended: Node.js v18.x or newer).

The most straightforward deployment method utilizes NPX.

First, ensure Node.js is available:

node --version # Should meet minimum requirement

Then, execute MongoDB Lens via NPX:

# Default URI: mongodb://localhost:27017
npx -y mongodb-lens

# Specifying a custom connection URI
npx -y mongodb-lens mongodb://custom-uri-here

# For bleeding-edge updates, specify @latest
npx -y mongodb-lens@latest

[!TIP]
If encountering resolution issues with npx, try clearing the local cache: npx clear-npx-cache before re-executing the primary command.

Deployment: Docker Hub Image

[!NOTE]
Requires a functional Docker daemon.

Verify Docker installation:

docker --version # Should meet minimum requirement

Execute MongoDB Lens using the official image:

# Default URI: mongodb://localhost:27017
docker run --rm -i --network=host furey/mongodb-lens

# Custom URI injection
docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string

# Force pull the latest image version before running
docker run --rm -i --network=host --pull=always furey/mongodb-lens

Deployment: From Source (Node.js Environment)

[!NOTE]
Requires Node.js and NPM/Yarn/pnpm environment setup.

  1. Obtain the source code: console git clone https://github.com/furey/mongodb-lens.git
  2. Change directory into the repository root: console cd /path/to/mongodb-lens
  3. Check Node.js version compatibility.
  4. Install project dependencies: console npm ci
  5. Initiate the server: ```console # Default startup node mongodb-lens.js

    Startup with specific connection URI

    node mongodb-lens.js mongodb://custom-uri ```

Deployment: From Source (Docker Build)

[!NOTE]
Requires Docker engine operational.

  1. Clone repository as above.
  2. Navigate to the project directory.
  3. Build the custom image: console docker build -t mongodb-lens .
  4. Execute the container: ```console # Default URI docker run --rm -i --network=host mongodb-lens

    Custom URI injection

    docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string ```

Deployment Validation Procedure

Confirm successful installation by sending the following standardized MCP message payload to the server's standard input (stdin):

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

A successful response will enumerate accessible databases, similar to this example:

{"result":{"contents":[{"uri":"mongodb://databases","text":"Databases (12):\n- admin (180.00 KB)\n- config (108.00 KB)\n- local (40.00 KB)\n- sample_airbnb (51.88 MB)\n..."}]},
"jsonrpc":"2.0","id":1}

Configuration Parameters

Configuration governs connection behavior, caching, and operational defaults. Settings are managed via:

Configuration: MongoDB Connection String

The primary connection point is specified as the first positional argument upon execution.

Format template:

mongodb://[user:pass@]host[:port][/db_name][?query_params]

If no URI is supplied, the engine defaults to a local connection attempt: mongodb://localhost:27017.

Configuration: Local Configuration File

Extensive customization is enabled through a local file, supporting both .json and .jsonc (JSON with comments) formats.

[!TIP]
Only properties requiring modification need inclusion; all unlisted properties inherit default values.

Comprehensive Configuration Template Example
{
  "mongoUri": "mongodb://localhost:27017",
  "connectionOptions": {
    "maxPoolSize": 20,
    "retryWrites": false,
    "connectTimeoutMS": 30000,
    "socketTimeoutMS": 360000,
    "heartbeatFrequencyMS": 10000,
    "serverSelectionTimeoutMS": 30000
  },
  "defaultDbName": "admin",
  "connection": {
    "maxRetries": 5,
    "maxRetryDelayMs": 30000,
    "reconnectionRetries": 10,
    "initialRetryDelayMs": 1000
  },
  "disabled": {
    "tools": [],
    "prompts": [],
    "resources": []
  },
  "enabled": {
    "tools": true,
    "prompts": true,
    "resources": true
  },
  "cacheTTL": {
    "stats": 15000,
    "fields": 30000,
    "schemas": 60000,
    "indexes": 120000,
    "collections": 30000,
    "serverStatus": 20000
  },
  "enabledCaches": [
    "stats", "fields", "schemas", "indexes", "collections", "serverStatus"
  ],
  "memory": {
    "enableGC": true,
    "warningThresholdMB": 1500,
    "criticalThresholdMB": 2000
  },
  "logLevel": "info",
  "disableDestructiveOperationTokens": false,
  "watchdogIntervalMs": 30000,
  "defaults": {
    "slowMs": 100,
    "queryLimit": 10,
    "allowDiskUse": true,
    "schemaSampleSize": 100,
    "aggregationBatchSize": 50
  },
  "security": {
    "tokenLength": 4,
    "tokenExpirationMinutes": 5,
    "strictDatabaseNameValidation": true
  },
  "tools": {
    "transaction": {
      "readConcern": "snapshot",
      "writeConcern": {
        "w": "majority"
      }
    },
    "bulkOperations": {
      "ordered": true
    },
    "export": {
      "defaultLimit": -1,
      "defaultFormat": "json"
    },
    "watchChanges": {
      "maxDurationSeconds": 60,
      "defaultDurationSeconds": 10
    },
    "queryAnalysis": {
      "defaultDurationSeconds": 10
    }
  }
}

Configuration files are sought in the user's home directory, prioritized as: ~/.mongodb-lens.jsonc then ~/.mongodb-lens.json.

The search path can be overridden by setting the CONFIG_PATH environment variable to the desired file location.

Configuration: File Generation Utility

You can bootstrap a configuration file using the built-in utility scripts:

# NPX Execution
npx -y mongodb-lens@latest config:create

# Local Node.js Execution
npm run config:create

# Overwrite existing configuration
npx -y mongodb-lens@latest config:create -- --force

If CONFIG_PATH is set, the utility will write the template output to that specified location.

Configuration: Multiple Connection Aliases

To manage connectivity to several MongoDB instances simultaneously, define the mongoUri setting as a map of connection labels to their respective URIs:

{
  "mongoUri": {
    "primary_cluster": "mongodb://localhost:27017",
    "analytics_shard": "mongodb://analytics-server:27018",
    "cloud_atlas": "mongodb+srv://user:pass@cluster.mongodb.net/prod_db"
  }
}

Connections can be switched via natural language (e.g., "Shift context to analytics_shard") or by supplying the alias name directly in the MCP client connection URI.

Configuration: Environment Variable Overrides

Settings defined via environment variables supersede any values present in the local configuration file. Variables must adhere to the following naming convention:

CONFIG_[CONFIGURATION_KEY_PATH_SNAKE_CASED_AND_UPPERCASED]

For instance, overriding the default query limit (defaults.queryLimit):

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

Configuration: Cross-Platform Environment Variables

To ensure environment variable consistency across disparate operating systems (Windows/Linux/macOS), utilize the cross-env package as a wrapper for your execution command.

Client Integration

MongoDB Lens is designed for interoperability with various MCP-aware clients:

Client Integration: Claude Desktop

Integration requires adding the MongoDB Lens execution command into the client's configuration file (claude_desktop_config.json). The command should point to your chosen deployment method (NPX, Docker, etc.).

Claude Desktop Configuration Options

Options detail how to structure the mcpServers entry in the configuration file, referencing the deployment method:

{
  "mcpServers": {
    "mongodb-lens": {
      "command": "/path/to/npx",
      "args": ["-y", "mongodb-lens@latest", "mongodb://your-connection-string"]
    }
  }
}
Option 2: Docker Hub Image
{
  "mcpServers": {
    "mongodb-lens": {
      "command": "docker",
      "args": ["run", "--rm", "-i", "--network=host", "--pull=always", "furey/mongodb-lens", "mongodb://your-connection-string"]
    }
  }
}

Client Integration: MCP Inspector for Debugging

Use the MCP Inspector tool to interactively test the server's responsiveness and capabilities. It establishes a local proxy layer.

Launch sequence example:

# Run Lens and Inspector concurrently (default ports)
npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest

Access the debugging interface via a web browser at http://localhost:5173.

Data Security Measures

Protecting data integrity and confidentiality during LLM interactions is paramount. Key strategies include:

Data Security Measures: Understanding the Data Transmission Pipeline

When interacting with remote LLMs (like those used by Claude Desktop), the data retrieved from MongoDB is transmitted back to the LLM engine for final response synthesis. This exposes your query results, including potentially sensitive fields, to the remote service unless explicitly prevented (see Projection).

Data Security Measures: Mandatory Confirmation for Write/Delete Operations

Operations that modify or remove data necessitate a two-stage verification process using time-sensitive tokens to prevent accidental execution. Tools requiring this safeguard include:

  • drop-collection, delete-document, drop-database, drop-user, drop-index, rename-collection, and destructive uses of bulk-operations.

Usage Walkthrough

This guide demonstrates connecting to a standard Dockerized MongoDB instance populated with MongoDB's official sample datasets.

  1. Setup Docker MongoDB Instance
  2. Load Sample Datasets
  3. Link MCP Client to Lens
  4. Execute Example Prompts
  5. Confirmation Workflow Example

Usage Walkthrough: 1. Setup Docker MongoDB Instance

Start a container mapped to the standard MongoDB port (27017):

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

Usage Walkthrough: 2. Load Sample Datasets

Download and inject the official sample archive into the running container to populate databases like sample_mflix and sample_airbnb.

Configure your client to point to the local server interface, typically using the default URI unless overridden in configuration or command line arguments.

Usage Walkthrough: 4. Execute Example Prompts

Test specific functionalities by issuing natural language commands. For instance:

  • "In the sample_mflix database, aggregate movies by their production year and count the total number of titles in each year" ➥ Utilizes aggregate-data tool

Usage Walkthrough: 5. Confirmation Workflow Example

When using tools like drop-collection, Lens will halt execution and require a security token (Confirmation code: XXXX) to be passed in a subsequent request before proceeding, ensuring deliberate action.

Automated Verification Suite

The integrated test suite is executed via Node.js and verifies tool efficacy, resource accessibility, and prompt generation quality. It requires a writable connection to a MongoDB instance (local or in-memory).

# Run tests against a local MongoDB instance
npm run test:localhost

MongDB Lens is provided under the permissive MIT License. It maintains no official affiliation with MongoDB, Inc. The implementation leverages advanced AI assistance; therefore, users should exercise caution, as occasional inaccuracies may be present. This utility is intended for experimental and educational exploration and is offered strictly 'as-is' without any warranty.

Community Support

Feedback, bug reports, and contributions are highly valued. Support the ongoing development via the provided links:

Buy Me a Coffee | GitHub Sponsorship

See Also

`