Skip to main content
Glama
elasticsearch-mcp

elasticsearch-mcp

by baburajr

elasticsearch-mcp

适用于 Elasticsearch 的 MCP 服务器,直接基于 REST API 构建(不依赖 elasticsearch-py,因此也适用于 OpenSearch 以及仅暴露 HTTP 接口的托管集群)。

提供 21 个工具,涵盖查询、诊断、映射和集群操作。默认只读,所有写入路径均受门控。

安装

git clone <your-repo> elasticsearch-mcp && cd elasticsearch-mcp
uv sync            # or: pip install -e ".[dev]"
cp .env.example .env
pytest -q

Related MCP server: OpenSearch MCP Server

注册到 Claude Code / Claude Desktop

{
  "mcpServers": {
    "elasticsearch": {
      "command": "uv",
      "args": ["--directory", "/abs/path/elasticsearch-mcp", "run", "elasticsearch-mcp"],
      "env": {
        "ES_MCP_HOSTS": "https://es.internal:9200",
        "ES_MCP_API_KEY": "base64-encoded-api-key",
        "ES_MCP_INDEX_ALLOW": "logs-*,metrics-*",
        "ES_MCP_READ_ONLY": "true"
      }
    }
  }
}

远程 / 共享部署(替代 stdio):

elasticsearch-mcp --transport streamable-http

工具

查询

工具

说明

run_query

执行 Query DSL。限制结果条数、注入超时、拒绝深分页,支持 search_after

generate_dsl

将结构化规范转换为有效 DSL,并针对索引进行校验,返回字段目录

explain_query

对 _validate?rewrite=true + profile 耗时明细 + 逐文档 _explain

count_documents

仅返回匹配数量,不获取命中详情

诊断工具

工具

说明

cluster_health

状态、分片数量、待处理任务,可选节点级堆内存/磁盘/CPU/拒绝次数

index_health

按索引:文档数、存储、段、平均查询和索引延迟、合并次数

shard_分配

_cat/shards 以及 _cluster/allocation/explain 中未分配分片的决策原因

find_slow_queries

按平均查询延迟排序的索引、运行中的搜索任务、线程池拒绝率、慢查询日志阈值

映射

工具

说明

list_indices

索引和别名,包含文档数、大小和存储

get_mapping

扁平化的 字段路径 -> 类型 目录,包含多字段

analyze_text

分析器的分词结果,用于 0 结果匹配查询的调试

put_mapping

添加字段映射变更(写入门控)

操作

工具

说明

list_snapshot_repositories、list_snapshots、snapshot_status

快照清单和进度

create_snapshot

快照所选索引,默认异步执行

restore_snapshot

恢复快照,包含预检以确保打开的索引不存在,并支持重命名

reindex

异步重建索引,支持查询、管道、脚本、切片过滤、节流;返回任务 ID

get_task、cancel_task

轮询或取消长时间运行的任务

cluster_info

版本、发行版以及当前安全策略

配置

所有配置项均使用 ES_MCP_ 前缀,从环境变量或 .env 文件中读取。

配置项

默认值

用途

HOSTS

http://localhost:9200

逗号分隔的地址;在这些可用的之间进行故障转移

API_KEY / USERNAME+PASSWORD / BEARER_TOKEN

–

选择其中一种认证方式

VERIFY_CERTS、CA_CERTS、CLIENT_CERT、CLIENT_KEY

true

TLS

REQUEST_TIMEOUT、CONNECT_TIMEOUT、MAX_REQUEST

30、30、3

重试覆盖 429/502/503/504 和连接错误,采用 jittered backoff 并遵循 Retry-After 头

READ_ONLY

true

所有写入和破坏性操作的唯一总开关

ALLOW_DESTRUCTIVE

false

对 restore、reindex、put_mapping 进行额外的二次门禁(第二道闸门)

INDEX_ALLOW

*

全局允许列表

INDEX_DENY

.*,security-*

全局拒绝列表;拒绝优先级更高

DEFAULT_SIZE、MAX_RESULT_SIZE

10、200

命中数限制

MAX_AGG_BUCKETS

1000

拒绝聚合桶数爆炸

SEARCH_TIMEOUT、TERMINATE_AFTER

30s、未设置

每次查询的自定义超时和提前终止保护

MAX_RESPONSE_CHARS、MAX_SOURCE_CHARS

60000、2000

结果字符数限制,控制 token 使用

AUDIT_LOG_PATH

未设置

每条工具调用及其结果的 JSONL 审计日志

