{
  "markdown": "# Elasticsearch MCP Server\n[![npm version](https://badge.fury.io/js/@tocharianou%2Felasticsearch-mcp.svg)](https://www.npmjs.com/package/@tocharianou/elasticsearch-mcp)\n[![Downloads](https://img.shields.io/npm/dm/@tocharianou/elasticsearch-mcp.svg)](https://www.npmjs.com/package/@tocharianou/elasticsearch-mcp)\n[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/TocharianOU/elasticsearch-mcp)\n\n> **Enhanced Elasticsearch MCP Server Solution - Security & Threat Analysis Focused**\n\nThis is a professional security-focused solution maintained by TocharianOU. It enables comprehensive interaction with all Elasticsearch APIs, specifically optimized for security analysis, threat detection, and incident investigation. Features include advanced security monitoring, anomaly detection, threat hunting, root cause analysis, and comprehensive audit capabilities.\n\n**Key Security Features:**\n- Real-time threat detection and security monitoring\n- Advanced machine learning for anomaly detection  \n- Root cause analysis and attack chain tracking\n- Security incident investigation and forensics\n- Compliance monitoring and audit reporting\n\n---\n\n**Note:** This solution is designed for security professionals, SOC teams, and threat analysts.\n\nConnect to your Elasticsearch data directly from any MCP Client (such as Claude Desktop) using the Model Context Protocol (MCP). Interact with your Elasticsearch security data through natural language queries for advanced threat analysis and incident response.\n\n\n## Prerequisites\n\n* An Elasticsearch instance\n* Elasticsearch authentication credentials (API key or username/password)\n* MCP Client (e.g. Claude Desktop) or HTTP client for remote access\n\n## Multi-Version Elasticsearch Support\n\n**Automatically supports Elasticsearch 5.x - 9.x with intelligent version detection:**\n\n| Version | Status | Client | Notes |\n|---------|--------|--------|-------|\n| ES 5.x | ✅ | 5.6.22 | EOL - Basic tools only |\n| ES 6.x | ✅ | 6.8.8 | EOL - ILM available (6.6+) |\n| ES 7.x | ✅ | 7.17.14 | LTS - Full features |\n| ES 8.x | ✅ | 8.19.1 | **Recommended** - Latest features, ES\\|QL (8.11+) |\n| ES 9.x+ | ✅ | Auto-fallback | Future-ready |\n\n**Key Features:**\n- **Automatic version detection** - No manual configuration needed\n- **Smart client selection** - Loads the right client for your ES version\n- **Adaptive features** - Disables unsupported tools (e.g., Data Streams on ES < 7.9, ES|QL on ES < 8.11)\n- **Version-specific optimizations** - Handles API differences transparently\n\n**What happens:**\n```\nConnect → Detect ES version → Load matching client → Register compatible tools\n```\n\n## The Query Harness (v0.9.0)\n\nSince v0.9.0 the server ships a **query harness**: a deterministic layer between\nthe AI model and your cluster. The design philosophy is simple:\n\n> **The model steers; the harness knows.**\n> Intent (\"find failed logins by user\") belongs to the model.\n> Correctness (real field names, aggregatability, version quirks) belongs to the harness.\n\nWhat this means in practice — at the level of principles, not internals:\n\n- **Live truth beats bundled knowledge beats model memory.** Every query is\n  checked against the cluster's actual field capabilities before it runs. A\n  bundled ECS (Elastic Common Schema) vocabulary provides *meaning*; the live\n  cluster provides *existence*. The model's own recollection is never trusted.\n- **Unambiguous mistakes are fixed silently; ambiguous ones become guidance.**\n  The classic example: a spurious `.keyword` suffix on modern ECS mappings is\n  auto-corrected (and the correction is reported); an unknown field blocks the\n  doomed query and returns the nearest real fields instead of a provider error.\n- **Field knowledge stays out of the context window.** The full ECS dictionary\n  (thousands of fields) lives in process memory. The model retrieves only the\n  handful it needs, on demand, via `lookup_fields`.\n- **Every failure must be actionable.** Raw Elasticsearch errors are rewritten\n  with live suggestions and index-naming advice (data stream vs. legacy Beats\n  naming, internal indices that should be accessed via Kibana APIs, and so on).\n- **The model needs zero version knowledge.** Naming eras, API differences and\n  mapping-style differences (legacy `text` + `.keyword` subfield vs. modern\n  bare `keyword`) are absorbed entirely by the harness. The same model behaves\n  identically against ES 5.6 and ES 9.x — verified by a version test matrix\n  covering nine watershed releases (5.6 → 9.0).\n- **An escape hatch always exists.** Validation can be bypassed per call\n  (`skip_lint`) when the model knows better — e.g. runtime fields defined\n  outside the query. The harness assists; it never imprisons.\n\n## SSL/TLS Connection\n\nTo connect to Elasticsearch with a self-signed certificate or in a test environment, you can set the following environment variable:\n\n```bash\nNODE_TLS_REJECT_UNAUTHORIZED=0\n```\n\n> ⚠️ This disables Node.js SSL certificate validation. Use only in development or testing environments. For production, always use a trusted CA certificate.\n\n## Installation & Setup\n\nInstall (or run) the server, point it at your cluster via environment\nvariables, register it in your MCP client, then just start a conversation —\nthe server connects and registers the tools your ES version supports.\n\n### Configuration Options\n\nThe Elasticsearch MCP Server supports the following configuration options:\n\n#### Elasticsearch Configuration\n\n| Environment Variable           | Description                                              | Required |\n|-------------------------------|----------------------------------------------------------|----------|\n| `ES_URL`                      | Your Elasticsearch instance URL                          | Yes      |\n| `ES_API_KEY`                  | Elasticsearch API key for authentication                 | No       |\n| `ES_USERNAME`                 | Elasticsearch username for basic authentication          | No       |\n| `ES_PASSWORD`                 | Elasticsearch password for basic authentication          | No       |\n| `ES_CA_CERT`                  | Path to custom CA certificate for Elasticsearch SSL/TLS  | No       |\n| `NODE_TLS_REJECT_UNAUTHORIZED`| Set to `0` to disable SSL certificate validation         | No       |\n\n#### Transport Mode Configuration (NEW in v0.3.0)\n\n| Environment Variable | Description                                      | Default   | Values          |\n|---------------------|--------------------------------------------------|-----------|-----------------|\n| `MCP_TRANSPORT`     | Transport mode selection                         | `stdio`   | `stdio`, `http` |\n| `MCP_HTTP_PORT`     | HTTP server port (when using HTTP transport)     | `3000`    | 1-65535         |\n| `MCP_HTTP_HOST`     | HTTP server host (when using HTTP transport)     | `localhost` | Any valid host  |\n\n**Transport Mode Details:**\n- **Stdio mode** (default): For Claude Desktop and local MCP clients\n- **HTTP Streamable mode**: Runs as a standalone HTTP server for remote access, API integration, and web applications\n\n### Quick Start\n\n#### Option 1: NPM Installation (Recommended)\n\n1. **Install globally via NPM**\n   ```bash\n   npm install -g @tocharianou/elasticsearch-mcp\n   ```\n\n2. **Run directly**\n   ```bash\n   npx @tocharianou/elasticsearch-mcp\n   ```\n\n#### Option 2: GitHub Release (Standalone Package)\n\n1. **Download release package**\n   - Go to [GitHub Releases](https://github.com/TocharianOU/elasticsearch-mcp/releases)\n   - Download the latest `.tar.gz` file and its checksum files (`.sha256` and `.sha512`)\n\n2. **Verify package integrity**\n   ```bash\n   shasum -a 256 -c elasticsearch-mcp-v*.tar.gz.sha256\n   # Should output: elasticsearch-mcp-v*.tar.gz: OK\n   ```\n\n3. **Extract and use**\n   ```bash\n   mkdir elasticsearch-mcp && cd elasticsearch-mcp\n   tar -xzf ../elasticsearch-mcp-v*.tar.gz\n   \n   # Run with your Elasticsearch credentials\n   ES_URL=https://localhost:9200 ES_API_KEY=your-key node dist/index.js\n   ```\n\n#### Option 3: Source Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone https://github.com/TocharianOU/elasticsearch-mcp.git\n   cd elasticsearch-mcp\n   ```\n\n2. **Install Dependencies**\n   ```bash\n   npm install\n   ```\n\n3. **Build the Project**\n   ```bash\n   npm run build\n   ```\n\n4. **Configure Claude Desktop App**\n   - Open **Claude Desktop App**\n   - Go to **Settings > Developer > MCP Servers**\n   - Click `Edit Config` and add a new MCP Server with the following configuration:\n\n   **For NPM Installation:**\n   ```json\n   {\n     \"mcpServers\": {\n       \"elasticsearch-mcp-server\": {\n         \"command\": \"npx\",\n         \"args\": [\n           \"@tocharianou/elasticsearch-mcp\"\n         ],\n         \"env\": {\n           \"ES_URL\": \"your-elasticsearch-url\",\n           \"ES_USERNAME\": \"elastic\",\n           \"ES_PASSWORD\": \"your_pass\",\n           \"NODE_TLS_REJECT_UNAUTHORIZED\": \"0\"\n         }\n       }\n     }\n   }\n   ```\n\n   **For Source Installation:**\n   ```json\n   {\n     \"mcpServers\": {\n       \"elasticsearch-mcp-server-local\": {\n         \"command\": \"node\",\n         \"args\": [\n           \"/path/to/your/elasticsearch-mcp/dist/index.js\"\n         ],\n         \"env\": {\n           \"ES_URL\": \"your-elasticsearch-url\",\n           \"ES_USERNAME\": \"elastic\",\n           \"ES_PASSWORD\": \"your_pass\",\n           \"NODE_TLS_REJECT_UNAUTHORIZED\": \"0\"\n         }\n       }\n     }\n   }\n   ```\n\n5. **Debugging with MCP Inspector** (optional)\n   ```bash\n   ES_URL=your-elasticsearch-url ES_USERNAME=elastic ES_PASSWORD=your_pass npm run inspector\n   ```\n\n### Installation & Integration Notes\n\n**If `npm install -g` misbehaves:**\n\n- *Permission errors (`EACCES`) on global install* — don't `sudo`. Either skip\n  the global install entirely and let your MCP client run `npx @tocharianou/elasticsearch-mcp`\n  (npx fetches on demand), or set a user-level prefix:\n  `npm config set prefix ~/.npm-global` and add it to your `PATH`.\n- *Slow or blocked registry* — use a mirror for the install only:\n  `npm install -g @tocharianou/elasticsearch-mcp --registry=https://registry.npmmirror.com`.\n- *Node version* — requires Node **18+** (`node --version`). Older Node fails\n  at startup with ESM/fetch errors, not at install time.\n- *`npx` cold start* — the first `npx` run downloads the package; if your MCP\n  client times out on first connect, run `npx @tocharianou/elasticsearch-mcp`\n  once in a terminal to warm the cache, then reconnect.\n- *Fully offline hosts* — use the GitHub Release tarball (Option 2) and point\n  your client at `node /path/to/dist/index.js`; nothing is fetched at runtime.\n\n**Claude Desktop** — Settings → Developer → MCP Servers → Edit Config, then add\nthe JSON block shown above. Restart the app after editing; the server appears\nin the tools list of a new conversation.\n\n**Claude Code (CLI)** — register the server per-project or globally:\n\n```bash\nclaude mcp add elasticsearch \\\n  -e ES_URL=https://your-es:9200 -e ES_API_KEY=your-key \\\n  -- npx @tocharianou/elasticsearch-mcp\n```\n\n**Any other MCP client / platform integration** — run in HTTP mode\n(`MCP_TRANSPORT=http`, see below) and point the client at `http://host:port/mcp`;\nthis is the recommended shape for containerized platforms, one server instance\nper cluster connection.\n\n**Credentials hygiene** — the env vars end up in your client's config file in\nplain text. Prefer a scoped, read-only API key (see *Elasticsearch Access\nControl* below) over superuser credentials.\n\n### Method 3: HTTP Streamable Mode (NEW in v0.3.0)\n\nRun the server as a standalone HTTP service for remote access and API integration:\n\n```bash\n# Start HTTP server (default port 3000)\nMCP_TRANSPORT=http \\\nES_URL=your-elasticsearch-url \\\nES_USERNAME=elastic \\\nES_PASSWORD=your_pass \\\nnpx @tocharianou/elasticsearch-mcp\n\n# Or with custom port and host\nMCP_TRANSPORT=http \\\nMCP_HTTP_PORT=9000 \\\nMCP_HTTP_HOST=0.0.0.0 \\\nES_URL=your-elasticsearch-url \\\nES_USERNAME=elastic \\\nES_PASSWORD=your_pass \\\nnpx @tocharianou/elasticsearch-mcp\n```\n\n**HTTP Streamable Mode Features:**\n- Exposes MCP server at `http://host:port/mcp` endpoint\n- Health check available at `http://host:port/health`\n- Session-based connection management\n- Supports both POST (JSON-RPC requests) and GET (SSE streams)\n- Compatible with any HTTP client or MCP SDK\n\nAny MCP-capable client (or plain JSON-RPC over HTTP) can talk to the `/mcp`\nendpoint: initialize once, keep the returned `mcp-session-id` header on\nsubsequent `tools/list` / `tools/call` requests. Use `/health` for liveness\nchecks.\n\n## Available Tools\n\n| Tool | Description | Min Version |\n|------|-------------|-------------|\n| `list_indices` | List indices with pattern filter, health filter, sorting and token-aware summary | ES 5.x+ |\n| `get_mappings` | Get field mappings with flat/tree/raw modes, field filtering and multi-index compare | ES 5.x+ |\n| `es_search` | Full Query DSL search with auto-highlight, plus harness field validation / auto-fix | ES 5.x+ |\n| `lookup_fields` | Find the right field names: ECS vocabulary intersected with the index's real fields | ES 5.x+ |\n| `execute_es_api` | Execute any ES REST endpoint directly (GET/POST/PUT/DELETE/HEAD) | ES 5.x+ |\n| `get_shards` | Shard info with health analysis, problem detection and recommendations | ES 5.x+ |\n| `list_data_streams` | List and analyze Data Streams with ILM info and backing index details | ES 7.9+ |\n| `esql_query` | Execute ES\\|QL pipe-based queries with harness field validation and tabular output | **ES 8.11+** |\n\n> Tools not supported by your cluster version are automatically skipped at startup.\n> `es_search` and `esql_query` accept `skip_lint: true` to bypass the harness\n> validation for edge cases (e.g. runtime fields defined outside the query).\n\n### ES|QL Query Tool (`esql_query`)\n\nES|QL is Elasticsearch's modern pipe-based query language, ideal for analytics and data exploration without complex JSON DSL.\n\n**Example queries:**\n```\nFROM logs-* | WHERE level == \"error\" | STATS count = COUNT(*) BY service | SORT count DESC | LIMIT 20\nFROM metrics-* | WHERE @timestamp > NOW() - 1 hour | STATS avg_cpu = AVG(cpu.usage) BY host.name\nFROM auditbeat-* | WHERE event.action == \"user_login\" AND event.outcome == \"failure\" | LIMIT 50\n```\n\n**Parameters:**\n- `query` — the ES|QL string (required)\n- `params` — positional parameters replacing `?` placeholders (optional)\n- `include_types` — include column type info in output (optional, default `false`)\n- `break_token_rule` — bypass token limit for large results (optional, default `false`)\n- `skip_lint` — bypass harness field validation (optional, default `false`)\n\n> Automatically registered only on ES 8.11+ clusters.\n\n## Contributing\n\nWe welcome contributions from the community! For details on how to contribute, please see [Contributing Guidelines](/docs/CONTRIBUTING.md).\n\n## How It Works\n\n1. The MCP client (the AI model) decides *what* to look for and calls a tool.\n2. The harness validates the request against the live cluster — fixing what is\n   unambiguous, blocking what would fail, and translating errors into guidance.\n3. Results come back token-bounded and pre-digested (highlights, tables,\n   aggregation summaries), so long investigations stay within context limits.\n\n## Security Analysis Examples\n\n> [!TIP]\n> Here are security-focused queries you can try with your MCP Client.\n\n**Threat Detection:**\n* \"Analyze brute force attack attempts in the past 24 hours\"\n* \"Detect abnormal login behavior and suspicious IP addresses in the system\"\n* \"Identify potential SQL injection attack patterns and malicious requests\"\n* \"Discover DDoS attack signatures and traffic anomalies in network flows\"\n\n**Root Cause Analysis:**\n* \"Trace the complete attack chain and impact scope for specific security incidents\"\n* \"Analyze root causes and propagation paths of system failures\"\n* \"Identify data breach sources and involved sensitive information\"\n* \"Investigate user privilege abuse incidents with timeline and operation records\"\n\n**Threat Intelligence:**\n* \"Create machine learning models to detect zero-day attacks and unknown threats\"\n* \"Establish behavioral baselines and identify activities deviating from normal patterns\"\n* \"Analyze threat levels and attack history of malicious domains and IP addresses\"\n* \"Detect behavioral characteristics and attack patterns of Advanced Persistent Threats (APT)\"\n\n**Real-time Monitoring:**\n* \"Monitor active threats and ongoing attacks in the current system\"\n* \"Detect abnormal data access patterns and privilege escalation behaviors\"\n* \"Discover suspicious network communications and data exfiltration activities\"\n* \"Identify security causes of abnormal system resource consumption and performance degradation\"\n\n## Security Best Practices\n\n> [!WARNING]\n> Avoid using cluster-admin privileges. Create dedicated API keys with limited scope and apply fine-grained access control at the index level to prevent unauthorized data access.\n\n### Package Integrity Verification\n\nWhen downloading release packages, always verify checksums to ensure integrity:\n\n```bash\n# Verify SHA256 checksum\nshasum -a 256 -c elasticsearch-mcp-vX.Y.Z.tar.gz.sha256\n\n# Verify SHA512 checksum\nshasum -a 512 -c elasticsearch-mcp-vX.Y.Z.tar.gz.sha512\n```\n\nThis protects against:\n- Corrupted downloads\n- Tampered packages\n- Man-in-the-middle attacks\n\n### Elasticsearch Access Control\n\nYou can create a dedicated Elasticsearch API key with minimal permissions to control access to your data:\n\n```POST /_security/api_key\n{\n  \"name\": \"es-mcp-server-access\",\n  \"role_descriptors\": {\n    \"mcp_server_role\": {\n      \"cluster\": [\n        \"monitor\"\n      ],\n      \"indices\": [\n        {\n          \"names\": [\n            \"index-1\",\n            \"index-2\",\n            \"index-pattern-*\"\n          ],\n          \"privileges\": [\n            \"read\",\n            \"view_index_metadata\"\n          ]\n        }\n      ]\n    }\n  }\n}\n```\n\n## License\n\nThis project is licensed under the Apache License 2.0.\n\n## Troubleshooting\n\n* Ensure your MCP configuration is correct.\n* Verify that your Elasticsearch URL is accessible from your machine.\n* Check that your authentication credentials (API key or username/password) have the necessary permissions.\n* If using SSL/TLS with a custom CA, verify that the certificate path is correct and the file is readable.\n* Look at the terminal output for error messages.\n\nIf you encounter issues, feel free to open an issue on the GitHub repository.\n",
  "bytes": 18399,
  "sha": "22178afebf93220b099039aa6c16056c83c87e2da1b032fd539d512f02a03f18",
  "repo_slug": "tocharianou/elasticsearch-mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_tocharianou_elasticsearch_85616829/readme"
}