Skip to main content
Glama
elastic

Elasticsearch MCP Server

Official
by elastic

Сервер Elasticsearch MCP

Этот репозиторий содержит экспериментальные функции, предназначенные для исследований и оценки и не готовые к использованию в производстве.

Подключитесь к данным Elasticsearch напрямую из любого клиента MCP (например, Claude Desktop) с помощью протокола контекста модели (MCP).

Этот сервер подключает агентов к вашим данным Elasticsearch с помощью Model Context Protocol. Он позволяет вам взаимодействовать с вашими индексами Elasticsearch посредством разговоров на естественном языке.

Доступные инструменты

  • list_indices : Список всех доступных индексов Elasticsearch

  • get_mappings : Получить сопоставления полей для определенного индекса Elasticsearch

  • search : выполнить поиск Elasticsearch с предоставленным запросом DSL

  • get_shards : Получить информацию о шардах для всех или определенных индексов

Related MCP server: Elasticsearch MCP Server

Предпосылки

  • Экземпляр Elasticsearch

  • Учетные данные аутентификации Elasticsearch (ключ API или имя пользователя/пароль)

  • Клиент MCP (например, Claude Desktop)

Демо

https://github.com/user-attachments/assets/5dd292e1-a728-4ca7-8f01-1380d1bebe0c

Установка и настройка

Использование опубликованного пакета NPM

[!СОВЕТ] Самый простой способ использовать сервер Elasticsearch MCP — через опубликованный пакет npm.

  1. Настроить MCP-клиент

    • Откройте ваш MCP Client. Посмотрите список MCP Clients , здесь мы настраиваем Claude Desktop.

    • Перейдите в Настройки > Разработчик > Серверы MCP.

    • Нажмите Edit Config и добавьте новый сервер MCP со следующей конфигурацией:

    {
      "mcpServers": {
        "elasticsearch-mcp-server": {
          "command": "npx",
          "args": [
            "-y",
            "@elastic/mcp-server-elasticsearch"
          ],
          "env": {
            "ES_URL": "your-elasticsearch-url",
            "ES_API_KEY": "your-api-key"
          }
        }
      }
    }
  2. Начать разговор

    • Откройте новый разговор в вашем MCP Client

    • Сервер MCP должен подключиться автоматически.

    • Теперь вы можете задавать вопросы о своих данных Elasticsearch

Параметры конфигурации

Сервер Elasticsearch MCP поддерживает параметры конфигурации для подключения к Elasticsearch:

[!ПРИМЕЧАНИЕ] Для аутентификации необходимо предоставить либо ключ API, либо имя пользователя и пароль.

Переменная среды

Описание

Необходимый

ES_URL

URL вашего экземпляра Elasticsearch

Да

ES_API_KEY

Ключ API Elasticsearch для аутентификации

Нет

ES_USERNAME

Имя пользователя Elasticsearch для базовой аутентификации

Нет

ES_PASSWORD

Пароль Elasticsearch для базовой аутентификации

Нет

ES_CA_CERT

Путь к пользовательскому сертификату CA для Elasticsearch SSL/TLS

Нет

Развитие на местном уровне

[!ПРИМЕЧАНИЕ] Если вы хотите изменить или расширить сервер MCP, следуйте этим шагам локальной разработки.

  1. Используйте правильную версию Node.js

    nvm use
  2. Установить зависимости

    npm install
  3. Построить проект

    npm run build
  4. Запустить локально в приложении Claude Desktop

    • Открыть приложение Claude для ПК

    • Перейдите в Настройки > Разработчик > Серверы MCP.

    • Нажмите Edit Config и добавьте новый сервер MCP со следующей конфигурацией:

    {
      "mcpServers": {
        "elasticsearch-mcp-server-local": {
          "command": "node",
          "args": [
            "/path/to/your/project/dist/index.js"
          ],
          "env": {
            "ES_URL": "your-elasticsearch-url",
            "ES_API_KEY": "your-api-key"
          }
        }
      }
    }
  5. Отладка с помощью MCP Inspector

    ES_URL=your-elasticsearch-url ES_API_KEY=your-api-key npm run inspector

    Это запустит MCP Inspector, позволяющий вам отлаживать и анализировать запросы. Вы должны увидеть:

    Starting MCP inspector...
    Proxy server listening on port 3000
    
    🔍 MCP Inspector is up and running at http://localhost:5173 🚀

Внося вклад

Мы приветствуем вклады от сообщества! Подробности о том, как внести вклад, см. в Руководстве по внесению вкладов .

Примеры вопросов

[!СОВЕТ] Вот несколько запросов на естественном языке, которые вы можете попробовать выполнить с помощью своего клиента MCP.

  • «Какие индексы есть в моем кластере Elasticsearch?»

  • «Покажите мне сопоставления полей для индекса «продукты»».

  • «Найти все заказы на сумму более 500 долларов за прошлый месяц».

  • «Какие продукты получили наибольшее количество 5-звездочных отзывов?»

Как это работает

  1. Клиент MCP анализирует ваш запрос и определяет, какие операции Elasticsearch необходимы.

  2. Сервер MCP выполняет эти операции (перечисление индексов, выборку сопоставлений, выполнение поиска).

  3. Клиент MCP обрабатывает результаты и представляет их в удобном для пользователя формате.

Лучшие практики безопасности