LOG_LEVEL

INFO

日志输出到 stderr;stderr 仍然覆盖写入,这是为了实现 stdio 传输。

安全模型

四层独立防护,全部默认拒绝:

  1. 索引策略 —— 每次调用都检查允许列表和拒绝列表;索引权限拒绝优先;拒绝在集群范围内执行通配符写入。

  2. 只读 —— 除非 READ_ONLY=false,否则可变工具拒绝执行。

  3. 破坏性操作门控(第二层) —— restore、reindex 和 put_mapping 额外需要 ALLOW_DESTRUCTIVE=true,且在调用时显式传入 confirm=true。

  4. 查询限制 —— 命中条数限制、聚合桶上限、嵌套聚合深度上限、深分页拒绝,以及注入搜索超时。

工具会以可读文本的形式返回错误(如 原因(run_query):...),而非抛出异常,让模型可以自行修正,而不是卡住。

推荐的生产环境做法:为 ES 创建专用的 API 密钥,仅对允许的索引授予 read 权限,并设置 READ_ONLY=true;只有在确实需要由助手执行 reindex/restore 时,才另开一个启用写入的实例。

扩展

在 src/es_mcp/tools/ 下添加一个模块,导出 register(server, ctx),并在 server.build_server 中进行接线。使用 ctx.guard 进行策略检查,用 ctx.render 处理输出,这样所有限制自动生效。

Available Tools

34 tools
alias_actionsA

Add or remove index aliases atomically in one request. Pass actions as a JSON array, e.g. [{"add": {"index": "logs-2026", "alias": "logs"}}, {"remove": {"index": "logs-2025", "alias": "logs"}}]. Use this to swap an alias from an old index to a new one with zero downtime after a reindex. Only add/remove are allowed. Every index touched is checked against the write policy. Requires writes enabled and confirm=true.

Inputs: actions (required), confirm. Returns: result

analyze_textA
Read-only

Run text through an analyzer and see the resulting tokens. Use it when a match query returns nothing: it shows exactly how the field's analyzer tokenizes the indexed text vs your search term.

Inputs: text (required), field, index, analyzer. Returns: result

bulk_indexA

Bulk index many documents into one index in a single request. Pass documents as a JSON array of objects; each becomes an index action. Optional id_field names a field to use as the document id. Reports how many succeeded and the first few errors. Much faster than index_document in a loop. Requires writes enabled and confirm=true.

Inputs: index (required), documents (required), confirm, refresh, +1 more. Returns: result

cancel_taskA
Idempotent

Cancel a running task by id. Use for a runaway reindex or a search eating the cluster.

Inputs: task_id (required), confirm. Returns: result

cat_nodesA
Read-only

List cluster nodes with role, version, heap/RAM/CPU/load, and master flag. Use it to spot a hot node, a version mismatch across nodes, or which node is master.

Inputs: no named parameters. Returns: result

close_pitB
Read-only

Close a point-in-time by its pit_id to free cluster resources. Call after paging finishes.

Inputs: pit_id (required). Returns: result

cluster_healthA
Read-only

Cluster health overview: status, node counts, active/relocating/initializing/unassigned shards, pending tasks, and (optionally) per-index health. Start troubleshooting here.

Inputs: level, include_nodes. Returns: result

cluster_infoA
Read-only

Cluster name, version, distribution, and the safety policy this server is running under.

Inputs: no named parameters. Returns: result

count_documentsA
Read-only

Count matching documents without returning hits. Cheap way to size a query before running it.

Inputs: index (required), query. Returns: result

create_snapshotA

Create a snapshot of selected indices into a repository. Non-blocking by default: returns immediately, poll with snapshot_status. Requires writes enabled and confirm=true.

Inputs: snapshot (required), repository (required), confirm, indices, +2 more. Returns: result

delete_by_queryA
Destructive

Delete documents matching a query from an index. DESTRUCTIVE and irreversible. A query is mandatory: match_all is refused so you cannot wipe an index by accident. Runs asynchronously (wait_for_completion=false) and returns a task_id to poll with get_task. Reports how many documents match before deleting. Requires writes enabled, ES_MCP_ALLOW_DESTRUCTIVE=true, and confirm=true.

Inputs: index (required), query (required), slices, confirm, +2 more. Returns: result

explain_queryA
Read-only

Explain a query three ways: (1) _validate/query?rewrite=true shows how ES rewrites it and why it may be invalid, (2) profile=true gives per-component timing to find the slow clause, (3) if doc_id is given, _explain shows why that document matched or did not, with scoring detail.

