Servidor MCP do Elasticsearch Octodet
Visão geral
Servidor MCP Elasticsearch Octodet
O Servidor MCP Elasticsearch Octodet é um poderoso servidor do Protocolo de Contexto de Modelo (MCP) projetado para interação sem costura com clusters Elasticsearch. Ele fornece uma maneira padronizada para aplicações alimentadas por LLM realizarem várias operações, como pesquisar, atualizar e gerenciar dados dentro do Elasticsearch.
Recursos
- Operações Completas do Elasticsearch: Execute operações completas de CRUD em documentos e índices sem esforço.
- Operações em Lote: Melhore o desempenho processando várias operações em uma única chamada de API.
- Atualizações/Exclusões Baseadas em Consulta: Modifique ou remova documentos com base em consultas específicas.
- Gerenciamento de Cluster: Monitore a saúde do seu cluster Elasticsearch, incluindo shards e templates.
- Pesquisa Avançada: Utilize todas as capacidades das consultas DSL do Elasticsearch com suporte embutido para destaque.
Como Instalar
Como um Pacote NPM
Para instalar o Servidor MCP Elasticsearch Octodet globalmente, execute:
npm install -g @octodet/elasticsearch-mcp
Alternativamente, você pode usá-lo diretamente com npx:
npx @octodet/elasticsearch-mcp
A Partir do Código Fonte
- Clone o repositório.
- Instale as dependências necessárias:
npm install
- Construa o servidor:
npm run build
Integração com Clientes MCP
Integração com VS Code
Para integrar com a extensão MCP do VS Code, adicione a seguinte configuração ao seu settings.json
:
"mcp.servers": {
"elasticsearch": {
"command": "npx",
"args": [
"-y", "@octodet/elasticsearch-mcp"
],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "sua_chave_api",
"ES_VERSION": "8"
}
}
}
Integração com Claude Desktop
Para Claude Desktop, configure suas definições da seguinte forma:
{
"mcpServers": {
"elasticsearch": {
"command": "npx",
"args": ["-y", "@octodet/elasticsearch-mcp"],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "sua_chave_api",
"ES_VERSION": "8"
}
}
}
}
Para Desenvolvimento Local
Se você estiver desenvolvendo o servidor MCP localmente, configure seus clientes para usar sua construção local:
{
"mcpServers": {
"elasticsearch": {
"command": "node",
"args": ["caminho/para/build/index.js"],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "sua_chave_api",
"ES_VERSION": "8"
}
}
}
}
Configuração
O servidor pode ser configurado usando as seguintes variáveis de ambiente:
Variável | Descrição | Padrão |
---|---|---|
ES_URL | URL do servidor Elasticsearch | http://localhost:9200 |
ES_API_KEY | Chave API para autenticação | |
ES_USERNAME | Nome de usuário para autenticação | |
ES_PASSWORD | Senha para autenticação | |
ES_CA_CERT | Caminho para o certificado CA customizado | |
ES_VERSION | Versão do Elasticsearch (8 ou 9) | 8 |
ES_SSL_SKIP_VERIFY | Ignorar verificação SSL | false |
ES_PATH_PREFIX | Prefixo de caminho para Elasticsearch |
Ferramentas
O servidor inclui 16 ferramentas MCP para várias operações do Elasticsearch, cada uma documentada com parâmetros obrigatórios e opcionais.
1. Listar Índices
Recupere uma lista de todos os índices disponíveis do Elasticsearch com informações detalhadas.
Parâmetros:
indexPattern
(opcional, string): Padrão para filtrar índices (por exemplo, "logs-", "meu-índice-")
Exemplo:
{
"indexPattern": "logs-*"
}
2. Obter Mapeamentos
Busque os mapeamentos de campo para um índice específico do Elasticsearch.
Parâmetros:
index
(obrigatório, string): O nome do índice para o qual recuperar mapeamentos.
Exemplo:
{
"index": "meu-índice"
}
3. Pesquisar
Realize uma pesquisa no Elasticsearch usando a consulta DSL fornecida e destaque.
Parâmetros:
index
(obrigatório, string): O índice ou índices a serem pesquisados (suporta valores separados por vírgula).queryBody
(obrigatório, objeto): O corpo da consulta DSL do Elasticsearch.highlight
(opcional, booleano): Ativar destaque para os resultados da pesquisa (padrão: true).
Exemplo:
{
"index": "meu-índice",
"queryBody": {
"query": {
"match": {
"content": "termo de pesquisa"
}
},
"size": 10,
"from": 0,
"sort": [{ "_score": { "order": "desc" } }]
},
"highlight": true
}
4. Obter Saúde do Cluster
Obtenha informações de saúde sobre o cluster Elasticsearch.
Parâmetros:
- Nenhum obrigatório.
Exemplo:
{}
5. Obter Shards
Recupere informações sobre shards para todos ou índices específicos.
Parâmetros:
index
(opcional, string): Índice específico para obter informações sobre shards. Se omitido, retorna shards para todos os índices.
Exemplo:
{
"index": "meu-índice"
}
6. Adicionar Documento
Insira um novo documento em um índice específico do Elasticsearch.
Parâmetros:
index
(obrigatório, string): O índice ao qual o documento será adicionado.document
(obrigatório, objeto): O conteúdo do documento a ser adicionado.id
(opcional, string): ID do documento. Se omitido, o Elasticsearch gera um automaticamente.
Exemplo:
{
"index": "meu-índice",
"id": "doc1",
"document": {
"title": "Meu Documento",
"content": "Conteúdo do documento aqui",
"timestamp": "2025-06-23T10:30:00Z",
"tags": ["importante", "rascunho"]
}
}
7. Atualizar Documento
Modifique um documento existente em um índice específico do Elasticsearch.
Parâmetros:
index
(obrigatório, string): O índice que contém o documento.id
(obrigatório, string): O ID do documento a ser atualizado.document
(obrigatório, objeto): O documento parcial com campos a serem atualizados.
Exemplo:
{
"index": "meu-índice",
"id": "doc1",
"document": {
"title": "Título do Documento Atualizado",
"last_modified": "2025-06-23T10:30:00Z"
}
}
8. Deletar Documento
Remova um documento de um índice específico do Elasticsearch.
Parâmetros:
index
(obrigatório, string): O índice que contém o documento.id
(obrigatório, string): O ID do documento a ser deletado.
Exemplo:
{
"index": "meu-índice",
"id": "doc1"
}
9. Atualizar por Consulta
Atualize documentos em um índice do Elasticsearch com base em uma consulta.
Parâmetros:
index
(obrigatório, string): O índice para atualizar documentos.query
(obrigatório, objeto): Consulta do Elasticsearch para corresponder documentos para atualização.script
(obrigatório, objeto): Script a ser executado para atualizar documentos correspondentes.conflicts
(opcional, string): Como lidar com conflitos de versão ("abort" ou "proceed", padrão: "abort").refresh
(opcional, booleano): Se deve atualizar o índice após a operação (padrão: false).
Exemplo:
{
"index": "meu-índice",
"query": {
"term": {
"status": "ativo"
}
},
"script": {
"source": "ctx._source.status = params.newStatus; ctx._source.updated_at = params.timestamp",
"params": {
"newStatus": "inativo",
"timestamp": "2025-06-23T10:30:00Z"
}
},
"conflicts": "proceed",
"refresh": true
}
10. Deletar por Consulta
Deletar documentos em um índice do Elasticsearch com base em uma consulta.
Parâmetros:
index
(obrigatório, string): O índice para deletar documentos.query
(obrigatório, objeto): Consulta do Elasticsearch para corresponder documentos para exclusão.conflicts
(opcional, string): Como lidar com conflitos de versão ("abort" ou "proceed", padrão: "abort").refresh
(opcional, booleano): Se deve atualizar o índice após a operação (padrão: false).
Exemplo:
{
"index": "meu-índice",
"query": {
"range": {
"created_date": {
"lt": "2025-01-01"
}
}
},
"conflicts": "proceed",
"refresh": true
}
11. Operações em Lote
Execute várias operações de documentos em uma única chamada de API para melhorar o desempenho.
Parâmetros:
operations
(obrigatório, array): Array de objetos de operação, cada um contendo:action
(obrigatório, string): O tipo de operação ("index", "create", "update" ou "delete").index
(obrigatório, string): O índice para esta operação.id
(opcional, string): ID do documento (obrigatório para update/delete, opcional para index/create).document
(condicional, objeto): Conteúdo do documento (obrigatório para operações de index/create/update).
Exemplo:
{
"operations": [
{
"action": "index",
"index": "meu-índice",
"id": "doc1",
"document": { "title": "Documento 1", "content": "Conteúdo aqui" }
},
{
"action": "update",
"index": "meu-índice",
"id": "doc2",
"document": { "title": "Título Atualizado" }
},
{
"action": "delete",
"index": "meu-índice",
"id": "doc3"
}
]
}
12. Criar Índice
Crie um novo índice Elasticsearch com configurações e mapeamentos opcionais.
Parâmetros:
index
(obrigatório, string): O nome do índice a ser criado.settings
(opcional, objeto): Configurações do índice, como número de shards, réplicas, etc.mappings
(opcional, objeto): Mapeamentos de campo definindo como os documentos devem ser indexados.
Exemplo:
{
"index": "novo-índice",
"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. Deletar Índice
Delete permanentemente um índice Elasticsearch.
Parâmetros:
index
(obrigatório, string): O nome do índice a ser deletado.
Exemplo:
{
"index": "meu-índice"
}
14. Contar Documentos
Conte documentos em um índice, opcionalmente filtrados por uma consulta.
Parâmetros:
index
(obrigatório, string): O índice para contar documentos.query
(opcional, objeto): Consulta do Elasticsearch para filtrar documentos para contagem.
Exemplo:
{
"index": "meu-índice",
"query": {
"bool": {
"must": [
{ "term": { "status": "ativo" } },
{ "range": { "created_date": { "gte": "2025-01-01" } } }
]
}
}
}
15. Obter Templates
Recupere templates de índice do Elasticsearch.
Parâmetros:
name
(opcional, string): Nome específico do template a ser recuperado. Se omitido, retorna todos os templates.
Exemplo:
{
"name": "template-logs"
}
16. Obter Aliases
Busque aliases de índice do Elasticsearch.
Parâmetros:
name
(opcional, string): Nome específico do alias a ser recuperado. Se omitido, retorna todos os aliases.
Exemplo:
{
"name": "alias-logs"
}
Desenvolvimento
Executando em Modo de Desenvolvimento
Para executar o servidor em modo de observação durante o desenvolvimento, use:
npm run dev
Implementação do Protocolo
Este servidor implementa o Protocolo de Contexto de Modelo para facilitar a comunicação padronizada entre clientes LLM e Elasticsearch. Ele fornece um conjunto abrangente de ferramentas que podem ser invocadas por clientes MCP para realizar várias operações do Elasticsearch.
Adicionando Novas Ferramentas
Para adicionar uma nova ferramenta ao servidor:
- Defina a ferramenta em
src/index.ts
usando o formato de registro de ferramentas do servidor MCP. - Implemente a funcionalidade necessária em
src/utils/elasticsearchService.ts
. - Atualize este README para documentar a nova ferramenta.
Outros Clientes MCP
O Servidor MCP Elasticsearch Octodet pode ser utilizado com qualquer cliente compatível com MCP, incluindo:
- ChatGPT da OpenAI via plugins MCP
- Claude Desktop da Anthropic
- Claude no VS Code
- Aplicações personalizadas usando o SDK MCP
Uso Programático
Você também pode usar o servidor programaticamente em suas aplicações Node.js:
import { createOctodetElasticsearchMcpServer } from "@octodet/elasticsearch-mcp";
import { CustomTransport } from "@modelcontextprotocol/sdk/server";
// Configure a conexão com o Elasticsearch
const config = {
url: "http://localhost:9200",
apiKey: "sua_chave_api",
version: "8",
};
// Crie e inicie o servidor
async function startServer() {
const server = await createOctodetElasticsearchMcpServer(config);
// Conecte-se ao seu transporte personalizado
const transport = new CustomTransport();
await server.connect(transport);
console.log("Servidor MCP Elasticsearch iniciado");
}
startServer().catch(console.error);
Licença
Este projeto está licenciado sob a Licença MIT - veja o arquivo LICENSE para detalhes.
Detalhe
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.
Configuração do Servidor
{
"mcpServers": {
"elasticsearch": {
"command": "npx",
"args": [
"-y",
"@octodet/elasticsearch-mcp"
],
"env": {
"ES_URL": "http://localhost:9200",
"ES_API_KEY": "your_api_key",
"ES_VERSION": "8"
}
}
}
}