MongoDB MCP Server
OfficialMongoDB MCP-сервер
Сервер Model Context Protocol для взаимодействия с базами данных MongoDB и MongoDB Atlas.
📚 Содержание
Related MCP server: MongoDB MCP Server for LLMs
Предпосылки
Node.js (v20.10.0 или более поздняя версия)
node -vСтрока подключения MongoDB или учетные данные API Atlas. Сервер не запустится, если не настроен .
Учетные записи служб Для использования инструментов Atlas требуются учетные данные API Atlas. Вы можете создать учетную запись службы в MongoDB Atlas и использовать ее учетные данные для аутентификации. Подробнее см. в разделе Доступ к API Atlas .
Если у вас есть строка подключения MongoDB, вы можете использовать ее напрямую для подключения к вашему экземпляру MongoDB.
Настраивать
Быстрый старт
Большинству клиентов MCP требуется создать или изменить файл конфигурации для добавления сервера MCP.
Примечание: Синтаксис файла конфигурации может отличаться в зависимости от клиента. Пожалуйста, обратитесь к следующим ссылкам для получения последнего ожидаемого синтаксиса:
Виндсерфинг : https://docs.windsurf.com/windsurf/mcp
VSCode : https://code.visualstudio.com/docs/copilot/chat/mcp-servers
Рабочий стол Клода : https://modelcontextprotocol.io/quickstart/user
Курсор : https://docs.cursor.com/context/model-context-protocol
Вариант 1: Аргументы строки подключения
Вы можете передать строку подключения через args, обязательно используйте действительные имя пользователя и пароль.
{
"mcpServers": {
"MongoDB": {
"command": "npx",
"args": [
"-y",
"mongodb-mcp-server",
"--connectionString",
"mongodb://localhost:27017/myDatabase"
]
}
}
}ПРИМЕЧАНИЕ: Строку подключения можно настроить для подключения к любому кластеру MongoDB, будь то локальный экземпляр или кластер Atlas.
Вариант 2: Аргументы учетных данных API Atlas
Используйте учетные данные Atlas API Service Accounts. Необходимо выполнить все шаги в разделе Atlas API Access .
{
"mcpServers": {
"MongoDB": {
"command": "npx",
"args": [
"-y",
"mongodb-mcp-server",
"--apiClientId",
"your-atlas-service-accounts-client-id",
"--apiClientSecret",
"your-atlas-service-accounts-client-secret"
]
}
}
}Вариант 3: Автономная служба с использованием аргументов команды
Запустите сервер с помощью команды npx:
npx -y mongodb-mcp-server --apiClientId="your-atlas-service-accounts-client-id" --apiClientSecret="your-atlas-service-accounts-client-secret"Полный список аргументов см. в разделе «Параметры конфигурации».
Чтобы настроить учетные данные учетных записей Atlas Service, обратитесь к разделу Atlas API Access.
Вариант 4: Автономная служба с использованием переменных среды
npx -y mongodb-mcp-serverВы можете использовать переменные среды в файле конфигурации или задать их и запустить сервер через npx.
Строка подключения через переменные среды в примере файла MCP
Учетные данные API Atlas через переменные среды в примере файла MCP
🛠️ Поддерживаемые инструменты
Список инструментов
Инструменты MongoDB Atlas
atlas-list-orgs- Списки организаций MongoDB Atlasatlas-list-projects- Списки проектов MongoDB Atlasatlas-create-project— создает новый проект MongoDB Atlasatlas-list-clusters— список кластеров MongoDB Atlasatlas-inspect-cluster— проверка определенного кластера MongoDB Atlasatlas-create-free-cluster— создание бесплатного кластера MongoDB Atlasatlas-connect-cluster— подключается к кластеру MongoDB Atlasatlas-inspect-access-list— проверка диапазонов IP/CIDR с доступом к кластерам MongoDB Atlasatlas-create-access-list— настройка списка доступа IP/CIDR для кластеров MongoDB Atlasatlas-list-db-users— список пользователей базы данных MongoDB Atlasatlas-create-db-user— создает пользователя базы данных MongoDB Atlasatlas-list-alerts— список оповещений MongoDB Atlas для проекта
ПРИМЕЧАНИЕ: инструменты Atlas доступны только при установке учетных данных в разделе конфигурации .
Инструменты базы данных MongoDB
connect— подключение к экземпляру MongoDBfind— выполнить поисковый запрос по коллекции MongoDB.aggregate— запуск агрегации для коллекции MongoDB.count— получить количество документов в коллекции MongoDBinsert-one— вставка одного документа в коллекцию MongoDBinsert-many— вставка нескольких документов в коллекцию MongoDBcreate-index— создание индекса для коллекции MongoDBupdate-one— обновление одного документа в коллекции MongoDBupdate-many— обновление нескольких документов в коллекции MongoDBrename-collection— переименование коллекции MongoDBdelete-one— удаление одного документа из коллекции MongoDBdelete-many— удаление нескольких документов из коллекции MongoDBdrop-collection— удаление коллекции из базы данных MongoDBdrop-database— удаление базы данных MongoDBlist-databases— список всех баз данных для соединения MongoDBlist-collections— список всех коллекций для заданной базы данныхcollection-indexes- Опишите индексы для коллекцииcollection-schema— Опишите схему для коллекцииcollection-storage-size- Получить размер коллекции в МБdb-stats— возвращает статистику о базе данных MongoDB
Конфигурация
Сервер MongoDB MCP можно настроить несколькими способами со следующим приоритетом (от высшего к низшему):
Аргументы командной строки
Переменные среды
Параметры конфигурации
Вариант | Описание |
| Идентификатор клиента API Atlas для аутентификации |
| Секретный ключ клиента API Atlas для аутентификации |
| Строка подключения MongoDB для прямого подключения к базе данных (по желанию пользователи могут информировать об этом при каждом вызове инструмента) |
| Папка для хранения журналов |
| Массив названий инструментов, типов операций и/или категорий инструментов, которые будут отключены |
| Если установлено значение true, разрешены только операции чтения и метаданных, отключены операции создания/обновления/удаления. |
| Если установлено значение «Отключено», отключает сбор телеметрии. |
Путь журнала
Расположение журнала по умолчанию следующее:
Windows:
%LOCALAPPDATA%\mongodb\mongodb-mcp\.app-logsmacOS/Linux:
~/.mongodb/mongodb-mcp/.app-logs
Отключенные инструменты
Вы можете отключить определенные инструменты или категории инструментов, используя опцию disabledTools . Эта опция принимает массив строк, где каждая строка может быть именем инструмента, типом операции или категорией.
Способ построения массива зависит от типа используемого метода конфигурации:
Для настройки переменных среды используйте строку, разделенную запятыми:
export MDB_MCP_DISABLED_TOOLS="create,update,delete,atlas,collectionSchema".Для настройки аргументов командной строки используйте строку, разделенную пробелами:
--disabledTools create update delete atlas collectionSchema.
Категории инструментов:
atlas- инструменты MongoDB Atlas, такие как список кластеров, создание кластера и т. д.mongodb— инструменты базы данных MongoDB, такие как поиск, агрегация и т. д.
Типы операций:
create- Инструменты, которые создают ресурсы, такие как создание кластера, вставка документа и т. д.update— инструменты, обновляющие ресурсы, такие как обновление документа, переименование коллекции и т. д.delete- инструменты, которые удаляют ресурсы, такие как удаление документа, удаление коллекции и т. д.read— инструменты для чтения ресурсов, такие как поиск, агрегация, составление списка кластеров и т. д.metadata— инструменты, которые считывают метаданные, такие как базы данных списков, коллекции списков, схемы коллекций и т. д.
Режим «Только чтение»
Параметр конфигурации readOnly позволяет ограничить сервер MCP, чтобы он использовал только инструменты с типами операций «read» и «metadata». При включении все инструменты с типами операций «create», «update» или «delete» не будут зарегистрированы на сервере.
Это полезно в сценариях, где вы хотите предоставить доступ к данным MongoDB для анализа, не допуская никаких изменений данных или инфраструктуры.
Вы можете включить режим «только чтение» с помощью:
Переменная среды :
export MDB_MCP_READ_ONLY=trueАргумент командной строки :
--readOnly
Если активен режим «только чтение», в журналах сервера вы увидите сообщение о том, каким инструментам не удалось зарегистрироваться из-за этого ограничения.
Телеметрия
Параметр конфигурации telemetry позволяет отключить сбор телеметрии. При включении сервер MCP будет собирать данные об использовании и отправлять их в MongoDB.
Вы можете отключить телеметрию с помощью:
Переменная среды :
export MDB_MCP_TELEMETRY=disabledАргумент командной строки :
--telemetry disabledПеременная среды DO_NOT_TRACK :
export DO_NOT_TRACK=1
Доступ к API Атласа
Чтобы использовать инструменты API Atlas, вам необходимо создать учетную запись службы в MongoDB Atlas:
Создайте учетную запись службы:
Войдите в MongoDB Atlas по адресу cloud.mongodb.com
Перейдите в Диспетчер доступа > Доступ к организации.
Нажмите Добавить новый > Приложения > Учетные записи служб.
Введите имя, описание и срок действия вашей учетной записи службы (например, «MCP, доступ к серверу MCP, 7 дней»).
Выберите соответствующие разрешения (для полного доступа используйте «Владелец организации»).
Нажмите «Создать»
Дополнительную информацию об учетных записях служб см. в документации MongoDB Atlas .
Сохранить учетные данные клиента:
После создания вам будут показаны идентификатор клиента и секретный код клиента.
Важно: немедленно скопируйте и сохраните секретный код клиента, поскольку он больше не будет отображаться.
Добавить запись в список доступа:
Добавьте свой IP-адрес в список доступа API
Настройте MCP-сервер:
Используйте один из методов настройки ниже, чтобы задать
apiClientIdиapiClientSecret
Методы конфигурации
Переменные среды
Задайте переменные среды с префиксом MDB_MCP_ , за которым следует имя параметра заглавными буквами с подчеркиваниями:
# Set Atlas API credentials (via Service Accounts)
export MDB_MCP_API_CLIENT_ID="your-atlas-service-accounts-client-id"
export MDB_MCP_API_CLIENT_SECRET="your-atlas-service-accounts-client-secret"
# Set a custom MongoDB connection string
export MDB_MCP_CONNECTION_STRING="mongodb+srv://username:password@cluster.mongodb.net/myDatabase"
export MDB_MCP_LOG_PATH="/path/to/logs"
Примеры файлов конфигурации MCP
Строка подключения с переменными среды
{
"mcpServers": {
"MongoDB": {
"command": "npx",
"args": ["-y", "mongodb-mcp-server"],
"env": {
"MDB_MCP_CONNECTION_STRING": "mongodb+srv://username:password@cluster.mongodb.net/myDatabase"
}
}
}
}Учетные данные API Atlas с переменными среды
{
"mcpServers": {
"MongoDB": {
"command": "npx",
"args": ["-y", "mongodb-mcp-server"],
"env": {
"MDB_MCP_API_CLIENT_ID": "your-atlas-service-accounts-client-id",
"MDB_MCP_API_CLIENT_SECRET": "your-atlas-service-accounts-client-secret"
}
}
}
}Аргументы командной строки
Передайте параметры конфигурации в качестве аргументов командной строки при запуске сервера:
npx -y mongodb-mcp-server --apiClientId="your-atlas-service-accounts-client-id" --apiClientSecret="your-atlas-service-accounts-client-secret" --connectionString="mongodb+srv://username:password@cluster.mongodb.net/myDatabase" --logPath=/path/to/logsПримеры файлов конфигурации MCP
Строка подключения с аргументами командной строки
{
"mcpServers": {
"MongoDB": {
"command": "npx",
"args": [
"-y",
"mongodb-mcp-server",
"--connectionString",
"mongodb+srv://username:password@cluster.mongodb.net/myDatabase"
]
}
}
}Учетные данные API Atlas с аргументами командной строки
{
"mcpServers": {
"MongoDB": {
"command": "npx",
"args": [
"-y",
"mongodb-mcp-server",
"--apiClientId",
"your-atlas-service-accounts-client-id",
"--apiClientSecret",
"your-atlas-service-accounts-client-secret"
]
}
}
}🤝 Вклад
Хотите внести свой вклад? Отлично! Пожалуйста, ознакомьтесь с нашим Руководством по внесению вклада для получения рекомендаций по внесению вклада в код, стандартов, добавления новых инструментов и информации по устранению неполадок.
Available Tools
28 toolsaggregateARead-only
Run an aggregation against a MongoDB collection
Inputs: database (required), pipeline (required), collection (required), connectionId (required), +1 more. Returns: count, documents, appliedLimits
aggregate-dbCRead-only
Run an aggregation against a MongoDB database
Inputs: database (required), pipeline (required), connectionId (required), responseBytesLimit. Returns: documents, appliedLimits, aggResultsCount
atlas-connect-clusterARead-only
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.
Inputs: projectId (required), clusterName (required), connectionType. Returns: state, connectionId, addedCurrentIp, sharedTierTier, +4 more
atlas-get-performance-advisorARead-only
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 logs
Inputs: projectId (required), clusterName (required), since, namespaces, +1 more. Returns: projectId, clusterName, slowQueryLogs, suggestedIndexes, +2 more
atlas-inspect-access-listARead-only
Inspect Ip/CIDR ranges with access to your MongoDB Atlas clusters.
Inputs: projectId (required). Returns: entries, projectId, totalCount
atlas-inspect-clusterBRead-only
Inspect metadata of a MongoDB Atlas cluster
Inputs: projectId (required), clusterName (required). Returns: name, state, paused, region, +5 more
atlas-list-alertsARead-only
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.
Inputs: projectId (required), limit, status, pageNum. Returns: alerts, status, projectId, totalCount
atlas-list-clustersBRead-only
List MongoDB Atlas clusters
Inputs: projectId. Returns: clusters, projectId, totalCount, projectName
atlas-list-db-usersARead-only
List MongoDB Atlas database users
Inputs: projectId (required). Returns: users, projectId, totalCount
atlas-list-orgsBRead-only
List MongoDB Atlas organizations
Inputs: limit, pageNum. Returns: totalCount, organizations
atlas-list-projectsBRead-only
List MongoDB Atlas projects.
Inputs: limit, orgId, pageNum. Returns: orgId, projects, totalCount
atlas-streams-discoverARead-only
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.
Inputs: action (required), projectId (required), limit, region, +5 more. Returns: dlq, tier, stats, pipeline, +9 more
collection-indexesARead-only
Describe the indexes for a collection
Inputs: database (required), collection (required), connectionId (required). Returns: searchIndexes, classicIndexes, searchIndexesCount, classicIndexesCount
collection-schemaCRead-only
Describe the schema for a collection
Inputs: database (required), collection (required), connectionId (required), sampleSize, +1 more. Returns: schema, fieldsCount
collection-storage-sizeBRead-only
Gets the size of the collection
Inputs: database (required), collection (required), connectionId (required). Returns: size, units
connectARead-only
Connect to a MongoDB instance 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. A connection with the id "preconfigured" already exists for the connection string the server was configured with — there is no need to call this tool to use it.
Inputs: connectionString (required), connectionName. Returns: connectionId
countARead-only
Gets the number of documents in a MongoDB collection using db.collection.count() and query as an optional filter parameter
Inputs: database (required), collection (required), connectionId (required), query. Returns: count
db-statsARead-only
Returns statistics that reflect the use state of a single database
Inputs: database (required), connectionId (required). Returns: stats
disconnectCRead-only
Close a MongoDB connection and revoke its connectionId. Disconnecting the "preconfigured" connection only closes it — it reconnects automatically on next use because the server configuration still declares it.
Inputs: connectionId (required). Returns: outcome
explainBRead-only
Returns statistics describing the execution of the winning plan chosen by the query optimizer for the evaluated method
Inputs: method (required), database (required), collection (required), connectionId (required), +1 more. Returns: method, verbosity, explainResult
exportARead-only
Export a query or aggregation results in the specified EJSON format.
Inputs: database (required), collection (required), exportTitle (required), connectionId (required), +2 more.
findBRead-only
Run a find query against a MongoDB collection
Inputs: database (required), collection (required), connectionId (required), sort, +4 more. Returns: documents, appliedLimits, queryResultsCount
list-collectionsARead-only
List all collections for a given database
Inputs: database (required), connectionId (required). Returns: totalCount, collections
list-connectionsARead-only
List the active MongoDB connections and their connectionIds. Use this to discover the "preconfigured" connection or to find a connectionId established earlier.
Inputs: no named parameters. Returns: connections
list-databasesARead-only
List all databases for a MongoDB connection
Inputs: connectionId (required). Returns: databases, totalCount
list-knowledge-sourcesARead-only
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.
Inputs: no named parameters.
mongodb-logsARead-only
Returns the most recent logged mongod events
Inputs: connectionId (required), type, limit. Returns: logs, shownCount, totalLinesWritten
search-knowledgeARead-only
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.
Inputs: query (required), limit, dataSources.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 28 tools
Most tools have distinct purposes: find, count, aggregate, export, and explain are clearly separate query operations. The Atlas tools are well-prefixed and target different resources. Minor confusion exists between aggregate and aggregate-db, and between connect and atlas-connect-cluster, but descriptions clarify the distinction.
Naming conventions are mixed: some tools use verb-first style (find, count, export, connect), some use noun-only (collection-indexes, db-stats), and the Atlas group consistently uses atlas-* prefix. This is readable but lacks a uniform pattern, making it less predictable.
With 28 tools, the server exceeds the 25-tool threshold for 'too many'. While the breadth reflects both core MongoDB operations and Atlas management, the large count can overwhelm agents, especially with many similar list/inspect tools. A leaner set or grouping would improve usability.
The tool surface is heavily read/analysis-oriented (find, aggregate, explain, export) and includes Atlas admin operations, but it lacks fundamental write/update/delete operations for documents and collections. Agents cannot perform mutations, which is a significant gap for a MongoDB server.
Maintenance
Related MCP Connectors
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
A Model Context Protocol server for Wix AI tools
The Mercado Pago MCP Server implements the Model Context Protocol to provide AI agents and LLMs with access to Mercado Pago's APIs and tools within compatible development environments. It acts as an intermediary that translates Mercado Pago resources into executable functions (tools) that AI applications can invoke to perform actions and automate flows. The server simplifies integration, enables using documentation to implement or improve code, and optimizes operations through natural language interactions without manual implementations.
The Telnyx MCP server is an official implementation of the Model Context Protocol that enables AI clients (like Claude Desktop, Cursor, and OpenAI Agents) to interact with Telnyx's telephony, messaging, and AI assistant APIs. It provides comprehensive capabilities including making and managing phone calls, sending SMS/MMS messages, purchasing and configuring phone numbers, creating AI assistants with custom instructions, managing cloud storage buckets, scraping and embedding website content, and handling integration secrets. The server exists as both a local implementation and a remotely hosted version, allowing developers to integrate real-world communication infrastructure directly into AI applications.
Related MCP Servers
- AlicenseAqualityDmaintenanceA Model Context Protocol server that provides read-only access to MongoDB databases, enabling AI assistants to directly query and analyze MongoDB data while maintaining data safety.149MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables LLMs to interact directly with MongoDB databases, allowing users to query collections, inspect schemas, and manage data through natural language.1MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables LLMs to interact directly with MongoDB databases, allowing users to query collections, inspect schemas, and manage data through natural language.MIT
- AlicenseAqualityBmaintenanceA Model Context Protocol server that enables interaction with MongoDB databases and MongoDB Atlas, allowing users to perform database operations and manage Atlas resources through natural language.22Apache 2.0