Inputs: index (required), query (required), doc_id, profile. Returns: result

field_capsA
Read-only

Show the capabilities of one or more fields across indices via _field_caps: the type(s) each field has, whether it is searchable and aggregatable. The key use is catching a field mapped as different types in different indices (e.g. long in one, keyword in another), which breaks queries across an index pattern. Pass fields as a comma list or *.

Inputs: index (required), fields. Returns: result

find_slow_queriesA
Read-only

Find what is slow. Combines: indices ranked by average query latency (_stats), currently running search tasks with elapsed time (_tasks), search thread-pool queue/rejection counts per node, and the configured search slowlog thresholds per index (so you know whether slowlog is even on). Use top_n to control how many indices come back.

Inputs: index, top_n, min_avg_ms. Returns: result

generate_dslA
Read-only

Build Elasticsearch Query DSL from a structured spec, then validate it against the real index. Supply spec as JSON with any of: text, text_fields, filters [{field, op, value}], must_not, should, time_field/time_from/time_to, sort, size, aggs [{name, type, field, size, interval}], highlight_fields, source_includes. Ops: eq, neq, in, not_in, gt, gte, lt, lte, exists, missing, prefix, wildcard, match, match_phrase. Returns the generated DSL plus validation result and a field catalog so you can correct field names before running it.

Inputs: spec (required), index (required), validate. Returns: result

get_mappingA
Read-only

Get the mapping for an index. Returns a flattened field catalog (field path -> type, including multi-fields like .keyword) which is what you need to write correct queries, plus dynamic templates and total field count. Set raw=true for the untouched mapping JSON.

Inputs: index (required), raw, field_filter. Returns: result

get_taskA
Read-only

Poll a long-running task (reindex, update_by_query, delete_by_query) for progress and errors.

Inputs: task_id (required), wait_for_completion. Returns: result

index_documentA

Index (create or overwrite) a single document into an index. Pass doc as a JSON object. Optional doc_id: given, it overwrites that id; omitted, ES assigns one. Set refresh=true to make it searchable immediately (slower). Requires writes enabled and confirm=true.

Inputs: index (required), document (required), doc_id, confirm, +1 more. Returns: result

index_healthB
Read-only

Per-index health and size: status, docs, store size, primaries/replicas, segment count, refresh and merge stats, plus search/index throughput. Pass an index pattern to narrow it down.

Inputs: index, include_settings. Returns: result

list_indicesA
Read-only

List indices, data streams and aliases matching a pattern, with doc counts and store size.

Inputs: pattern, include_aliases. Returns: result

list_snapshot_repositoriesA
Read-only

List registered snapshot repositories with their type and settings (bucket, base_path, ...).

Inputs: no named parameters. Returns: result

list_snapshotsA
Read-only

List snapshots in a repository with state, start/end time, duration, indices count, shard failures and size. Use this before restoring to pick the right snapshot.

Inputs: repository (required), verbose, snapshot. Returns: result

open_pitA
Read-only

Open a point-in-time (PIT) against an index and return its pit_id. A PIT freezes the data view so you can page through a large result set consistently with paged_search, past the 10000 deep-paging limit. Always close it with close_pit when done; keep_alive controls how long ES holds it open.

Inputs: index (required), keep_alive. Returns: result

put_mappingA
Destructive

Add new fields to an existing index mapping. Only additive changes are possible in Elasticsearch; changing an existing field type requires reindex. Blocked unless the server runs with writes enabled, and requires confirm=true.

Inputs: index (required), properties (required), confirm. Returns: result

reindexA
Destructive

Copy documents from a source index to a destination, optionally filtered by a query and transformed by a pipeline or script. Runs asynchronously (wait_for_completion=false) and returns a task_id to poll with get_task. Use this to change a field type, reshard, or migrate data. Requires writes enabled, ES_MCP_ALLOW_DESTRUCTIVE=true, and confirm=true.

Inputs: dest_index (required), source_index (required), query, slices, +6 more. Returns: result

restore_snapshotA
Destructive

Restore indices from a snapshot. DESTRUCTIVE: an index that already exists must be closed or renamed via rename_pattern/rename_replacement, otherwise the restore fails. Requires writes enabled, ES_MCP_ALLOW_DESTRUCTIVE=true, and confirm=true.

Inputs: indices (required), snapshot (required), repository (required), confirm, +4 more. Returns: result

