MongoDB MCP Server

MongoDB MCP Server

A secure, read-only MCP server that enables AI agents to connect to MongoDB, perform queries and aggregations, and manage connections.

Category
访问服务器

README

MongoDB MCP Server

English · Español

English

A secure, read-only Model Context Protocol server that lets Codex, Claude Code, OpenCode, and other MCP clients connect to MongoDB over Streamable HTTP/HTTPS.

Features

  • Validates and names MongoDB connections for reuse.
  • Persists connection profiles across restarts in a local file with 0600 permissions.
  • Lists configured connections, databases, and collections.
  • Runs bounded find queries and read-only aggregation pipelines.
  • Accepts MongoDB Extended JSON in query inputs and returns BSON values as Extended JSON.
  • Supports JSON and Markdown tool responses plus MCP structured content.
  • Applies query limits, operation timeouts, response-size limits, URI redaction, Host/Origin validation, and optional Bearer authentication.
  • Serves stateless MCP over HTTP or direct TLS with Bun.

The server intentionally does not expose insert, update, delete, $out, $merge, or server-side JavaScript operations.

Requirements

  • Bun 1.3 or newer.
  • A reachable MongoDB deployment and a connection URI.
  • A MongoDB user with only the permissions the agents should have. A read-only database user is strongly recommended.

Install and run

git clone https://github.com/stock42/mcp-mongodb.git
cd mcp-mongodb
bun install
cp .env.example .env
bun run check
bun run start:source

The default endpoints are:

  • MCP: http://127.0.0.1:3000/mcp
  • Health check: http://127.0.0.1:3000/health

For a built server:

bun run build
bun start

Configuration

Bun loads .env automatically. All settings are optional when running only on loopback.

Variable Default Description
MCP_HOST 127.0.0.1 HTTP bind address.
MCP_PORT 3000 HTTP port.
MCP_API_KEY unset Bearer token for /mcp; required outside loopback.
MCP_ALLOWED_HOSTS loopback hosts Comma-separated exact Host values; required outside loopback. Include the port when clients send one.
MCP_ALLOWED_ORIGINS empty Comma-separated browser origins. Requests containing an unlisted Origin are rejected.
MCP_MONGODB_STORE_PATH .data/connections.json Persistent connection-profile file.
MCP_MAX_QUERY_LIMIT 100 Maximum documents/items per tool call.
MCP_QUERY_TIMEOUT_MS 10000 Maximum query and connection timeout accepted by tools.
MCP_MAX_RESPONSE_CHARS 50000 Maximum serialized document payload before truncation.
MCP_TLS_CERT_PATH unset PEM certificate path; must be used with MCP_TLS_KEY_PATH.
MCP_TLS_KEY_PATH unset PEM private-key path; must be used with MCP_TLS_CERT_PATH.

Generate a token for remote access and configure the public hostname:

openssl rand -hex 32
MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=replace-with-the-generated-value
MCP_ALLOWED_HOSTS=mcp.example.com

Use HTTPS in production, either through a trusted reverse proxy or directly:

MCP_TLS_CERT_PATH=/absolute/path/to/fullchain.pem
MCP_TLS_KEY_PATH=/absolute/path/to/privkey.pem

Install in Codex

Codex CLI, the Codex IDE extension, and the ChatGPT desktop app share MCP configuration. Export the same token configured in the server and add its Streamable HTTP URL:

export MONGODB_MCP_TOKEN='replace-with-your-MCP_API_KEY'
codex mcp add mongodb \
  --url http://127.0.0.1:3000/mcp \
  --bearer-token-env-var MONGODB_MCP_TOKEN
codex mcp list

If MCP_API_KEY is unset for a loopback-only server, omit --bearer-token-env-var.

Manual ~/.codex/config.toml equivalent:

[mcp_servers.mongodb]
url = "http://127.0.0.1:3000/mcp"
bearer_token_env_var = "MONGODB_MCP_TOKEN"
required = true
tool_timeout_sec = 30

Restart the Codex client after editing its configuration, then use /mcp to inspect the connection. See the official Codex MCP documentation.

Install in Claude Code

Add the remote server at user scope. The following command resolves the token from your current shell:

export MONGODB_MCP_TOKEN='replace-with-your-MCP_API_KEY'
claude mcp add --transport http --scope user \
  --header "Authorization: Bearer ${MONGODB_MCP_TOKEN}" \
  mongodb http://127.0.0.1:3000/mcp
