
Mongodb Mcp Server
io.github.mongodb-js由 GitHub 账号 mongodb-js 发布v3.2.2更新于 Nov 4, 2026
MongoDB Model Context Protocol Server
概览
MongoDB 官方 MCP 服务器,让助手在本机进程中查询和管理 MongoDB 数据库与 Atlas 项目。
- 可以做什么
- 查询与查看数据:find、count、聚合、explain,列出数据库与集合,读取模式、索引和存储大小
- 修改数据与结构:插入、更新、删除文档,创建、重命名和删除集合,创建和删除索引,删除数据库
- 管理连接:连接、断开并列出活动连接,包括 Atlas 集群和 Atlas Local 部署
- 管理 Atlas:列出组织、项目、集群和数据库用户,创建集群与项目,管理访问列表,暂停或恢复集群,读取性能建议和告警
- 创建和查看 Atlas Stream Processing 工作区、连接与处理器
- 检索 MongoDB Assistant 知识源,并将查询结果导出为 EJSON 文件
- 适用场景
- 适合希望助手直接探查或操作 MongoDB 部署的场景,例如查看模式与索引、运行查询和聚合,或创建和检查 Atlas 集群,而不必手工搬运数据。
- 运行要求
- 通过 npx(Node.js 22.13 或更高版本)或 Docker 镜像在本机运行。需要 MongoDB 连接字符串(MDB_MCP_CONNECTION_STRING 或 MDB_MCP_CONNECTION_STRINGS),或用于 Atlas 工具的 Atlas 服务账号凭据(MDB_MCP_API_CLIENT_ID 与 MDB_MCP_API_CLIENT_SECRET)。需能访问数据库或 Atlas 的网络。
安装
在 SourceWeft 中
- 打开 控制台中的 Mongodb Mcp Server,将其添加到工作区。
- 为需要使用其工具的对话启用该服务。
Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。
其他 MCP 客户端
参照 仓库 中的启动说明。
README
[Install in VS Code] [Install in Cursor]
MongoDB MCP Server
A Model Context Protocol server for interacting with MongoDB Databases and MongoDB Atlas.
Quick Start
Using the official MongoDB plugins for AI agents
MongoDB MCP Server comes bundled with the official MongoDB plugins for AI agents. The following plugins are available:
mongodb-atlas — connects to the MongoDB-hosted Atlas MCP server over OAuth. This does not require you to run anything locally, and is the recommended way to connect to MongoDB Atlas from your AI agent:
- Cursor: marketplace
- VSCode: Open the Extensions view (
⇧⌘X/Ctrl+Shift+X), search for@agentPlugins, and installmongodb-atlas. - Claude: marketplace
- Codex: Open
/pluginsand installmongodb-atlas. - GitHub Copilot CLI: Run
copilot plugin install mongodb-atlas. - Grok: Open
/marketplacein Grok Build and installmongodb-atlas.
mongodb — runs the MongoDB MCP server locally and connects to any self-managed deployment:
- Cursor: marketplace
- Claude: marketplace
- Gemini: marketplace
- Codex: Run
codex plugin marketplace add mongodb/agent-skills, then open/pluginsand installmongodb. - GitHub Copilot CLI: Run
copilot plugin install mongodb. - Grok: Open
/marketplacein Grok Build and installmongodb.
Using the setup script
You can manually set up the local MCP server by running the following command:
This will guide you through an interactive setup process, including configuring your MongoDB connection string or Atlas API credentials.
For more advanced setup options, see the Manual Setup section below.
Using the MongoDB MCP Server setup skill
You can add and use the MongoDB MCP Server setup skill to configure your local MCP server using an AI agent.
Using manual configuration
See Manual Setup for instructions on how to manually configure the MongoDB MCP Server.
📚 Table of Contents
- 🚀 Getting Started
- 🛠️ Supported Tools
- 📄 Supported Resources
- ⚙️ Configuration
- 🚀 Deploy on Public Clouds
- 🤝 Contributing
Prerequisites
[!NOTE] Node 20.x support is deprecated and will be removed in a future release. Please upgrade to Node 22.13 or later. See https://nodejs.org/en/blog/migrations/v20-to-v22 for migration details.
-
Node.js
- At least v22.13.0. Check with
node -v.
- At least v22.13.0. Check with
-
A MongoDB connection string or Atlas API credentials.
- Service Accounts Atlas API credentials are required to use the Atlas tools. You can create a service account in MongoDB Atlas and use its credentials for authentication. See Atlas API Access for more details.
- If you have a MongoDB connection string, you can use it directly to connect to your MongoDB instance.
Manual Setup
🔒 Security Recommendation 1: When using Atlas API credentials, be sure to assign only the minimum required permissions to your service account. See Atlas API Permissions for details.
🔒 Security Recommendation 2: For enhanced security, we strongly recommend using environment variables to pass sensitive configuration such as connection strings and API credentials instead of command line arguments. Command line arguments can be visible in process lists and logged in various system locations, potentially exposing your secrets. Environment variables provide a more secure way to handle sensitive information.
Most MCP clients require a configuration file to be created or modified to add the MCP server.
Note: The configuration file syntax can be different across clients. Please refer to the following links for the latest expected syntax:
Default Safety Notice: All examples below include
--readOnlyby default to ensure safe, read-only access to your data. Remove--readOnlyif you need to enable write operations.
Option 1: Connection String
You can pass your connection string via environment variables, make sure to use a valid username and password.
NOTE: The connection string can be configured to connect to any MongoDB cluster, whether it's a local instance or an Atlas cluster.
Option 2: Connect to the MongoDB Atlas-Managed MCP Server
When working with MongoDB Atlas, the recommended approach is to install the mongodb-atlas plugin for your AI agent, which handles OAuth authentication automatically.
For manual configuration, see the client-specific instructions for setting up the Atlas Remote MCP server with OAuth. Alternatively, you can connect using the mongodb-atlas-mcp-remote package with Service Account credentials — see the package README for setup instructions.
Note: You cannot authenticate to the remote MongoDB MCP server using a static API key over HTTP. You must either:
- Use a client that supports the OAuth flow.
- Use the
mongodb-atlas-mcp-remotestdio server, which you can authenticate into using the staticMDB_MCP_API_CLIENT_IDandMDB_MCP_API_CLIENT_SECRETenvironment variables.
To connect with the mongodb-atlas-mcp-remote stdio server using Service Account credentials, add it to your client's MCP configuration:
Option 3: Atlas API Credentials
Use your Atlas API Service Accounts credentials. Must follow all the steps in Atlas API Access section.
Option 4: Standalone Service using environment variables and command line arguments
You can source environment variables defined in a config file or explicitly set them like we do in the example below and run the server via npx.
💡 Platform Note: The examples above use Unix/Linux/macOS syntax. For Windows users, see Environment Variables for platform-specific instructions.
- For a complete list of configuration options see Configuration Options
- To configure your Atlas Service Accounts credentials please refer to Atlas API Access
- Connection String via environment variables in the MCP file example
- Atlas API credentials via environment variables in the MCP file example
Option 5: Using Docker
You can run the MongoDB MCP Server in a Docker container, which provides isolation and doesn't require a local Node.js installation.
Run with Environment Variables
You may provide either a MongoDB connection string OR Atlas API credentials:
Option A: No configuration
Option B: With MongoDB connection string
💡 Platform Note: The examples above use Unix/Linux/macOS syntax. For Windows users, see Environment Variables for platform-specific instructions.
Option C: With Atlas API credentials
💡 Platform Note: The examples above use Unix/Linux/macOS syntax. For Windows users, see Environment Variables for platform-specific instructions.
Docker in MCP Configuration File
Without options:
With connection string:
With Atlas API credentials:
HTTP Compatibility
For custom HTTP clients and hosts, see the library guide's HTTP compatibility requirements, including protocol headers, redirects, legacy sessions, and request size limits.
🛠️ Supported Tools
Tool List
MongoDB Database Tools
aggregate- Run an aggregation against a MongoDB collectionaggregate-db- Run an aggregation against a MongoDB databasecollection-indexes- Describe the indexes for a collectioncollection-schema- Describe the schema for a collectioncollection-storage-size- Gets the size of the collectionconnect- Connect to a MongoDB instancecount- Gets the number of documents in a MongoDB collection using db.collection.count() and query as an optional filter parametercreate-collection- Creates a new collection in a database. If the database doesn't exist, it will be created automatically.create-index- Create an index for a collectiondb-stats- Returns statistics that reflect the use state of a single databasedelete-many- Removes all documents that match the filter from a MongoDB collectiondisconnect- Close a MongoDB connection and revoke its connectionId.drop-collection- Removes a collection or view from the database. The method also removes any indexes associated with the dropped collection.drop-database- Removes the specified database, deleting the associated data filesdrop-index- Drop an index for the provided database and collection.explain- Returns statistics describing the execution of the winning plan chosen by the query optimizer for the evaluated methodexport- Export a query or aggregation results in the specified EJSON format.find- Run a find query against a MongoDB collectioninsert-many- Insert an array of documents into a MongoDB collection. If the list of documents is above com.mongodb/maxRequestPayloadBytes, consider inserting them in batches.list-collections- List all collections for a given databaselist-connections- List the active MongoDB connections and their connectionIds. Use this to find a connectionId established earlier.list-databases- List all databases for a MongoDB connectionmongodb-logs- Returns the most recent logged mongod eventsrename-collection- Renames a collection in a MongoDB databaseupdate-many- Updates all documents that match the specified filter for a collection. If the list of documents is above com.mongodb/maxRequestPayloadBytes, consider updating them in batches.
MongoDB Atlas Tools
atlas-connect-cluster- Connect to MongoDB Atlas cluster and get back a connectionId to pass to the other MongoDB tools. Each call establishes a new, independent connection — multiple connections can be active at the same time.atlas-create-access-list- Allow Ip/CIDR ranges to access your MongoDB Atlas clusters.atlas-create-cluster- Create a MongoDB Atlas cluster (M10–M80, replica set or single shard). Compute autoscaling is enabled by default: min instance size is set to the selected instance size, max is set two tiers above. Disk autoscaling is always enabled. Encryption at rest with customer-managed keys (CMK) is supported, the CMK provider must already have a valid encryption at rest configuration in the project. The tool returns immediately, use the atlas-inspect-cluster tool to poll the cluster state for readiness (state: IDLE). Connection strings are unavailable until the cluster reaches IDLE state.atlas-create-db-user- Create an MongoDB Atlas database useratlas-create-free-cluster- Create a free MongoDB Atlas clusteratlas-create-project- Create a MongoDB Atlas projectatlas-get-performance-advisor- Get MongoDB Atlas performance advisor recommendations and suggestions, which includes the operations: suggested indexes, drop index suggestions, schema suggestions, and a sample of the most recent (max 50) slow query logsatlas-get-regions- List supported MongoDB Atlas regions for a cloud provider.atlas-inspect-access-list- Inspect Ip/CIDR ranges with access to your MongoDB Atlas clusters.atlas-inspect-cluster- Inspect metadata of a MongoDB Atlas clusteratlas-list-alerts- List triggered alerts for a MongoDB Atlas project. These are alerts Atlas has raised, not the alert configurations that define them. Defaults to OPEN alerts; set status to TRACKING or CLOSED to see others.atlas-list-clusters- List MongoDB Atlas clustersatlas-list-db-users- List MongoDB Atlas database usersatlas-list-orgs- List MongoDB Atlas organizationsatlas-list-projects- List MongoDB Atlas projects.atlas-load-sample-dataset- Load a MongoDB sample dataset into an Atlas cluster, or check the status of a previously-initiated load. To start a new load, provideclusterName— the load runs asynchronously and the response includes ajobIdand initial state. To check progress, call this tool again withjobId(sample dataset loads typically take 1–5 minutes). State can be WORKING, COMPLETED, or FAILED.atlas-pause-resume-cluster- Pause or resume a dedicated (M10+) MongoDB Atlas cluster.atlas-streams-build- Create Atlas Stream Processing resources. Use this tool for 'set up a Kafka pipeline', 'create a workspace', 'add a connection', or 'deploy a processor'. Use resource='workspace' to create a new workspace (specify cloud provider, region, and tier). Use resource='connection' to add a data source or sink to an existing workspace. Use resource='processor' to deploy a stream processor with a pipeline. Use resource='privatelink' to set up private networking. Typical workflow: create workspace → add connections → deploy processor.atlas-streams-discover- Discover and inspect Atlas Stream Processing resources. Also use for 'why is my processor failing', 'what workspaces do I have', 'show processor stats', or 'check processor health'. Use 'list-workspaces' to see all workspaces in a project. Use inspect actions for details on a specific resource. Use 'diagnose-processor' for a combined health report including state, stats, connection health, and recent errors. Use 'get-networking' for PrivateLink and account details.atlas-streams-manage- Manage Atlas Stream Processing resources: start/stop processors, modify pipelines, update configurations. Also use for 'change the pipeline', 'scale up my processor', or 'update my workspace tier'. Common workflow: action='stop-processor' → action='modify-processor' → action='start-processor'. Useatlas-streams-discoverwith action 'inspect-processor' to check state before managing.atlas-streams-teardown- Delete Atlas Stream Processing resources. Also use for 'remove my workspace', 'disconnect a source', 'delete all processors', or 'clean up my streams environment'. Performs basic safety checks before deletion: summarizes counts of processors and connections, highlights connections referenced by processors where possible, and surfaces API errors if processors are still running when deletion is attempted. Useatlas-streams-discoverto review resources before deleting.atlas-upgrade-cluster- Upgrade or scale a MongoDB Atlas cluster. Free and Flex clusters can be upgraded to Flex or M10 Dedicated. Dedicated clusters can be scaled to a different instance size, and compute autoscaling settings can be updated. When scaling a Dedicated cluster, at least one of targetTier, computeAutoScaling, minInstanceSize, or maxInstanceSize must be provided. Compute autoscaling defaults to enabled when upgrading to M10 Dedicated: min instance size is set to the selected instance size, max is set two tiers above, unless overridden. Note to LLM: If provider and region are not already known, ask for both together in a single question before calling this tool. Use atlas-get-regions to resolve natural-language locations or uncertain region codes before calling this tool.
NOTE: atlas tools are only available when you set credentials on configuration section.
MongoDB Atlas Local Tools
atlas-local-connect-deployment- Connect to a MongoDB Atlas Local deployment and get back a connectionId to pass to the other MongoDB toolsatlas-local-create-deployment- Create a MongoDB Atlas local deployment. Default image is preview. When the user does not specify an image tag, inform them that preview is used by default and provide this link for more information: https://hub.docker.com/r/mongodb/mongodb-atlas-localatlas-local-delete-deployment- Delete a MongoDB Atlas local deploymentatlas-local-list-deployments- List MongoDB Atlas local deployments
MongoDB Assistant Tools
list-knowledge-sources- List available data sources in the MongoDB Assistant knowledge base. Use this to explore available data sources or to find search filter parameters to use in search-knowledge.search-knowledge- Search for information in the MongoDB Assistant knowledge base. This includes official documentation, curated expert guidance, and other resources provided by MongoDB. Supports filtering by data source and version.
📄 Supported Resources
config- Server configuration, supplied by the user either as environment variables or as startup arguments with sensitive parameters redacted. The resource can be accessed under URIconfig://config.debug- Debugging information for MongoDB connectivity issues. Tracks the last connectivity attempt and error information. The resource can be accessed under URIdebug://mongodb.exported-data- A resource template to access the data exported using the export tool. The template can be accessed under URIexported-data://{exportName}whereexportNameis the unique name for an export generated by the export tool.
Configuration
🔒 Security Best Practice: We strongly recommend using environment variables for sensitive configuration such as API credentials (
MDB_MCP_API_CLIENT_ID,MDB_MCP_API_CLIENT_SECRET) and connection strings (MDB_MCP_CONNECTION_STRING) instead of command-line arguments. Environment variables are not visible in process lists and provide better security for your sensitive data.
The MongoDB MCP Server can be configured using multiple methods, with the following precedence (highest to lowest):
- Command-line arguments
- Environment variables
- Configuration File
Configuration Options
Logger Options
The loggers configuration option controls where logs are sent. You can specify one or more logger types as a comma-separated list. The available options are:
mcp: Sends logs to the MCP client (if supported by the client/transport).disk: Writes logs to disk files. Log files are stored in the log path (seelogPathabove).stderr: Outputs logs to standard error (stderr), useful for debugging or when running in containers.
Default: disk,mcp (logs are written to disk and sent to the MCP client).
You can combine multiple loggers, e.g. --loggers disk stderr or export MDB_MCP_LOGGERS="mcp,stderr".
Example: Set logger via environment variable
💡 Platform Note: For Windows users, see Environment Variables for platform-specific instructions.
Example: Set logger via command-line argument
Log File Location
When using the disk logger, log files are stored in:
- Windows:
%LOCALAPPDATA%\mongodb\mongodb-mcp\.app-logs - macOS/Linux:
~/.mongodb/mongodb-mcp/.app-logs
You can override the log directory with the logPath option.
🔒 Security Guideline: The user account running the MCP server must have both read and write permissions to the
logPathdirectory. Ensure this directory is properly secured with appropriate file system permissions to prevent unauthorized access to log files.
Disabled Tools
You can disable specific tools or categories of tools by using the disabledTools option. This option accepts an array of strings,
where each string can be a tool name, operation type, or category.
The way the array is constructed depends on the type of configuration method you use:
- For environment variable configuration, use a comma-separated string:
export MDB_MCP_DISABLED_TOOLS="create,update,delete,atlas,collectionSchema". - For command-line argument configuration, use a space-separated string:
--disabledTools create update delete atlas collectionSchema.
Categories of tools:
atlas- MongoDB Atlas tools, such as list clusters, create cluster, etc.mongodb- MongoDB database tools, such as find, aggregate, etc.
Operation types:
create- Tools that create resources, such as create cluster, insert document, etc.update- Tools that update resources, such as update document, rename collection, etc.delete- Tools that delete resources, such as delete document, drop collection, etc.read- Tools that read resources, such as find, aggregate, list clusters, etc.metadata- Tools that read metadata, such as list databases/collections/indexes, infer collection schema, etc.connect- Tools that allow you to connect or switch the connection to a MongoDB instance. If this is disabled, you will need to provide a connection string through the config when starting the server.
Require Confirmation
If your client supports elicitation, you can set the MongoDB MCP server to request user confirmation before executing certain tools.
When a tool is marked as requiring confirmation, the server will send an elicitation request to the client. The client with elicitation support will then prompt the user for confirmation and send the response back to the server. If the client does not support elicitation, the tool will execute without confirmation.
You can set the confirmationRequiredTools configuration option to specify the names of tools which require confirmation. By default, the following tools have this setting enabled: drop-database, drop-collection, delete-many, drop-index, atlas-create-db-user, atlas-create-access-list, atlas-streams-manage, atlas-streams-teardown.
In addition, the aggregate and aggregate-db tools always request confirmation before running a pipeline that contains a $out or $merge stage, regardless of whether they appear in confirmationRequiredTools. Those stages write to a collection — $out replaces its contents entirely — so this confirmation names the affected collection and what will happen to it. Pipelines without a write stage are not confirmed.
Adding either tool to confirmationRequiredTools is broader: every call is then confirmed up front with the standard tool-level message, and a write stage does not raise a second prompt.
Read-Only Mode
The readOnly configuration option allows you to restrict the MCP server to only use tools with "read", "connect", and "metadata" operation types. When enabled, all tools that have "create", "update" or "delete" operation types will not be registered with the server.
This is useful for scenarios where you want to provide access to MongoDB data for analysis without allowing any modifications to the data or infrastructure.
You can enable read-only mode using:
- Environment variable:
export MDB_MCP_READ_ONLY=true - Command-line argument:
--readOnly
💡 Platform Note: For Windows users, see Environment Variables for platform-specific instructions.
When read-only mode is active, you'll see a message in the server logs indicating which tools were prevented from registering due to this restriction.
Index Check Mode
The indexCheck configuration option allows you to enforce that query operations must use an index. When enabled, queries that perform a collection scan will be rejected to ensure better performance.
This is useful for scenarios where you want to ensure that database queries are optimized.
You can enable index check mode using:
- Environment variable:
export MDB_MCP_INDEX_CHECK=true - Command-line argument:
--indexCheck
💡 Platform Note: For Windows users, see Environment Variables for platform-specific instructions.
When index check mode is active, you'll see an error message if a query is rejected due to not using an index.
Exports
The data exported by the export tool is temporarily stored in the configured exportsPath on the machine running the MCP server until cleaned up by the export cleanup process. If the exportsPath configuration is not provided, the following defaults are used:
- Windows:
%LOCALAPPDATA%\mongodb\mongodb-mcp\exports - macOS/Linux:
~/.mongodb/mongodb-mcp/exports
The exportTimeoutMs configuration controls the time after which the exported data is considered expired and eligible for cleanup. By default, exports expire after 5 minutes (300000ms).
The exportCleanupIntervalMs configuration controls how frequently the cleanup process runs to remove expired export files. By default, cleanup runs every 2 minutes (120000ms).
🔒 Security Guideline: The user account running the MCP server must have both read and write permissions to the
exportsPathdirectory. Ensure this directory is properly secured with appropriate file system permissions to prevent unauthorized access to exported data files, which may contain sensitive MongoDB data. Consider the sensitivity of your data when choosing the export location and apply restrictive permissions accordingly.
Telemetry
The telemetry configuration option allows you to disable telemetry collection. When enabled, the MCP server will collect usage data and send it to MongoDB.
You can disable telemetry using:
- Environment variable:
export MDB_MCP_TELEMETRY=disabled - Command-line argument:
--telemetry disabled - DO_NOT_TRACK environment variable:
export DO_NOT_TRACK=1
💡 Platform Note: For Windows users, see Environment Variables for platform-specific instructions.
Opting into Preview Features
The MongoDB MCP Server may offer functionality that is still in development and may change in future releases. These features are considered "preview features" and are not enabled by default. Generally, these features are well tested, but may not offer the complete functionality we intend to provide in the final release or we'd like to gather feedback before making them generally available. To enable one or more preview features, use the previewFeatures configuration option.
- For environment variable configuration, use a comma-separated string:
export MDB_MCP_PREVIEW_FEATURES="feature1,feature2". - For command-line argument configuration, use a space-separated string:
--previewFeatures feature1 feature2.
List of available preview features:
mcpUI- Enables an optional web-based UI for interacting with the MCP server.
Monitoring Server (Health Check & Metrics)
When running with --transport http, you can expose a separate monitoring HTTP server for health checks and metrics. This server is only started when both monitoringServerHost and monitoringServerPort are set, and it listens on its own host/port (independent from the main httpHost/httpPort).
The features exposed are controlled by monitoringServerFeatures (default: health-check). Available features and their endpoints:
The /health response is sent with Cache-Control: no-store and has the following shape (status is always "ok" while the process is alive):
Example: start the server with the monitoring server enabled and call the health-check endpoint:
To expose both endpoints, pass the features explicitly:
Select process-metrics to expose /metrics with both MCP server metrics and Node.js process metrics. You do not need to select metrics as well:
💡 Note:
healthCheckHost/healthCheckPortare deprecated aliases formonitoringServerHost/monitoringServerPortand continue to serve the same/healthendpoint.
Atlas API Access
To use the Atlas API tools, you'll need to create a service account in MongoDB Atlas:
ℹ️ Note: For a detailed breakdown of the minimum required permissions for each Atlas operation, see the Atlas API Permissions section below.
- Create a Service Account:
- Log in to MongoDB Atlas at cloud.mongodb.com
- Navigate to Access Manager > Organization Access
- Click Add New > Applications > Service Accounts
- Enter name, description and expiration for your service account (e.g., "MCP, MCP Server Access, 7 days")
- Assign only the minimum permissions needed for your use case.
- See Atlas API Permissions for details.
- Click "Create"
To learn more about Service Accounts, check the MongoDB Atlas documentation.
-
Save Client Credentials:
- After creation, you'll be shown the Client ID and Client Secret
- Important: Copy and save the Client Secret immediately as it won't be displayed again
-
Add Access List Entry:
- Add your IP address to the API access list
-
Configure the MCP Server:
- Use one of the configuration methods below to set your
apiClientIdandapiClientSecret
- Use one of the configuration methods below to set your
Atlas API Permissions
Security Warning: Granting the Organization Owner role is rarely necessary and can be a security risk. Assign only the minimum permissions needed for your use case.
Quick Reference: Required roles per operation
- Prefer project-level roles for most operations. Assign only to the specific projects you need to manage or view.
- Avoid Organization Owner unless you require full administrative control over all projects and settings in the organization.
For a full list of roles and their privileges, see the Atlas User Roles documentation.
Configuration Methods
Configuration File
Store configuration in a JSON file and load it using the MDB_MCP_CONFIG environment variable.
🔒 Security Best Practice: Prefer using the
MDB_MCP_CONFIGenvironment variable for sensitive fields over the configuration file or--configCLI argument. Command-line arguments are visible in process listings.
🔒 File Security: Ensure your configuration file has proper ownership and permissions, limited to the user running the MongoDB MCP server:
Linux/macOS:
Windows: Right-click the file → Properties → Security → Restrict access to your user account only.
Create a JSON file with your configuration (all keys use camelCase):
Linux/macOS (bash/zsh):
Windows Command Prompt (cmd):
Windows PowerShell:
Environment Variables
Set environment variables with the prefix MDB_MCP_ followed by the option name in uppercase with underscores:
Linux/macOS (bash/zsh):
Windows Command Prompt (cmd):
Windows PowerShell:
MCP configuration file examples
Connection String with environment variables
Atlas API credentials with environment variables
Command-Line Arguments
Pass configuration options as command-line arguments when starting the server:
🔒 Security Note: For sensitive configuration like API credentials and connection strings, use environment variables instead of command-line arguments.
💡 Platform Note: The examples above use Unix/Linux/macOS syntax. For Windows users, see Environment Variables for platform-specific instructions.
MCP configuration file examples
Connection String with command-line arguments
🔒 Security Note: We do not recommend passing connection string as command line argument. Connection string might contain credentials which can be visible in process lists and logged in various system locations, potentially exposing your credentials. Instead configure connection string through environment variables
Atlas API credentials with command-line arguments
🔒 Security Note: We do not recommend passing Atlas API credentials as command line argument. The provided credentials can be visible in process lists and logged in various system locations, potentially exposing your credentials. Instead configure Atlas API credentials through environment variables
Proxy Support
The MCP Server detects standard proxy environment variables and uses them for supported
outbound connections, including the Atlas Administration API, MongoDB cluster connections,
OIDC identity providers, and the MongoDB Assistant. The behaviour matches mongosh
(both rely on @mongodb-js/devtools-proxy-support),
so any proxy configuration that works with mongosh also works here.
Environment variables
Set the relevant variable before starting the server. The conventional *_PROXY
variables are honored:
Proxy in the connection string
For the MongoDB cluster connection specifically, you can configure a SOCKS5 proxy directly in the connection string instead of using environment variables:
Supported parameters: proxyHost, proxyPort, proxyUsername, proxyPassword.
Certificate authorities
For the HTTP(S) requests handled by @mongodb-js/devtools-proxy-support (the Atlas API,
OIDC, and the MongoDB Assistant), the operating system's certificate store is trusted in
addition to the bundled CAs — the same way mongosh does — so corporate root certificates
installed at the OS level are picked up automatically.
🚀Deploy on Public Clouds
You can deploy the MongoDB MCP Server to your preferred cloud provider using the deployment assets under deploy/. Each guide explains the prerequisites, configuration, and automation scripts that streamline the rollout.
Azure
For detailed Azure instructions, see deploy/azure/README.md.
Deployment Constraints
The CLI tool (mongodb-mcp-server / npx mongodb-mcp-server) is designed for single-user, localhost (or private) deployments where the operating user is the only principal. It ships with no built-in authentication, and the MCP protocol does not carry a verified end-user identity. It is not meant to serve multiple users — there is no authentication middleware in front of it to distinguish callers or control connection isolation.
As a result, if you expose it to a network — or run it as a shared server — you are responsible for the isolation guarantees:
- Internet exposure: binding to
0.0.0.0/::(or any non-loopback host) with no auth exposes an unauthenticated endpoint that can run MongoDB operations (including destructive ones) against the configured connection string. If you intentionally bind to a non-loopback host, you must setMDB_MCP_DANGEROUS_HOST_BINDING=true(see Configuration Options). - Multi-user isolation: connections are scoped by the (soon-to-be-removed)
connectionScopeoption, whose default is moving toglobal— every request shares one scope. Themcp-session-idheader that keys the scope on the sessionless path is client-asserted, not a security boundary, and requests without it fall into the shared scope. So multiple users can see and operate on each other's connections, including any Atlas temporary database user credentials. The server does not distinguish callers. To ensure proper isolation, you can either setup an authenticated middleware which controls themcp-session-idheader or provide a custom scoping mechanism using the@mongodb-js/mcp-*library packages.
Do not run the CLI tool as a shared, internet-facing endpoint without adding your own authentication and identity layer in front of it.
Use the library and add your own auth
For multi-tenant or public deployments, build an authenticated solution using the @mongodb-js/mcp-* library packages instead:
- Terminate authentication / user identity at your own proxy or middleware, and pass a verified principal into the request via
authInfo(the SDK'screateMcpHandlerand the legacy handler both forward it). - Supply a
connectionScopepolicy that keys on your verified end-user identity (e.g. the OIDCsubclaim) so each user's connections and credentials are isolated — do not let it fall back to the sharedglobalscope for multi-user traffic.
Already on MongoDB Atlas? For multi-tenant Atlas cluster usage, the simplest alternative is the MongoDB Atlas-Managed MCP server — a hosted, authenticated deployment that handles per-user identity (OAuth / service-account) for you instead of you standing up your own. See Option 2 above.
See MCP_SERVER_LIBRARY.md for the embedding API, createHttpTransportRunnerFromConfig / CliMcpHttpServer and the connectionScope policy seam, and the per-user scoping example to copy.
🤝Contributing
Interested in contributing? Great! Please check our Contributing Guide for guidelines on code contributions, standards, adding new tools, and troubleshooting information.
来源:README.md,提交 6143ab6
工具
0版本历史
3- v3.2.2最新Nov 4, 2026
- v3.2.1Oct 29, 2026
- v2.1.0Sep 16, 2026
评分
已满足适用检查项的 50%
该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。
- 近 30 天内可连通25 分
请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。
- 已声明认证方式10 分
请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。
- 已列出工具15 分
请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。
- 描述必需15 分
- 图标10 分
- 文档15 分
- 许可证10 分