run_queryA
Read-only

Execute an Elasticsearch search against an index or alias. Accepts a full Query DSL body (JSON string or object). Size is capped by server policy, a search timeout is injected, and deep paging is rejected. Returns hits, aggregations, timing and shard stats. Use search_after for pagination beyond 10k.

Inputs: index (required), size, sort, from_, +6 more. Returns: result

shard_allocationA
Read-only

Shard placement and why shards are unassigned. Returns _cat/shards, per-node disk usage, and for any UNASSIGNED shard the cluster allocation explanation (decider-level reasons: disk watermark, awareness, filtering, max_retries). This is the tool for a yellow/red cluster.

Inputs: index, only_problems. Returns: result

snapshot_statusA
Read-only

Detailed progress of running or recent snapshots: per-shard stage, bytes done vs total.

Inputs: snapshot, repository. Returns: result

sql_queryA
Read-only

Run an Elasticsearch SQL query via the _sql API. Good for quick aggregate/filter questions without hand-writing Query DSL, e.g. SELECT status, COUNT() FROM "logs-" WHERE code >= 500 GROUP BY status. Only SELECT is allowed. The index in FROM is checked against the allow/deny policy. Row count is capped by fetch_size (server result-size limit applies). Returns columns and rows; if there are more rows a cursor is returned to pass back as the cursor argument.

Inputs: query, cursor, fetch_size. Returns: result

sql_translateA
Read-only

Translate an Elasticsearch SQL SELECT into the equivalent native Query DSL via _sql/translate, without running it. Use this to learn the DSL for a query, then hand the DSL to run_query for full control (search_after, routing, profiling).

Inputs: query (required). Returns: result

update_by_queryA
Destructive

Update documents in place by query, using a painless script. DESTRUCTIVE and irreversible. A query is mandatory: match_all is refused so you cannot rewrite a whole index by accident. Runs asynchronously; returns a task_id to poll with get_task. Reports how many documents match before updating. Requires writes enabled, ES_MCP_ALLOW_DESTRUCTIVE=true, and confirm=true.

Inputs: index (required), query (required), script_source (required), slices, +4 more. Returns: result

update_settingsA
Destructive

Update dynamic index settings such as number_of_replicas, refresh_interval, max_result_window, or blocks.*. Static settings (e.g. number_of_shards) cannot be changed on a live index and are refused. Requires writes enabled, ES_MCP_ALLOW_DESTRUCTIVE=true, and confirm=true.

Inputs: index (required), settings (required), confirm. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 34 tools

    Disambiguation5/5

    Each tool addresses a distinct concern: query execution, DSL generation, SQL translation, pagination, health, snapshots, async tasks, and writes. Even the seemingly similar search tools are clearly separated by their input format and use case, so an agent can select the right one with confidence.

    Naming Consistency3/5

    Many names follow a verb_noun pattern like list_indices, create_snapshot, and run_query, but there are many noun-first or adjective-noun exceptions such as cluster_health, shard_allocation, field_caps, snapshot_status, sql_query, and bulk_index. The naming is readable and snake_case throughout, but the conventions are mixed enough that the pattern is not predictable.

    Tool Count2/5

    34 tools is a heavy surface for an agent to navigate, especially since several areas such as cluster diagnostics, query generation, and snapshot management could be consolidated. While the breadth is understandable for Elasticsearch, the count exceeds what is typically needed for a coherent, easy-to-use tool set.

    Completeness3/5

    The server covers a wide range of operations: search, query generation, SQL, mappings, cluster health, slow-query investigation, snapshots, reindexing, async tasks, settings, aliases, and document writes. However, some core lifecycle operations are missing: no create_index, delete_index, close/open index, get document by id, delete snapshot, or single-document delete, which can create dead ends in common workflows.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      D
      maintenance
      An MCP server that enables interaction with Elasticsearch and OpenSearch clusters for searching documents and managing indices. It provides tools for cluster health monitoring, index configuration, and general API requests.
      16
      Apache 2.0
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables LLMs to interact with OpenSearch clusters to monitor cluster health, manage indices, and perform data searches. It provides a standardized interface for real-time OpenSearch operations within MCP-compatible environments like Open WebUI.
      -
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables AI assistants to interact with OpenSearch clusters for searching indices, retrieving mappings, and managing shards through the MCP protocol.
      Apache 2.0
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables read-only interaction with Elasticsearch, supporting listing indices, retrieving mappings, and executing search/aggregation queries via MCP.
      -