search
Search Elasticsearch indices using query DSL to retrieve and highlight relevant data from your database.
Instructions
Perform an Elasticsearch search with the provided query DSL. Highlights are always enabled.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| index | Yes | Name of the Elasticsearch index to search | |
| queryBody | Yes | Complete Elasticsearch query DSL object that can include query, size, from, sort, etc. |
Implementation Reference
- src/tools/search.ts:3-94 (handler)The core handler function that executes the Elasticsearch search logic. It fetches mappings, constructs a search request with highlighting for text and dense_vector fields, performs the search, processes hits into highlighted content fragments, adds metadata, and handles errors gracefully.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:72-104 (registration)MCP tool registration for 'search', including Zod input schema for 'index' and 'queryBody', description, and handler that invokes the search function with the Elasticsearch client.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); } );
- src/server.ts:76-100 (schema)Input schema definition using Zod for the 'search' tool parameters: required 'index' string and 'queryBody' as 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." ), },