Skip to main content
Glama
awesimon

Elasticsearch MCP Server

search

Execute Elasticsearch searches by specifying an index and a query DSL object. Supports size, sort, and filters. Highlights are automatically included in results.

Instructions

Perform an Elasticsearch search with the provided query DSL. Highlights are always enabled.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
indexYesName of the Elasticsearch index to search
queryBodyYesComplete Elasticsearch query DSL object that can include query, size, from, sort, etc.

Implementation Reference

  • The main handler function for the 'search' tool. It takes an Elasticsearch client, index name, and query DSL body, fetches index mappings to determine text fields, enables search highlighting, executes the search, formats the results as MCP text content blocks, and returns them with metadata about total results.
    export async function search(
      esClient: Client,
      index: string,
      queryBody: Record<string, any>
    ) {
      try {
        const mappingResponse = await esClient.indices.getMapping({
          index,
        });
    
        const indexMappings = mappingResponse[index]?.mappings || {};
    
        const searchRequest: estypes.SearchRequest = {
          index,
          ...queryBody,
        };
    
        // enable highlight
        if (indexMappings.properties) {
          const textFields: Record<string, estypes.SearchHighlightField> = {};
    
          for (const [fieldName, fieldData] of Object.entries(
            indexMappings.properties
          )) {
            if (fieldData.type === "text" || "dense_vector" in fieldData) {
              textFields[fieldName] = {};
            }
          }
    
          searchRequest.highlight = {
            fields: textFields,
            pre_tags: ["<em>"],
            post_tags: ["</em>"],
          };
        }
    
        const result = await esClient.search(searchRequest);
    
        const from = queryBody.from || 0;
    
        const contentFragments = result.hits.hits.map((hit) => {
          const highlightedFields = hit.highlight || {};
          const sourceData = hit._source || {};
    
          let content = "";
    
          for (const [field, highlights] of Object.entries(highlightedFields)) {
            if (highlights && highlights.length > 0) {
              content += `${field} (Highlight): ${highlights.join(" ... ")}\n`;
            }
          }
    
          for (const [field, value] of Object.entries(sourceData)) {
            if (!(field in highlightedFields)) {
              content += `${field}: ${JSON.stringify(value)}\n`;
            }
          }
    
          return {
            type: "text" as const,
            text: content.trim(),
          };
        });
    
        const metadataFragment = {
          type: "text" as const,
          text: `Total search results: ${
            typeof result.hits.total === "number"
              ? result.hits.total
              : result.hits.total?.value || 0
          }, Displaying ${result.hits.hits.length} records starting from position ${from}`,
        };
    
        return {
          content: [metadataFragment, ...contentFragments],
        };
      } catch (error) {
        console.error(
          `Search failed: ${error instanceof Error ? error.message : String(error)}`
        );
        return {
          content: [
            {
              type: "text" as const,
              text: `Error: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    } 
  • src/server.ts:71-104 (registration)
    Registration of the 'search' tool on the McpServer. Defines the tool name as 'search', its description, the input schema (index string and queryBody record with Zod refinement), and the handler that delegates to the search function.
    // search with query DSL
    server.tool(
      "search",
      "Perform an Elasticsearch search with the provided query DSL. Highlights are always enabled.",
      {
        index: z
          .string()
          .trim()
          .min(1, "Index name is required")
          .describe("Name of the Elasticsearch index to search"),
    
        queryBody: z
          .record(z.any())
          .refine(
            (val) => {
              try {
                JSON.parse(JSON.stringify(val));
                return true;
              } catch (e) {
                return false;
              }
            },
            {
              message: "queryBody must be a valid Elasticsearch query DSL object",
            }
          )
          .describe(
            "Complete Elasticsearch query DSL object that can include query, size, from, sort, etc."
          ),
      },
      async ({ index, queryBody }) => {
        return await search(esClient, index, queryBody);
      }
    );
  • Input schema for the 'search' tool. 'index' is a required string. 'queryBody' is a required record of any type, validated to be a valid JSON-serializable Elasticsearch query DSL object.
    index: z
      .string()
      .trim()
      .min(1, "Index name is required")
      .describe("Name of the Elasticsearch index to search"),
    
    queryBody: z
      .record(z.any())
      .refine(
        (val) => {
          try {
            JSON.parse(JSON.stringify(val));
            return true;
          } catch (e) {
            return false;
          }
        },
        {
          message: "queryBody must be a valid Elasticsearch query DSL object",
        }
      )
      .describe(
        "Complete Elasticsearch query DSL object that can include query, size, from, sort, etc."
      ),
  • src/server.ts:15-27 (registration)
    Re-export of the search function from the server module, making it available as part of the public API.
    export { 
      listIndices, 
      getMappings, 
      search, 
      getClusterHealth, 
      createIndex, 
      createMapping, 
      bulk, 
      reindex, 
      createIndexTemplate,
      getIndexTemplate,
      deleteIndexTemplate
    }; 
Behavior2/5

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

Only mentions highlights are always enabled. No disclosure of read-only nature, error handling, pagination, or required permissions. With no annotations, more behavioral detail is needed.

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

Conciseness4/5

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

Two concise sentences, front-loaded with the main action. No wasted words, though could be expanded with important behavioral notes without sacrificing conciseness.

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

Completeness2/5

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

Given the complexity of Elasticsearch searches (query DSL), the description lacks return format, pagination behavior, and error context. Incomplete for a search tool.

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 already describes both parameters. The description adds no additional meaning beyond the schema, so baseline 3 is appropriate.

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?

Clearly states it performs an Elasticsearch search with query DSL, identifying the specific verb and resource. Distinguishes from sibling tools that handle index management, bulk operations, etc.

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 over siblings (e.g., bulk, list_indices) or when not to use it. Lacks prerequisites or context.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/awesimon/elasticsearch-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server