A secure read/write Model Context Protocol server that lets Codex, Claude Code, OpenCode, and other MCP clients connect to MongoDB over Streamable HTTP/HTTPS.
- Validates and names MongoDB connections for reuse.
- Persists connection profiles across restarts in a local file with
0600permissions. - Lists configured connections, databases, and collections.
- Runs bounded
findqueries and read-only aggregation pipelines. - Inserts, updates, replaces, and deletes documents with explicit per-call limits.
- Runs bounded
$merge/$outpipelines and can drop an exactly confirmed collection or database. - 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.
Write access is explicit and follows the connected MongoDB user's permissions. The server does not expose arbitrary database commands and continues to block server-side JavaScript operators such as $where, $function, and $accumulator.
- Bun 1.3 or newer.
- A reachable MongoDB deployment and a connection URI.
- A MongoDB user with exactly the permissions the agents should have. Use
readWriteonly for databases the MCP may modify; drop operations require the corresponding MongoDB privileges.
git clone https://github.com/stock42/mcp-mongodb.git
cd mcp-mongodb
bun install
cp .env.example .env
bun run check
bun run start:sourceThe 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 startBun 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 returned, inserted, or selected by a bounded multi-write 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 32MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=replace-with-the-generated-value
MCP_ALLOWED_HOSTS=mcp.example.comUse 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.pemCodex 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 listIf 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 = 30Restart the Codex client after editing its configuration, then use /mcp to inspect the connection. See the official Codex MCP documentation.
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 listFor 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.
Export the token and add this entry to opencode.json or opencode.jsonc:
export MONGODB_MCP_TOKEN='replace-with-your-MCP_API_KEY'Verify it with opencode mcp list. See the official OpenCode MCP documentation.
| 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. |
mongodb_insert_one |
Insert one Extended JSON document. | Adds one document. |
mongodb_insert_many |
Insert a bounded ordered/unordered batch. | Adds documents. |
mongodb_update_one |
Update or upsert at most one matching document. | Modifies or creates a document. |
mongodb_update_many |
Update a bounded set of matching documents. | Modifies up to the requested limit. |
mongodb_replace_one |
Replace or upsert one complete document. | Replaces or creates a document. |
mongodb_delete_one |
Delete at most one matching document. | Permanently deletes a document. |
mongodb_delete_many |
Delete a bounded set of matching documents. | Permanently deletes up to the requested limit. |
mongodb_aggregate_write |
Run a bounded pipeline ending in $merge or $out. |
Writes to or replaces the exact output collection. |
mongodb_drop_collection |
Drop one exactly confirmed collection. | Permanently deletes its documents and indexes. |
mongodb_drop_database |
Drop one exactly confirmed database. | Permanently deletes the full database. |
mongodb_update_many scans matching documents in _id order. When has_more is true, pass its next_after_id value back as after_id to continue without selecting the same batch again. mongodb_delete_many naturally advances because each selected batch is removed.
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.
Insert a new order into shop.orders using Extended JSON.
Mark at most 50 pending jobs as queued and tell me if more remain.
Merge daily revenue totals into analytics.daily_revenue.
Drop the staging.tmp_import collection after confirming its exact name.
For BSON values in filters, use Extended JSON, for example:
{
"_id": { "$oid": "507f1f77bcf86cd799439011" },
"createdAt": { "$gte": { "$date": "2026-01-01T00:00:00.000Z" } }
}- A persisted MongoDB URI is stored unencrypted in the file configured by
MCP_MONGODB_STORE_PATH, protected with filesystem mode0600. 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. - Treat access to this MCP as write access to every namespace granted to that MongoDB account. Prefer separate credentials and deployments for production and development.
- Binding outside loopback fails at startup unless both Bearer authentication and explicit allowed hosts are configured.
- Requests with a browser
Originare rejected unless it is explicitly listed. - Tool annotations help clients understand side effects, but MongoDB permissions remain the security boundary.
bun run typecheck
bun test
bun run build
bun run checkWith an unauthenticated MongoDB server listening on 127.0.0.1:27017, run:
bun run test:integrationTo use another test deployment:
MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integrationbun 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
Servidor seguro de lectura y escritura para Model Context Protocol que permite a Codex, Claude Code, OpenCode y otros clientes MCP conectarse a MongoDB mediante Streamable HTTP/HTTPS.
- 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
findacotadas y pipelines de agregación de solo lectura. - Inserta, actualiza, reemplaza y borra documentos con límites explícitos por llamada.
- Ejecuta pipelines
$merge/$outacotados y puede eliminar una colección o base confirmada por nombre exacto. - 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 acceso de escritura es explícito y respeta los permisos del usuario MongoDB conectado. El servidor no expone comandos arbitrarios de base de datos y continúa bloqueando operadores de JavaScript del servidor como $where, $function y $accumulator.
- Bun 1.3 o superior.
- Un despliegue MongoDB accesible y su URI de conexión.
- Un usuario MongoDB con exactamente los permisos que deben tener los agentes. Usar
readWritesolo para las bases que el MCP pueda modificar; los drops requieren los privilegios MongoDB correspondientes.
git clone https://github.com/stock42/mcp-mongodb.git
cd mcp-mongodb
bun install
cp .env.example .env
bun run check
bun run start:sourceEndpoints 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 startBun 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 devueltos, insertados o seleccionados por una escritura múltiple acotada. |
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 32MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=reemplazar-con-el-valor-generado
MCP_ALLOWED_HOSTS=mcp.example.comEn 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.pemCodex 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 listSi 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 = 30Reiniciar el cliente luego de editar la configuración y usar /mcp para verificar la conexión. Ver la documentación MCP de Codex.
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 listPara 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.
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.
| 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. |
mongodb_insert_one |
Insertar un documento Extended JSON. | Agrega un documento. |
mongodb_insert_many |
Insertar un lote acotado, ordenado o no. | Agrega documentos. |
mongodb_update_one |
Actualizar o hacer upsert de un documento. | Modifica o crea un documento. |
mongodb_update_many |
Actualizar un conjunto acotado de documentos. | Modifica hasta el límite pedido. |
mongodb_replace_one |
Reemplazar o hacer upsert de un documento completo. | Reemplaza o crea un documento. |
mongodb_delete_one |
Borrar como máximo un documento. | Borra permanentemente un documento. |
mongodb_delete_many |
Borrar un conjunto acotado de documentos. | Borra permanentemente hasta el límite pedido. |
mongodb_aggregate_write |
Ejecutar un pipeline acotado terminado en $merge o $out. |
Escribe o reemplaza la colección de salida exacta. |
mongodb_drop_collection |
Eliminar una colección confirmada por nombre exacto. | Borra permanentemente documentos e índices. |
mongodb_drop_database |
Eliminar una base confirmada por nombre exacto. | Borra permanentemente la base completa. |
mongodb_update_many recorre los documentos coincidentes en orden de _id. Cuando has_more sea verdadero, enviar su next_after_id como after_id en la llamada siguiente para no seleccionar el mismo lote. mongodb_delete_many avanza naturalmente porque elimina cada lote seleccionado.
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.
Insertá una orden nueva en shop.orders usando Extended JSON.
Marcá como queued hasta 50 jobs pendientes e indicá si quedan más.
Fusioná los totales diarios en analytics.daily_revenue.
Eliminá staging.tmp_import después de confirmar el nombre exacto de la colección.
Para valores BSON en filtros usar Extended JSON, por ejemplo:
{
"_id": { "$oid": "507f1f77bcf86cd799439011" },
"createdAt": { "$gte": { "$date": "2026-01-01T00:00:00.000Z" } }
}- Una URI persistida se guarda sin cifrar en
MCP_MONGODB_STORE_PATH, protegida con modo0600. 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_KEYfuerte e independiente. - Tratar el acceso a este MCP como acceso de escritura a todo namespace permitido para esa cuenta MongoDB. Usar credenciales y despliegues separados para producción y desarrollo.
- El inicio falla fuera de loopback si no se configuraron autenticación Bearer y hosts permitidos.
- Todo request con
Originde 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.
bun run typecheck
bun test
bun run build
bun run checkCon MongoDB sin autenticación escuchando en 127.0.0.1:27017, ejecutar:
bun run test:integrationPara usar otro despliegue de prueba:
MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integrationbun 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
{ "$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}" } } } }