claude mcp list

For a project-scoped configuration that expands the token at runtime, add .mcp.json without committing the secret itself:

{
  "mcpServers": {
    "mongodb": {
      "type": "http",
      "url": "http://127.0.0.1:3000/mcp",
      "headers": {
        "Authorization": "Bearer ${MONGODB_MCP_TOKEN}"
      }
    }
  }
}

Run /mcp inside Claude Code to inspect server status. See the official Claude Code MCP documentation.

Install in OpenCode

Export the token and add this entry to opencode.json or opencode.jsonc:

export MONGODB_MCP_TOKEN='replace-with-your-MCP_API_KEY'
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "mongodb": {
      "type": "remote",
      "url": "http://127.0.0.1:3000/mcp",
      "enabled": true,
      "oauth": false,
      "headers": {
        "Authorization": "Bearer {env:MONGODB_MCP_TOKEN}"
      }
    }
  }
}

Verify it with opencode mcp list. See the official OpenCode MCP documentation.

Available tools

Tool Purpose Side effects
mongodb_connect Validate, ping, and optionally persist a named MongoDB URI. Updates the local connection store.
mongodb_list_connections List profiles with redacted endpoints and live status. None.
mongodb_disconnect Close a live client without deleting its profile. Runtime-only.
mongodb_remove_connection Delete a saved/transient profile and close its client. Deletes the local profile only.
mongodb_list_databases List visible databases with pagination. None.
mongodb_list_collections List/filter collections with pagination. None.
mongodb_find Run a bounded read-only find query. None.
mongodb_aggregate Run a bounded read-only aggregation. None.

Example prompts:

Connect as "analytics" using mongodb+srv://... and persist the profile.
List the databases available through analytics.
Find 20 active users in app.users, sorted by createdAt descending.
Group paid orders by currency and calculate total revenue.

For BSON values in filters, use Extended JSON, for example:

{
  "_id": { "$oid": "507f1f77bcf86cd799439011" },
  "createdAt": { "$gte": { "$date": "2026-01-01T00:00:00.000Z" } }
}

Security notes

  • A persisted MongoDB URI is stored unencrypted in the file configured by MCP_MONGODB_STORE_PATH, protected with filesystem mode 0600. Protect the host and backups accordingly.
  • The server never returns stored URIs or credentials; profile listings contain only scheme, host, and database path.
  • Use a dedicated least-privilege MongoDB account and a separate strong MCP_API_KEY.
  • Binding outside loopback fails at startup unless both Bearer authentication and explicit allowed hosts are configured.
  • Requests with a browser Origin are rejected unless it is explicitly listed.
  • Tool annotations help clients understand side effects, but MongoDB permissions remain the security boundary.

Development

bun run typecheck
bun test
bun run build
bun run check

Local MongoDB integration test

With an unauthenticated MongoDB server listening on 127.0.0.1:27017, run:

bun run test:integration

To use another test deployment:

MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integration

bun run check:all runs the regular quality checks followed by this integration. The test creates a uniquely named mcp_mongodb_test_<uuid> database, seeds it, exercises the real MCP HTTP endpoint, and removes both the database and temporary connection store in finally. Never point MONGODB_TEST_URI at a deployment where that reserved test prefix is used for real data.

Project layout:

src/
  connections/     Persistent profiles and MongoClient lifecycle
  tools/           MCP tool registration
  utils/           Query, pagination, redaction, and request safety
  config.ts        Environment parsing and deployment invariants
  http-server.ts   Bun HTTP/HTTPS adapter for Streamable HTTP
  mcp-server.ts    MCP server factory and instructions
  index.ts         Process entry point and graceful shutdown
test/              Unit and MCP protocol tests

Español

Servidor seguro y de solo lectura para Model Context Protocol que permite a Codex, Claude Code, OpenCode y otros clientes MCP conectarse a MongoDB mediante Streamable HTTP/HTTPS.

