M

MongoDB透镜

@furey/mongodb-lens
1 Stars 583 次浏览 furey 更新于 2026-08-23

功能齐全的MCP服务器,用于MongoDB数据库分析。

MCP 服务配置

复制以下 JSON 到 OPClaw 或其他 MCP 客户端的配置文件中即可使用

{
  "mcpServers": {
    "mongodb-lens": {
      "args": [
        "run",
        "--rm",
        "-i",
        "--network=host",
        "mongodb-lens",
        "mongodb://your-connection-string"
      ],
      "command": "docker"
    }
  }
}

该服务需要配置环境变量:MONGODB_CONNECTION_STRING

服务介绍

MongoDB Lens

License
Docker Hub Version
NPM Version
Buy Me a Coffee

MongoDB Lens 是一个本地模型上下文协议 (MCP) 服务器,通过 LLMs 使用自然语言全面访问 MongoDB 数据库,以执行查询、运行聚合、优化性能等。

目录

快速开始

功能

工具

资源

提示

其他功能

其他功能:概览

MongoDB Lens 包含许多其他功能:

  • 配置文件: 通过 ~/.mongodb-lens.[jsonc|json] 自定义配置
  • 环境变量覆盖: 通过 process.env.CONFIG_* 覆盖配置设置
  • 确认系统: 对破坏性操作进行两步验证
  • 多连接: 定义并切换命名的 URI 别名
  • 组件禁用: 选择性地禁用工具、提示或资源
  • 连接韧性: 带有指数退避的自动重连
  • 查询保护措施: 可配置的限制和性能保护
  • 错误处理: 全面的 JSONRPC 错误代码和消息
  • 模式推断: 通过智能采样进行高效的模式分析
  • 凭证保护: 在日志中模糊处理连接字符串密码
  • 内存管理: 对大型操作进行自动监控和清理
  • 智能缓存: 为模式、索引、字段和集合优化缓存
  • 向后兼容: 支持现代版和旧版 MongoDB

其他功能:新数据库元数据

MongoDB Lens 会在它创建的每个数据库中插入一个 metadata 集合。

这个 metadata 集合存储一个包含上下文信息的文档,作为数据库来源的永久记录,同时确保新的且为空的数据库在 MongoDB 的存储系统中持续存在。

{
    "_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")
    }
}

一旦你向新数据库添加了自己的集合,你可以通过 drop-collection 工具安全地移除 metadata 集合:

  • "删除新数据库的 metadata 集合"
    ➥ 使用 drop-collection 工具(需要确认)

安装

MongoDB Lens 可以通过多种方式安装和运行:

安装:NPX

[!NOTE]
NPX 需要在你的系统上安装并运行 Node.js (建议使用 Volta)。

运行 MongoDB Lens 最简单的方法是使用 NPX。

首先,确保已安装 Node.js:

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

然后,通过 NPX 运行 MongoDB Lens:

# 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]
如果你在使用 npx 时遇到权限错误,可以尝试先运行 npx clear-npx-cache,然后再运行 npx -y mongodb-lens (这会清除缓存并重新下载包)。

安装:Docker Hub

[!NOTE]
Docker Hub 需要您在系统上安装并运行 Docker

首先,确保已安装 Docker:

docker --version # Ideally >= v27.x

然后,通过 Docker Hub 运行 MongoDB Lens:

# 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

安装:从源代码安装 Node.js

[!NOTE]
从源代码安装 Node.js 需要您在系统上安装并运行 Node.js(建议使用 Volta)。

  1. 克隆 MongoDB Lens 仓库:
    git clone https://github.com/furey/mongodb-lens.git
    
  2. 导航到克隆的仓库目录:
    cd /path/to/mongodb-lens
    
  3. 确保已安装 Node.js:
    node --version # 理想情况下 >= v22.x,但 MongoDB Lens 支持 >= v18.x
    
  4. 安装 Node.js 依赖项:
    npm ci
    
  5. 启动服务器:
    # 使用默认连接字符串 mongodb://localhost:27017
    node mongodb-lens.js
    
    # 使用自定义连接字符串
    node mongodb-lens.js mongodb://your-connection-string
    

安装:从源代码安装 Docker

[!NOTE]
从源代码安装 Docker 需要您在系统上安装并运行 Docker

  1. 克隆 MongoDB Lens 仓库:
    git clone https://github.com/furey/mongodb-lens.git
    
  2. 导航到克隆的仓库目录:
    cd /path/to/mongodb-lens
    
  3. 确保已安装 Docker:
    docker --version # 理想情况下 >= v27.x
    
  4. 构建 Docker 镜像:
    docker build -t mongodb-lens .
    
  5. 运行容器:
    # 使用默认连接字符串 mongodb://localhost:27017
    docker run --rm -i --network=host mongodb-lens
    
    # 使用自定义连接字符串
    docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string
    

