Skip to main content
Glama
cyberbalsa

OpenSearch MCP Server

by cyberbalsa

getIndexMapping

Retrieve field mappings for a specified index in OpenSearch to analyze and understand data structure for effective querying and log analysis within the Wazuh security framework.

Instructions

Get the field mappings for an index

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
indexYesIndex name to inspect

Implementation Reference

  • index.js:244-304 (registration)
    Full registration of the 'getIndexMapping' tool using FastMCP server.addTool, including schema, description, and execute handler that queries OpenSearch for index mappings and formats them hierarchically.
    server.addTool({
      name: "getIndexMapping",
      description: "Get the field mappings for an index",
      parameters: z.object({
        index: z.string().describe("Index name to inspect"),
      }),
      execute: async (args, { log }) => {
        log.info("Getting index mapping", { index: args.index });
    
        return safeOpenSearchQuery(async () => {
          const response = await client.indices.getMapping({
            index: args.index,
            timeout: "20s"
          });
    
          const mappings = response.body;
          if (!mappings) {
            return `No mappings found for index ${args.index}.`;
          }
          
          const indexName = Object.keys(mappings)[0];
          const properties = mappings[indexName]?.mappings?.properties || {};
          
          if (Object.keys(properties).length === 0) {
            return `No field mappings found for index ${args.index}.`;
          }
    
          let resultText = `## Field Mappings for ${args.index}\n\n`;
          
          function processProperties(props, prefix = '') {
            Object.entries(props).forEach(([field, details]) => {
              const fullPath = prefix ? `${prefix}.${field}` : field;
              
              if (details.type) {
                resultText += `- **${fullPath}**: ${details.type}`;
                if (details.fields) {
                  resultText += ` (has multi-fields)`;
                }
                resultText += '\n';
              }
              
              // Recursively process nested fields
              if (details.properties) {
                processProperties(details.properties, fullPath);
              }
              
              // Process multi-fields
              if (details.fields) {
                Object.entries(details.fields).forEach(([subField, subDetails]) => {
                  resultText += `  - ${fullPath}.${subField}: ${subDetails.type}\n`;
                });
              }
            });
          }
          
          processProperties(properties);
          
          return resultText;
        }, `Failed to get mapping for index ${args.index}.`);
      },
    });
  • The handler function that executes the tool: logs the action, uses safeOpenSearchQuery to call client.indices.getMapping, extracts properties, recursively processes nested and multi-fields, formats as markdown list, and returns the result.
    execute: async (args, { log }) => {
      log.info("Getting index mapping", { index: args.index });
    
      return safeOpenSearchQuery(async () => {
        const response = await client.indices.getMapping({
          index: args.index,
          timeout: "20s"
        });
    
        const mappings = response.body;
        if (!mappings) {
          return `No mappings found for index ${args.index}.`;
        }
        
        const indexName = Object.keys(mappings)[0];
        const properties = mappings[indexName]?.mappings?.properties || {};
        
        if (Object.keys(properties).length === 0) {
          return `No field mappings found for index ${args.index}.`;
        }
    
        let resultText = `## Field Mappings for ${args.index}\n\n`;
        
        function processProperties(props, prefix = '') {
          Object.entries(props).forEach(([field, details]) => {
            const fullPath = prefix ? `${prefix}.${field}` : field;
            
            if (details.type) {
              resultText += `- **${fullPath}**: ${details.type}`;
              if (details.fields) {
                resultText += ` (has multi-fields)`;
              }
              resultText += '\n';
            }
            
            // Recursively process nested fields
            if (details.properties) {
              processProperties(details.properties, fullPath);
            }
            
            // Process multi-fields
            if (details.fields) {
              Object.entries(details.fields).forEach(([subField, subDetails]) => {
                resultText += `  - ${fullPath}.${subField}: ${subDetails.type}\n`;
              });
            }
          });
        }
        
        processProperties(properties);
        
        return resultText;
      }, `Failed to get mapping for index ${args.index}.`);
    },
  • Zod input schema defining the required 'index' parameter as a string.
    parameters: z.object({
      index: z.string().describe("Index name to inspect"),
    }),
  • Helper function used by getIndexMapping to safely execute OpenSearch queries with error handling and user-friendly error messages.
    async function safeOpenSearchQuery(operation, fallbackMessage) {
      try {
        debugLog('Executing OpenSearch query');
        const result = await operation();
        debugLog('OpenSearch query completed successfully');
        return result;
      } catch (error) {
        console.error(`OpenSearch error: ${error.message}`, error);
        debugLog('OpenSearch query failed:', error);
        
        // Check for common OpenSearch errors
        if (error.message.includes('timeout')) {
          throw new UserError(`OpenSearch request timed out. The query may be too complex or the cluster is under heavy load.`);
        } else if (error.message.includes('connect')) {
          throw new UserError(`Cannot connect to OpenSearch. Please check your connection settings in .env file.`);
        } else if (error.message.includes('no such index')) {
          throw new UserError(`The specified index doesn't exist in OpenSearch.`);
        } else if (error.message.includes('unauthorized')) {
          throw new UserError(`Authentication failed with OpenSearch. Please check your credentials in .env file.`);
        }
        
        // For any other errors
        throw new UserError(fallbackMessage || `OpenSearch operation failed: ${error.message}`);
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states a read operation ('Get'), implying it's likely non-destructive, but doesn't disclose behavioral traits such as permissions needed, rate limits, error handling, or what the output includes (e.g., format, pagination). This leaves significant gaps for a tool with no annotation coverage.

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

Conciseness5/5

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

The description is a single, clear sentence with zero waste. It's appropriately sized and front-loaded, directly stating the tool's purpose without unnecessary elaboration, making it highly concise and well-structured.

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 tool has no annotations, no output schema, and a simple input schema, the description is incomplete. It doesn't explain what 'field mappings' entail, the return format, or any behavioral context needed for effective use. For a read operation with no structured support, more detail is warranted.

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?

The schema description coverage is 100%, with the parameter 'index' documented as 'Index name to inspect'. The description adds no additional meaning beyond this, as it only repeats the concept of inspecting an index without providing extra context like valid index names or examples. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Get') and resource ('field mappings for an index'), making the purpose understandable. However, it doesn't differentiate from sibling tools like 'listIndexes' or 'exploreFieldValues', which might also involve index metadata operations, so it lacks sibling distinction.

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?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'listIndexes' and 'exploreFieldValues', there's no indication of whether this is for detailed mapping inspection versus general listing or exploration, leaving usage context unclear.

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

Related 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/cyberbalsa/mcp-opensearch-js'

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