Octodet Elasticsearch MCP Сервер
Обзор
Octodet Elasticsearch MCP Server
Сервер Octodet Elasticsearch MCP — это мощный сервер Протокола Контекста Модели (MCP), предназначенный для бесшовного взаимодействия с кластерами Elasticsearch. Он предоставляет стандартизированный способ для приложений на базе LLM выполнять различные операции, такие как поиск, обновление и управление данными в Elasticsearch.
Особенности
- Полные операции Elasticsearch: Выполняйте полные операции CRUD с документами и индексами без усилий.
- Пакетные операции: Повышайте производительность, обрабатывая несколько операций в одном API-вызове.
- Обновления/Удаления на основе запросов: Изменяйте или удаляйте документы на основе конкретных запросов.
- Управление кластером: Мониторьте состояние вашего кластера Elasticsearch, включая шардирование и шаблоны.
- Расширенный поиск: Используйте все возможности запросов DSL Elasticsearch с поддержкой встроенного выделения.
Как установить
Как пакет NPM
Чтобы установить сервер Octodet Elasticsearch MCP глобально, выполните:
npm install -g @octodet/elasticsearch-mcp
В качестве альтернативы, вы можете использовать его напрямую с npx:
npx @octodet/elasticsearch-mcp
Из исходников
- Клонируйте репозиторий.
- Установите необходимые зависимости:
npm install
- Соберите сервер:
npm run build
Интеграция с клиентами MCP
Интеграция с VS Code
Чтобы интегрировать с расширением MCP для VS Code, добавьте следующую конфигурацию в ваш settings.json
:
"mcp.servers": {
"elasticsearch": {
"command": "npx",
"args": [
"-y", "@octodet/elasticsearch-mcp"
],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
Интеграция с Claude Desktop
Для Claude Desktop настройте ваши параметры следующим образом:
{
"mcpServers": {
"elasticsearch": {
"command": "npx",
"args": ["-y", "@octodet/elasticsearch-mcp"],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
}
Для локальной разработки
Если вы разрабатываете сервер MCP локально, настройте ваши клиенты на использование вашей локальной сборки:
{
"mcpServers": {
"elasticsearch": {
"command": "node",
"args": ["path/to/build/index.js"],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
}
Конфигурация
Сервер можно настроить с помощью следующих переменных окружения:
| Переменная | Описание | Значение по умолчанию | | | | | | ES_URL | URL сервера Elasticsearch | http://localhost:9200 | | ES_API_KEY | API-ключ для аутентификации | | | ES_USERNAME | Имя пользователя для аутентификации | | | ES_PASSWORD | Пароль для аутентификации | | | ES_CA_CERT | Путь к пользовательскому CA-сертификату | | | ES_VERSION | Версия Elasticsearch (8 или 9) | 8 | | ES_SSL_SKIP_VERIFY | Пропустить проверку SSL | false | | ES_PATH_PREFIX | Префикс пути для Elasticsearch | |
Инструменты
Сервер включает 16 инструментов MCP для различных операций Elasticsearch, каждый из которых документирован с обязательными и необязательными параметрами.
1. Список индексов
Получите список всех доступных индексов Elasticsearch с подробной информацией.
Параметры:
indexPattern
(необязательный, строка): Шаблон для фильтрации индексов (например, "logs-", "my-index-")
Пример:
{
"indexPattern": "logs-*"
}
2. Получить отображения
Получите отображения полей для конкретного индекса Elasticsearch.
Параметры:
index
(обязательный, строка): Имя индекса, для которого нужно получить отображения.
Пример:
{
"index": "my-index"
}
3. Поиск
Проведите поиск в Elasticsearch, используя предоставленный запрос DSL и выделение.
Параметры:
index
(обязательный, строка): Индекс или индексы для поиска (поддерживает значения, разделенные запятыми).queryBody
(обязательный, объект): Тело запроса DSL Elasticsearch.highlight
(необязательный, булев): Включить выделение для результатов поиска (по умолчанию: true).
Пример:
{
"index": "my-index",
"queryBody": {
"query": {
"match": {
"content": "search term"
}
},
"size": 10,
"from": 0,
"sort": [{ "_score": { "order": "desc" } }]
},
"highlight": true
}
4. Получить состояние кластера
Получите информацию о состоянии кластера Elasticsearch.
Параметры:
- Не требуется.
Пример:
{}
5. Получить шардирование
Получите информацию о шардировании для всех или конкретных индексов.
Параметры:
index
(необязательный, строка): Конкретный индекс для получения информации о шардировании. Если опущен, возвращает шардирование для всех индексов.
Пример:
{
"index": "my-index"
}
6. Добавить документ
Вставьте новый документ в конкретный индекс Elasticsearch.
Параметры:
index
(обязательный, строка): Индекс, в который будет добавлен документ.document
(обязательный, объект): Содержимое документа для добавления.id
(необязательный, строка): ID документа. Если опущен, Elasticsearch автоматически сгенерирует его.
Пример:
{
"index": "my-index",
"id": "doc1",
"document": {
"title": "My Document",
"content": "Document content here",
"timestamp": "2025-06-23T10:30:00Z",
"tags": ["important", "draft"]
}
}
7. Обновить документ
Измените существующий документ в конкретном индексе Elasticsearch.
Параметры:
index
(обязательный, строка): Индекс, содержащий документ.id
(обязательный, строка): ID документа для обновления.document
(обязательный, объект): Частичный документ с полями для обновления.
Пример:
{
"index": "my-index",
"id": "doc1",
"document": {
"title": "Updated Document Title",
"last_modified": "2025-06-23T10:30:00Z"
}
}
8. Удалить документ
Удалите документ из конкретного индекса Elasticsearch.
Параметры:
index
(обязательный, строка): Индекс, содержащий документ.id
(обязательный, строка): ID документа для удаления.
Пример:
{
"index": "my-index",
"id": "doc1"
}
9. Обновить по запросу
Обновите документы в индексе Elasticsearch на основе запроса.
Параметры:
index
(обязательный, строка): Индекс для обновления документов.query
(обязательный, объект): Запрос Elasticsearch для сопоставления документов для обновления.script
(обязательный, объект): Скрипт для выполнения обновления сопоставленных документов.conflicts
(необязательный, строка): Как обрабатывать конфликты версий ("abort" или "proceed", по умолчанию: "abort").refresh
(необязательный, булев): Нужно ли обновлять индекс после операции (по умолчанию: false).
Пример:
{
"index": "my-index",
"query": {
"term": {
"status": "active"
}
},
"script": {
"source": "ctx._source.status = params.newStatus; ctx._source.updated_at = params.timestamp",
"params": {
"newStatus": "inactive",
"timestamp": "2025-06-23T10:30:00Z"
}
},
"conflicts": "proceed",
"refresh": true
}
10. Удалить по запросу
Удалите документы в индексе Elasticsearch на основе запроса.
Параметры:
index
(обязательный, строка): Индекс для удаления документов.query
(обязательный, объект): Запрос Elasticsearch для сопоставления документов для удаления.conflicts
(необязательный, строка): Как обрабатывать конфликты версий ("abort" или "proceed", по умолчанию: "abort").refresh
(необязательный, булев): Нужно ли обновлять индекс после операции (по умолчанию: false).
Пример:
{
"index": "my-index",
"query": {
"range": {
"created_date": {
"lt": "2025-01-01"
}
}
},
"conflicts": "proceed",
"refresh": true
}
11. Пакетные операции
Выполните несколько операций с документами в одном API-вызове для повышения производительности.
Параметры:
operations
(обязательный, массив): Массив объектов операций, каждый из которых содержит:action
(обязательный, строка): Тип операции ("index", "create", "update" или "delete").index
(обязательный, строка): Индекс для этой операции.id
(необязательный, строка): ID документа (обязателен для обновления/удаления, необязателен для индексации/создания).document
(условный, объект): Содержимое документа (обязательно для индексации/создания/обновления).
Пример:
{
"operations": [
{
"action": "index",
"index": "my-index",
"id": "doc1",
"document": { "title": "Document 1", "content": "Content here" }
},
{
"action": "update",
"index": "my-index",
"id": "doc2",
"document": { "title": "Updated Title" }
},
{
"action": "delete",
"index": "my-index",
"id": "doc3"
}
]
}
12. Создать индекс
Создайте новый индекс Elasticsearch с необязательными настройками и отображениями.
Параметры:
index
(обязательный, строка): Имя индекса для создания.settings
(необязательный, объект): Настройки индекса, такие как количество шардов, реплик и т. д.mappings
(необязательный, объект): Отображения полей, определяющие, как документы должны индексироваться.
Пример:
{
"index": "new-index",
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"custom_analyzer": {
"type": "standard",
"stopwords": "_english_"
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "custom_analyzer"
},
"created": {
"type": "date",
"format": "yyyy-MM-dd'T'HH:mm:ss'Z'"
},
"tags": {
"type": "keyword"
}
}
}
}
13. Удалить индекс
Постоянно удалите индекс Elasticsearch.
Параметры:
index
(обязательный, строка): Имя индекса для удаления.
Пример:
{
"index": "my-index"
}
14. Подсчитать документы
Подсчитайте документы в индексе, при необходимости отфильтровав по запросу.
Параметры:
index
(обязательный, строка): Индекс для подсчета документов.query
(необязательный, объект): Запрос Elasticsearch для фильтрации документов для подсчета.
Пример:
{
"index": "my-index",
"query": {
"bool": {
"must": [
{ "term": { "status": "active" } },
{ "range": { "created_date": { "gte": "2025-01-01" } } }
]
}
}
}
15. Получить шаблоны
Получите шаблоны индексов из Elasticsearch.
Параметры:
name
(необязательный, строка): Конкретное имя шаблона для получения. Если опущено, возвращает все шаблоны.
Пример:
{
"name": "logs-template"
}
16. Получить псевдонимы
Получите псевдонимы индексов из Elasticsearch.
Параметры:
name
(необязательный, строка): Конкретное имя псевдонима для получения. Если опущено, возвращает все псевдонимы.
Пример:
{
"name": "logs-alias"
}
Разработка
Запуск в режиме разработки
Чтобы запустить сервер в режиме наблюдения во время разработки, используйте:
npm run dev
Реализация протокола
Этот сервер реализует Протокол Контекста Модели для облегчения стандартизированного общения между клиентами LLM и Elasticsearch. Он предоставляет комплексный набор инструментов, которые могут быть вызваны клиентами MCP для выполнения различных операций Elasticsearch.
Добавление новых инструментов
Чтобы добавить новый инструмент на сервер:
- Определите инструмент в
src/index.ts
, используя формат регистрации инструментов сервера MCP. - Реализуйте необходимую функциональность в
src/utils/elasticsearchService.ts
. - Обновите этот README для документирования нового инструмента.
Другие клиенты MCP
Сервер Octodet Elasticsearch MCP может быть использован с любым совместимым клиентом MCP, включая:
- ChatGPT от OpenAI через плагины MCP
- Claude Desktop от Anthropic
- Claude в VS Code
- Пользовательские приложения с использованием MCP SDK
Программное использование
Вы также можете использовать сервер программно в ваших приложениях Node.js:
import { createOctodetElasticsearchMcpServer } from "@octodet/elasticsearch-mcp";
import { CustomTransport } from "@modelcontextprotocol/sdk/server";
// Настройте соединение с Elasticsearch
const config = {
url: "http://localhost:9200",
apiKey: "your_api_key",
version: "8",
};
// Создайте и запустите сервер
async function startServer() {
const server = await createOctodetElasticsearchMcpServer(config);
// Подключите ваш пользовательский транспорт
const transport = new CustomTransport();
await server.connect(transport);
console.log("Сервер Elasticsearch MCP запущен");
}
startServer().catch(console.error);
Лицензия
Этот проект лицензирован под лицензией MIT - смотрите файл LICENSE для подробностей.
Деталь
Octodet Elasticsearch MCP Server
A Model Context Protocol (MCP) server for Elasticsearch operations, providing a comprehensive set of tools for interacting with Elasticsearch clusters through the standardized Model Context Protocol. This server enables LLM-powered applications to search, update, and manage Elasticsearch data.
Features
- Complete Elasticsearch Operations: Full CRUD operations for documents and indices
- Bulk Operations: Process multiple operations in a single API call
- Query-Based Updates/Deletes: Modify or remove documents based on queries
- Cluster Management: Monitor health, shards, and templates
- Advanced Search: Full support for Elasticsearch DSL queries with highlighting
Installation
As an NPM Package
Install the package globally:
npm install -g @octodet/elasticsearch-mcp
Or use it directly with npx:
npx @octodet/elasticsearch-mcp
From Source
- Clone this repository
- Install dependencies:
npm install
- Build the server:
npm run build
Integration with MCP Clients
VS Code Integration
Add the following configuration to your VS Code settings.json to integrate with the VS Code MCP extension:
"mcp.servers": {
"elasticsearch": {
"command": "npx",
"args": [
"-y", "@octodet/elasticsearch-mcp"
],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
Claude Desktop Integration
Configure in your Claude Desktop configuration file:
{
"mcpServers": {
"elasticsearch": {
"command": "npx",
"args": ["-y", "@octodet/elasticsearch-mcp"],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
}
For Local Development
If you're developing the MCP server locally, you can configure the clients to use your local build:
{
"mcpServers": {
"elasticsearch": {
"command": "node",
"args": ["path/to/build/index.js"],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
}
Configuration
The server uses the following environment variables for configuration:
| Variable | Description | Default | | | | | | ES_URL | Elasticsearch server URL | http://localhost:9200 | | ES_API_KEY | API key for authentication | | | ES_USERNAME | Username for authentication | | | ES_PASSWORD | Password for authentication | | | ES_CA_CERT | Path to custom CA certificate | | | ES_VERSION | Elasticsearch version (8 or 9) | 8 | | ES_SSL_SKIP_VERIFY | Skip SSL verification | false | | ES_PATH_PREFIX | Path prefix for Elasticsearch | |
Tools
The server provides 16 MCP tools for Elasticsearch operations. Each tool is documented with its required and optional parameters:
1. List Indices
List all available Elasticsearch indices with detailed information.
Parameters:
indexPattern
(optional, string): Pattern to filter indices (e.g., "logs-", "my-index-")
Example:
{
"indexPattern": "logs-*"
}
2. Get Mappings
Get field mappings for a specific Elasticsearch index.
Parameters:
index
(required, string): The name of the index to get mappings for
Example:
{
"index": "my-index"
}
3. Search
Perform an Elasticsearch search with the provided query DSL and highlighting.
Parameters:
index
(required, string): The index or indices to search in (supports comma-separated values)queryBody
(required, object): The Elasticsearch query DSL bodyhighlight
(optional, boolean): Enable search result highlighting (default: true)
Example:
{
"index": "my-index",
"queryBody": {
"query": {
"match": {
"content": "search term"
}
},
"size": 10,
"from": 0,
"sort": [{ "_score": { "order": "desc" } }]
},
"highlight": true
}
4. Get Cluster Health
Get health information about the Elasticsearch cluster.
Parameters:
- None required
Example:
{}
5. Get Shards
Get shard information for all or specific indices.
Parameters:
index
(optional, string): Specific index to get shard information for. If omitted, returns shards for all indices
Example:
{
"index": "my-index"
}
6. Add Document
Add a new document to a specific Elasticsearch index.
Parameters:
index
(required, string): The index to add the document todocument
(required, object): The document content to addid
(optional, string): Document ID. If omitted, Elasticsearch will generate one automatically
Example:
{
"index": "my-index",
"id": "doc1",
"document": {
"title": "My Document",
"content": "Document content here",
"timestamp": "2025-06-23T10:30:00Z",
"tags": ["important", "draft"]
}
}
7. Update Document
Update an existing document in a specific Elasticsearch index.
Parameters:
index
(required, string): The index containing the documentid
(required, string): The ID of the document to updatedocument
(required, object): The partial document with fields to update
Example:
{
"index": "my-index",
"id": "doc1",
"document": {
"title": "Updated Document Title",
"last_modified": "2025-06-23T10:30:00Z"
}
}
8. Delete Document
Delete a document from a specific Elasticsearch index.
Parameters:
index
(required, string): The index containing the documentid
(required, string): The ID of the document to delete
Example:
{
"index": "my-index",
"id": "doc1"
}
9. Update By Query
Update documents in an Elasticsearch index based on a query.
Parameters:
index
(required, string): The index to update documents inquery
(required, object): Elasticsearch query to match documents for updatescript
(required, object): Script to execute for updating matched documentsconflicts
(optional, string): How to handle version conflicts ("abort" or "proceed", default: "abort")refresh
(optional, boolean): Whether to refresh the index after the operation (default: false)
Example:
{
"index": "my-index",
"query": {
"term": {
"status": "active"
}
},
"script": {
"source": "ctx._source.status = params.newStatus; ctx._source.updated_at = params.timestamp",
"params": {
"newStatus": "inactive",
"timestamp": "2025-06-23T10:30:00Z"
}
},
"conflicts": "proceed",
"refresh": true
}
10. Delete By Query
Delete documents in an Elasticsearch index based on a query.
Parameters:
index
(required, string): The index to delete documents fromquery
(required, object): Elasticsearch query to match documents for deletionconflicts
(optional, string): How to handle version conflicts ("abort" or "proceed", default: "abort")refresh
(optional, boolean): Whether to refresh the index after the operation (default: false)
Example:
{
"index": "my-index",
"query": {
"range": {
"created_date": {
"lt": "2025-01-01"
}
}
},
"conflicts": "proceed",
"refresh": true
}
11. Bulk Operations
Perform multiple document operations in a single API call for better performance.
Parameters:
operations
(required, array): Array of operation objects, each containing:action
(required, string): The operation type ("index", "create", "update", or "delete")index
(required, string): The index for this operationid
(optional, string): Document ID (required for update/delete, optional for index/create)document
(conditional, object): Document content (required for index/create/update operations)
Example:
{
"operations": [
{
"action": "index",
"index": "my-index",
"id": "doc1",
"document": { "title": "Document 1", "content": "Content here" }
},
{
"action": "update",
"index": "my-index",
"id": "doc2",
"document": { "title": "Updated Title" }
},
{
"action": "delete",
"index": "my-index",
"id": "doc3"
}
]
}
12. Create Index
Create a new Elasticsearch index with optional settings and mappings.
Parameters:
index
(required, string): The name of the index to createsettings
(optional, object): Index settings like number of shards, replicas, etc.mappings
(optional, object): Field mappings defining how documents should be indexed
Example:
{
"index": "new-index",
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"custom_analyzer": {
"type": "standard",
"stopwords": "_english_"
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "custom_analyzer"
},
"created": {
"type": "date",
"format": "yyyy-MM-dd'T'HH:mm:ss'Z'"
},
"tags": {
"type": "keyword"
}
}
}
}
13. Delete Index
Delete an Elasticsearch index permanently.
Parameters:
index
(required, string): The name of the index to delete
Example:
{
"index": "my-index"
}
14. Count Documents
Count documents in an index, optionally filtered by a query.
Parameters:
index
(required, string): The index to count documents inquery
(optional, object): Elasticsearch query to filter documents for counting
Example:
{
"index": "my-index",
"query": {
"bool": {
"must": [
{ "term": { "status": "active" } },
{ "range": { "created_date": { "gte": "2025-01-01" } } }
]
}
}
}
15. Get Templates
Get index templates from Elasticsearch.
Parameters:
name
(optional, string): Specific template name to retrieve. If omitted, returns all templates
Example:
{
"name": "logs-template"
}
16. Get Aliases
Get index aliases from Elasticsearch.
Parameters:
name
(optional, string): Specific alias name to retrieve. If omitted, returns all aliases
Example:
{
"name": "logs-alias"
}
Development
Running in Development Mode
Run the server in watch mode during development:
npm run dev
Protocol Implementation
This server implements the Model Context Protocol to enable standardized communication between LLM clients and Elasticsearch. It provides a set of tools that can be invoked by MCP clients to perform various Elasticsearch operations.
Adding New Tools
To add a new tool to the server:
- Define the tool in
src/index.ts
using the MCP server's tool registration format - Implement the necessary functionality in
src/utils/elasticsearchService.ts
- Update this README to document the new tool
Other MCP Clients
This server can be used with any MCP-compatible client, including:
- OpenAI's ChatGPT via MCP plugins
- Anthropic's Claude Desktop
- Claude in VS Code
- Custom applications using the MCP SDK
Programmatic Usage
You can also use the server programmatically in your Node.js applications:
import { createOctodetElasticsearchMcpServer } from "@octodet/elasticsearch-mcp";
import { CustomTransport } from "@modelcontextprotocol/sdk/server";
// Configure the Elasticsearch connection
const config = {
url: "http://localhost:9200",
apiKey: "your_api_key",
version: "8",
};
// Create and start the server
async function startServer() {
const server = await createOctodetElasticsearchMcpServer(config);
// Connect to your custom transport
const transport = new CustomTransport();
await server.connect(transport);
console.log("Elasticsearch MCP server started");
}
startServer().catch(console.error);
License
This project is licensed under the MIT License - see the LICENSE file for details.
Конфигурация сервера
{
"mcpServers": {
"elasticsearch": {
"command": "npx",
"args": [
"-y",
"@octodet/elasticsearch-mcp"
],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
}