[!WARNING] Избегайте использования привилегий администратора кластера. Создавайте выделенные ключи API с ограниченной областью действия и применяйте детальный контроль доступа на уровне индекса, чтобы предотвратить несанкционированный доступ к данным.

Вы можете создать специальный ключ API Elasticsearch с минимальными правами доступа для управления доступом к вашим данным:

POST /_security/api_key
{
  "name": "es-mcp-server-access",
  "role_descriptors": {
    "mcp_server_role": {
      "cluster": [
        "monitor"
      ],
      "indices": [
        {
          "names": [
            "index-1",
            "index-2",
            "index-pattern-*"
          ],
          "privileges": [
            "read",
            "view_index_metadata"
          ]
        }
      ]
    }
  }
}

Лицензия

Данный проект лицензирован по лицензии Apache License 2.0.

Поиск неисправностей

  • Убедитесь, что конфигурация вашего MCP правильная.

  • Убедитесь, что URL-адрес Elasticsearch доступен с вашего компьютера.

  • Убедитесь, что ваши учетные данные аутентификации (ключ API или имя пользователя/пароль) имеют необходимые разрешения.

  • При использовании SSL/TLS с пользовательским центром сертификации убедитесь, что путь к сертификату указан правильно и файл доступен для чтения.

  • Проверьте вывод терминала на наличие сообщений об ошибках.

Если у вас возникли проблемы, смело сообщайте о них в репозитории GitHub.

Available Tools

3 tools
get_mappingsB

Get field mappings for a specific Elasticsearch index

ParametersJSON Schema
NameRequiredDescriptionDefault
indexYesName of the Elasticsearch index to get mappings for

TDQS

B3.3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full burden but only states 'Get field mappings', implying read-only but not disclosing permissions, side effects, or behavior like error handling.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence, no unnecessary words, front-loaded with the action and target.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema, the description could mention what the response contains; it is adequate but minimal for a simple get operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% and the parameter 'index' has a description; the tool description adds no extra meaning beyond what the schema provides.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description uses specific verb 'Get' and resource 'field mappings' for a specific Elasticsearch index, clearly distinguishing from siblings like create_mapping or search.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives; for example, it doesn't explain how it differs from create_mapping or search in terms of use cases.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_indicesB

List all available Elasticsearch indices

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.2/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. While 'List' implies a read operation, it doesn't specify whether this requires special permissions, returns paginated results, includes hidden/system indices, or provides any metadata beyond names. For a tool with zero annotation coverage, this leaves significant behavioral questions unanswered.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that communicates the core functionality without any wasted words. It's appropriately sized for a simple listing tool and front-loads the essential information. Every word earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a zero-parameter read operation without output schema, the description provides the minimum viable information about what the tool does. However, given the lack of annotations and sibling tools with potentially overlapping functionality, more context about when to use this versus alternatives would be helpful. The description is complete enough for basic understanding but leaves operational context gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters with 100% schema description coverage, so the schema already fully documents the parameter situation. The description appropriately doesn't mention parameters since none exist. A baseline of 4 is appropriate for zero-parameter tools where the schema handles all parameter documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('List') and resource ('all available Elasticsearch indices'), making the tool's purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'get_mappings' or 'search' - it's unclear if this is a simple listing versus more detailed metadata retrieval.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'get_mappings' or 'search'. There's no indication of whether this is for administrative purposes, discovery, or as a prerequisite for other operations. The agent must infer usage context from tool names alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv1.0.0
    • First observedget_mappings
    • First observedlist_indices
    • First observedsearch

TDQS

B3.2/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: get_mappings retrieves field mappings for a specific index, list_indices enumerates all indices, and search performs query-based searches. There is no overlap in functionality, making tool selection unambiguous.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern (get_mappings, list_indices, search), with clear and descriptive verbs that align with their actions. No deviations or mixed conventions are present.

Tool Count3/5

With only 3 tools, the set feels thin for an Elasticsearch server, as it lacks essential operations like creating/deleting indices, updating mappings, or performing CRUD operations on documents. While the tools are well-defined, the count is borderline for the domain's scope.

Completeness2/5

There are significant gaps in the tool surface for Elasticsearch functionality. Missing operations include index creation/deletion, document indexing/updating/deleting, and cluster management. This incompleteness will likely cause agent failures when attempting full workflows.

Maintenance

ActivityInactive
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    A
    maintenance
    Facilitates interaction with Elasticsearch clusters by allowing users to perform index operations, document searches, and cluster management via a Model Context Protocol server and natural language commands.
    20
    308
    Apache 2.0
  • A
    license
    B
    quality
    C
    maintenance
    Connects agents to Elasticsearch data using the Model Context Protocol, allowing natural language interaction with Elasticsearch indices through MCP Clients like Claude Desktop and Cursor.
    11
    71 npm
    23
    MIT
  • A
    license
    B
    quality
    D
    maintenance
    Connects to Elasticsearch databases using the Model Context Protocol, allowing users to query and interact with their Elasticsearch indices through natural language conversations.
    4
    7 npm
    Apache 2.0
  • A
    license
    Not graded
    quality
    D
    maintenance
    Connects agents to Elasticsearch data using the Model Context Protocol, allowing natural language interaction with Elasticsearch indices through tools for listing indices, getting field mappings, performing searches, and viewing shard information.
    2,662 npm
    Apache 2.0