Funcionalidades

  • Valida y asigna nombres reutilizables a conexiones MongoDB.
  • Persiste perfiles entre reinicios en un archivo local con permisos 0600.
  • Lista conexiones configuradas, bases de datos y colecciones.
  • Ejecuta consultas find acotadas y pipelines de agregación de solo lectura.
  • Acepta Extended JSON de MongoDB y devuelve valores BSON como Extended JSON.
  • Ofrece respuestas JSON o Markdown, además de contenido estructurado MCP.
  • Aplica límites de resultados, timeout, tamaño de respuesta, redacción de URIs, validación Host/Origin y autenticación Bearer opcional.
  • Sirve MCP stateless sobre HTTP o TLS directo usando Bun.

El servidor no expone inserciones, actualizaciones, borrados, $out, $merge ni JavaScript ejecutado por MongoDB.

Requisitos

  • Bun 1.3 o superior.
  • Un despliegue MongoDB accesible y su URI de conexión.
  • Un usuario MongoDB con únicamente los permisos que deben tener los agentes. Se recomienda fuertemente un usuario de solo lectura.

Instalación y ejecución

git clone https://github.com/stock42/mcp-mongodb.git
cd mcp-mongodb
bun install
cp .env.example .env
bun run check
bun run start:source

Endpoints predeterminados:

  • MCP: http://127.0.0.1:3000/mcp
  • Salud: http://127.0.0.1:3000/health

Para ejecutar el artefacto compilado:

bun run build
bun start

Configuración

Bun carga .env automáticamente. Todas las variables son opcionales si el servidor escucha únicamente en loopback.

Variable Predeterminado Descripción
MCP_HOST 127.0.0.1 Dirección donde escucha HTTP.
MCP_PORT 3000 Puerto HTTP.
MCP_API_KEY sin definir Token Bearer para /mcp; obligatorio fuera de loopback.
MCP_ALLOWED_HOSTS hosts de loopback Valores Host exactos separados por comas; obligatorio fuera de loopback. Incluir puerto cuando el cliente lo envíe.
MCP_ALLOWED_ORIGINS vacío Orígenes de navegador separados por comas. Se rechaza todo Origin no listado.
MCP_MONGODB_STORE_PATH .data/connections.json Archivo de perfiles persistentes.
MCP_MAX_QUERY_LIMIT 100 Máximo de documentos/elementos por tool.
MCP_QUERY_TIMEOUT_MS 10000 Timeout máximo de conexión y consulta aceptado por las tools.
MCP_MAX_RESPONSE_CHARS 50000 Máximo del payload serializado antes de truncarlo.
MCP_TLS_CERT_PATH sin definir Certificado PEM; debe acompañarse de MCP_TLS_KEY_PATH.
MCP_TLS_KEY_PATH sin definir Clave privada PEM; debe acompañarse de MCP_TLS_CERT_PATH.

Para acceso remoto, generar un token y declarar el hostname público:

openssl rand -hex 32
MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=reemplazar-con-el-valor-generado
MCP_ALLOWED_HOSTS=mcp.example.com

En producción usar HTTPS mediante un reverse proxy confiable o TLS directo:

MCP_TLS_CERT_PATH=/ruta/absoluta/fullchain.pem
MCP_TLS_KEY_PATH=/ruta/absoluta/privkey.pem

Instalar en Codex

Codex CLI, la extensión de IDE y la app de escritorio de ChatGPT comparten la configuración MCP. Exportar el mismo token del servidor y registrar la URL Streamable HTTP:

export MONGODB_MCP_TOKEN='reemplazar-con-MCP_API_KEY'
codex mcp add mongodb \
  --url http://127.0.0.1:3000/mcp \
  --bearer-token-env-var MONGODB_MCP_TOKEN
codex mcp list

Si el servidor de loopback no usa MCP_API_KEY, omitir --bearer-token-env-var.

Configuración manual equivalente en ~/.codex/config.toml:

[mcp_servers.mongodb]
url = "http://127.0.0.1:3000/mcp"
bearer_token_env_var = "MONGODB_MCP_TOKEN"
required = true
tool_timeout_sec = 30

Reiniciar el cliente luego de editar la configuración y usar /mcp para verificar la conexión. Ver la documentación MCP de Codex.

Instalar en Claude Code

Agregar el servidor remoto con alcance de usuario. Este comando toma el token del shell actual:

export MONGODB_MCP_TOKEN='reemplazar-con-MCP_API_KEY'
claude mcp add --transport http --scope user \
  --header "Authorization: Bearer ${MONGODB_MCP_TOKEN}" \
  mongodb http://127.0.0.1:3000/mcp
