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

furey
Quick Info
Actions
Tags
MongoDB Lens Interface for MCP
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
- Core Capabilities
- Deployment Instructions
- Configuration Parameters
- Client Integration
- Data Security Measures
- Usage Walkthrough
- Automated Verification Suite
- Legal Notice
- Community Support
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
add-connection-alias: Establishes a named shortcut for a MongoDB Uniform Resource Identifier (URI).aggregate-data: Runs specified data processing pipelines.analyze-query-patterns: Inspects live query behavior to suggest performance enhancements.analyze-schema: Intelligently derives collection structures.bulk-operations: Executes multiple database actions in a single, optimized batch (requires user consent for modification).clear-cache: Flushes volatile memory caches to ensure data freshness.collation-query: Fetches documents adhering to specific linguistic sorting or comparison rules.compare-schemas: Audits structural variance between two distinct collections.connect-mongodb: Switches the operational endpoint to a newly supplied MongoDB URI.connect-original: Reverts the connection back to the initial URI established at server launch.count-documents: Tallies records matching specified query criteria.create-collection: Provisions a fresh collection, allowing custom settings.create-database: Initializes a new database, optionally setting it as the current context.create-index: Establishes new indexing structures for enhanced retrieval speed.create-timeseries: Deploys specialized time-series collections for chronological data.create-user: Provisions new database accounts with granular role assignments.current-database: Reports the currently active database context.delete-document: Removes documents satisfying given criteria (requires consent)).distinct-values: Extracts the set of unique values present in a specified field across documents.drop-collection: Deletes a collection entirely (requires consent)).drop-database: Purges an entire database (requires consent)).drop-index: Decommissions indexes from collections (requires consent)).drop-user: Revokes database user privileges (requires consent)).explain-query: Retrieves the execution plan details for a given query.export-data: Serializes query results into JSON or CSV formats.find-documents: Executes retrieval queries, supporting filtering, field selection (projection), and ordering.generate-schema-validator: Crafts JSON Schema definitions based on collection content.geo-query: Runs spatial queries utilizing MongoDB's geospatial operators.get-stats: Fetches operational metrics for databases or collections.gridfs-operation: Manages binary large objects (BLOBs) stored via GridFS buckets.insert-document: Adds one or more new records to collections.list-collections: Enumerates all collection names within the currently active database.list-connections: Displays the registry of defined MongoDB connection aliases.list-databases: Retrieves a list of all databases accessible by the current user.rename-collection: Changes the identifier name of an existing collection (confirmation needed if overwriting a target)).shard-status: Reports on the distribution and configuration of sharding across the cluster.text-search: Performs full-text searches against fields indexed for text search.transaction: Atomically commits a sequence of database modifications.update-document: Modifies records that meet the specified predicate.use-database: Swaps the active database context.validate-collection: Scans a collection for data structural anomalies.watch-changes: Establishes a change stream listener for real-time data event monitoring.
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 thedrop-collectiontool (requires confirmation)
Deployment Instructions
MongDB Lens deployment offers multiple paths:
- NPX Execution (Simplest)
- Docker Hub Image
- From Source (Node.js Environment)
- From Source (Docker Build)
- Installation Validation Procedure
- Legacy MongoDB Version Support
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 withnpx, try clearing the local cache:npx clear-npx-cachebefore 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.
- Obtain the source code:
console git clone https://github.com/furey/mongodb-lens.git - Change directory into the repository root:
console cd /path/to/mongodb-lens - Check Node.js version compatibility.
- Install project dependencies:
console npm ci -
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.
- Clone repository as above.
- Navigate to the project directory.
- Build the custom image:
console docker build -t mongodb-lens . -
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:
- Command Line Argument (URI)
- Local Configuration File
- File Generation Utility
- Multiple Connection Aliases
- Environment Variable Overrides
- Cross-Platform Environment Variables
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:
Option 1: NPX (Recommended)
{
"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:
- Employing Database Credentials with Minimum Required Privileges
- Operating Against Data Replicas/Backups
- Understanding the Data Transmission Pipeline
- Mandatory Confirmation for Write/Delete Operations
- Disabling Destructive Functionality
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 ofbulk-operations.
Usage Walkthrough
This guide demonstrates connecting to a standard Dockerized MongoDB instance populated with MongoDB's official sample datasets.
- Setup Docker MongoDB Instance
- Load Sample Datasets
- Link MCP Client to Lens
- Execute Example Prompts
- 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.
Usage Walkthrough: 3. Link MCP Client to Lens
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-datatool
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
Legal Notice
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:
