Skip to main content
Glama
cyberbalsa

OpenSearch MCP Server

by cyberbalsa

exploreFieldValues

Analyze and retrieve possible values for a specific field within an OpenSearch index, with options to filter results and limit the number of returned values.

Instructions

Explore possible values for a field in an index

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fieldYesField name to explore
indexYesIndex pattern to search
maxValuesNoMaximum number of values to return
queryNoOptional query to filter documents*

Implementation Reference

  • The execute handler function for the exploreFieldValues tool. Performs an OpenSearch aggregation (terms) on the specified field to retrieve top values, counts, and percentages.
      execute: async (args, { log }) => {
        log.info("Exploring field values", { 
          index: args.index,
          field: args.field,
          query: args.query 
        });
    
        return safeOpenSearchQuery(async () => {
          const response = await client.search({
            index: args.index,
            body: {
              size: 0,
              query: {
                query_string: {
                  query: args.query
                }
              },
              aggs: {
                field_values: {
                  terms: {
                    field: args.field,
                    size: args.maxValues
                  }
                }
              },
              timeout: "25s"
            }
          });
    
          const buckets = response.body.aggregations?.field_values?.buckets || [];
          const total = response.body.hits.total?.value || 0;
          
          if (buckets.length === 0) {
            return `No values found for field "${args.field}" in index ${args.index}.\n\nPossible reasons:\n- The field does not exist\n- The field is not indexed for aggregations\n- No documents match your query\n- The field has no values`;
          }
    
          let resultText = `## Values for field "${args.field}" in ${args.index}\n\n`;
          resultText += `Found ${total} matching documents. Top ${buckets.length} values:\n\n`;
          
          // Calculate percentage of total for each value
          let totalCount = buckets.reduce((sum, bucket) => sum + bucket.doc_count, 0);
          
          // Format results as a table
          resultText += "| Value | Count | Percentage |\n";
          resultText += "|-------|-------|------------|\n";
          
          buckets.forEach(bucket => {
            const percentage = ((bucket.doc_count / totalCount) * 100).toFixed(2);
            resultText += `| ${bucket.key} | ${bucket.doc_count} | ${percentage}% |\n`;
          });
          
          return resultText;
        }, `Failed to explore values for field "${args.field}" in index ${args.index}.`);
      },
    });
  • Zod schema defining input parameters for the exploreFieldValues tool: index, field, query, maxValues.
    parameters: z.object({
      index: z.string().describe("Index pattern to search"),
      field: z.string().describe("Field name to explore"),
      query: z.string().default("*").describe("Optional query to filter documents"),
      maxValues: z.number().default(20).describe("Maximum number of values to return"),
    }),
  • index.js:307-307 (registration)
    Initial registration of the exploreFieldValues tool with name and description.
    server.addTool({
  • Helper function used by exploreFieldValues (and other tools) to safely execute OpenSearch queries with error handling and user-friendly 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 the full burden of behavioral disclosure. It states the tool explores values but doesn't cover critical aspects like whether it's read-only or mutative, performance characteristics (e.g., rate limits), error handling, or output format. For a tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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, efficient sentence that directly states the tool's purpose without unnecessary words. It's front-loaded and appropriately sized, making it easy to parse quickly while conveying the core functionality.

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 moderate complexity (4 parameters including optional ones), the description is incomplete. It lacks details on behavioral traits, output expectations, and usage context, making it insufficient for an agent to fully understand how to invoke and interpret results without additional inference.

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 description coverage is 100%, meaning all parameters are documented in the input schema. The description adds minimal value beyond the schema by implying the tool explores values for a field in an index, but it doesn't provide additional context like typical use cases or constraints not in the schema. This meets the baseline for high schema coverage.

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 'Explore possible values for a field in an index' clearly states the tool's purpose with specific verbs ('explore') and resources ('field', 'index'), making it understandable. However, it doesn't explicitly distinguish this tool from siblings like 'getIndexMapping' or 'searchLogs', which might also involve field or index operations, leaving some ambiguity about uniqueness.

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. It doesn't mention prerequisites, exclusions, or compare it to sibling tools such as 'getIndexMapping' (which might provide field metadata) or 'searchLogs' (which might filter values), leaving the agent to infer usage context without explicit direction.

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