claude mcp list

Para una configuración de proyecto que expanda el token al ejecutarse, agregar .mcp.json sin guardar el secreto:

{
  "mcpServers": {
    "mongodb": {
      "type": "http",
      "url": "http://127.0.0.1:3000/mcp",
      "headers": {
        "Authorization": "Bearer ${MONGODB_MCP_TOKEN}"
      }
    }
  }
}

Usar /mcp dentro de Claude Code para revisar el estado. Ver la documentación MCP de Claude Code.

Instalar en OpenCode

Exportar el token y agregar la configuración en opencode.json u opencode.jsonc:

export MONGODB_MCP_TOKEN='reemplazar-con-MCP_API_KEY'
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "mongodb": {
      "type": "remote",
      "url": "http://127.0.0.1:3000/mcp",
      "enabled": true,
      "oauth": false,
      "headers": {
        "Authorization": "Bearer {env:MONGODB_MCP_TOKEN}"
      }
    }
  }
}

Verificar con opencode mcp list. Ver la documentación MCP de OpenCode.

Tools disponibles

Tool Propósito Efectos
mongodb_connect Validar, comprobar y opcionalmente persistir una URI con nombre. Actualiza el almacén local.
mongodb_list_connections Listar perfiles con endpoints redactados y estado actual. Ninguno.
mongodb_disconnect Cerrar el cliente sin borrar el perfil. Solo en el proceso actual.
mongodb_remove_connection Borrar un perfil y cerrar su cliente. Borra únicamente el perfil local.
mongodb_list_databases Listar bases visibles con paginación. Ninguno.
mongodb_list_collections Listar/filtrar colecciones con paginación. Ninguno.
mongodb_find Ejecutar una consulta de lectura acotada. Ninguno.
mongodb_aggregate Ejecutar una agregación de solo lectura acotada. Ninguno.

Prompts de ejemplo:

Conectate como "analytics" usando mongodb+srv://... y persistí el perfil.
Listá las bases disponibles mediante analytics.
Buscá 20 usuarios activos en app.users, ordenados por createdAt descendente.
Agrupá las órdenes pagadas por moneda y calculá el ingreso total.

Para valores BSON en filtros usar Extended JSON, por ejemplo:

{
  "_id": { "$oid": "507f1f77bcf86cd799439011" },
  "createdAt": { "$gte": { "$date": "2026-01-01T00:00:00.000Z" } }
}

Seguridad

  • Una URI persistida se guarda sin cifrar en MCP_MONGODB_STORE_PATH, protegida con modo 0600. Proteger también el host y sus backups.
  • El servidor nunca devuelve URIs ni credenciales guardadas; solo muestra esquema, host y ruta de base de datos.
  • Usar una cuenta MongoDB dedicada con privilegios mínimos y una MCP_API_KEY fuerte e independiente.
  • El inicio falla fuera de loopback si no se configuraron autenticación Bearer y hosts permitidos.
  • Todo request con Origin de navegador se rechaza salvo que esté permitido explícitamente.
  • Las anotaciones de tools orientan al cliente, pero los permisos MongoDB siguen siendo la frontera de seguridad real.

Desarrollo

bun run typecheck
bun test
bun run build
bun run check

Prueba de integración con MongoDB local

Con MongoDB sin autenticación escuchando en 127.0.0.1:27017, ejecutar:

bun run test:integration

Para usar otro despliegue de prueba:

MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integration

bun run check:all ejecuta primero las validaciones normales y luego esta integración. La prueba crea una base única mcp_mongodb_test_<uuid>, carga fixtures, recorre el endpoint MCP HTTP real y elimina en finally tanto la base como el almacén temporal de conexiones. Nunca apuntar MONGODB_TEST_URI a un despliegue donde ese prefijo reservado contenga datos reales.

Estructura principal:

src/
  connections/     Persistencia de perfiles y ciclo de vida de MongoClient
  tools/           Declaración de tools MCP
  utils/           Seguridad de consultas, paginación y redacción
  config.ts        Variables de entorno e invariantes de despliegue
  http-server.ts   Adaptador HTTP/HTTPS de Bun para Streamable HTTP
  mcp-server.ts    Factory e instrucciones del servidor MCP
  index.ts         Entrada del proceso y apagado ordenado
test/              Pruebas unitarias y de protocolo MCP

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选