安装验证

为了验证安装,请将以下 JSONRPC 消息粘贴并运行到服务器的 stdio 中:

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

服务器应该响应您的 MongoDB 实例中的数据库列表,例如:

{"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- sample_analytics (9.46 MB)\n- sample_geospatial (980.00 KB)\n- sample_guides (40.00 KB)\n- sample_mflix (108.90 MB)\n- sample_restaurants (7.73 MB)\n- sample_supplies (968.00 KB)\n- sample_training (40.85 MB)\n- sample_weatherdata (2.69 MB)"}]},"jsonrpc":"2.0","id":1}

MongoDB Lens 现已安装完毕,并准备好接受 MCP 请求。

安装:旧版本的 MongoDB

如果连接到版本 < 4.0 的 MongoDB 实例,最新版本的 MongoDB Lens 所使用的 MongoDB Node.js 驱动程序将不兼容。具体来说,MongoDB Node.js 驱动程序版本 4.0.0 及以上需要 MongoDB 版本 4.0 或更高。

要使用旧版本的 MongoDB 实例运行 MongoDB Lens,您需要使用 3.x 系列的 MongoDB Node.js 驱动程序版本(例如 3.7.4 与 MongoDB 3.6 兼容)。

旧版本的 MongoDB:从源代码运行

  1. 克隆 MongoDB Lens 仓库:
    git clone https://github.com/furey/mongodb-lens.git
    
  2. 进入克隆的仓库目录:
    cd /path/to/mongodb-lens
    
  3. 修改 package.json
    "dependencies": {
      ...
    -  "mongodb": "^6.15.0",  // 或者其他更新版本
    +  "mongodb": "^3.7.4",   // 或者与你的旧版 MongoDB 实例兼容的 3.x 版本
      ...
    }
    
  4. 安装 Node.js 依赖项:
    npm install
    
  5. 启动 MongoDB Lens:
    node mongodb-lens.js mongodb://older-mongodb-instance
    

这将使用与你的 MongoDB 实例兼容的旧版驱动程序。

[!NOTE]
你可能还需要回滚 这个提交 以添加 useNewUrlParseruseUnifiedTopology MongoDB 配置选项。

旧版 MongoDB:使用 NPX 或 Docker

如果你更喜欢使用 NPX 或 Docker,你需要使用一个带有兼容驱动程序的旧版 MongoDB Lens。

例如,MongoDB Lens 8.3.0 使用 MongoDB Node.js 驱动程序 3.7.4(见:package-lock.json)。

要使用 NPX 运行旧版 MongoDB Lens,请指定版本标签:

npx -y mongodb-lens@8.3.0

同样适用于 Docker:

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

配置

配置:MongoDB 连接字符串

服务器接受 MongoDB 连接字符串作为其唯一参数。

示例 NPX 用法:

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

MongoDB 连接字符串具有以下格式:

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

示例连接字符串:

  • 本地连接:
    mongodb://localhost:27017
  • 连接到 mydatabase 并从 admin 数据库中获取凭据:
    mongodb://username:password@hostname:27017/mydatabase?authSource=admin
  • 连接到 mydatabase 并包含各种其他选项:
    mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority

如果没有提供连接字符串,服务器将尝试通过本地连接进行连接。

配置:配置文件

MongoDB Lens 支持通过 JSON 配置文件进行广泛的自定义。

[!NOTE]
配置文件是可选的。如果没有提供配置文件,MongoDB Lens 将使用默认设置运行。

[!TIP]
你只需要在配置文件中包含你想自定义的设置。对于省略的值,MongoDB Lens 将使用默认设置。

[!TIP]
MongoDB Lens 支持 .json.jsonc(带注释的 JSON)配置文件格式。

{
  "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
    }
  }
}

默认情况下,MongoDB Lens 会在以下位置查找配置文件:

  • 首先查找 ~/.mongodb-lens.jsonc,如果不存在,则回退到
  • ~/.mongodb-lens.json

要自定义配置文件路径,请将环境变量 CONFIG_PATH 设置为你希望的文件路径。

NPX 使用示例:

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

Docker Hub 使用示例:

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

配置:配置文件生成

你可以使用 config:create 脚本自动生成配置文件:

# 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

该脚本提取上面的示例配置文件并将其保存到 ~/.mongodb-lens.jsonc

配置文件生成:自定义路径

你可以使用 CONFIG_PATH 环境变量指定自定义输出位置。

  • 如果 CONFIG_PATH 没有文件扩展名,则被视为目录并

相关 MCP 服务