Skip to main content
Glama
cyberbalsa

OpenSearch MCP Server

by cyberbalsa

alertStatistics

Analyze and aggregate security alert statistics by time range, field, and index pattern using OpenSearch MCP Server for actionable insights.

Instructions

Get statistics about security alerts

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fieldNoField to aggregate byrule.level
indexNoIndex patternwazuh-alerts-*
timeRangeNoTime range (e.g., 1h, 24h, 7d)24h

Implementation Reference

  • The main handler function that executes the tool: queries OpenSearch for term aggregations on the specified field over the given time range, computes statistics and percentages, and formats the results.
    execute: async (args, { log }) => {
      log.info("Getting alert statistics", { timeRange: args.timeRange, field: args.field });
    
      return safeOpenSearchQuery(async () => {
        const timeRangeMs = parseTimeRange(args.timeRange);
        const now = new Date();
        const from = new Date(now.getTime() - timeRangeMs);
    
        const response = await client.search({
          index: args.index,
          body: {
            size: 0,
            query: {
              range: {
                timestamp: {
                  gte: from.toISOString(),
                  lte: now.toISOString(),
                },
              },
            },
            aggs: {
              stats: {
                terms: {
                  field: args.field,
                  size: 20,
                },
              },
            },
            timeout: "25s"
          },
        });
    
        const buckets = response.body.aggregations?.stats?.buckets || [];
        const total = buckets.reduce((sum, bucket) => sum + bucket.doc_count, 0);
    
        log.info(`Found statistics for ${total} alerts`, { count: total });
    
        if (total === 0) {
          return "No alerts found in the specified time range.";
        }
    
        let resultText = `## Alert Statistics for the past ${args.timeRange}\n\n`;
        resultText += `Total alerts: ${total}\n\n`;
        
        resultText += `### Breakdown by ${args.field}\n\n`;
        buckets.forEach(bucket => {
          const percentage = ((bucket.doc_count / total) * 100).toFixed(2);
          resultText += `- **${bucket.key}**: ${bucket.doc_count} (${percentage}%)\n`;
        });
    
        return resultText;
      }, `Failed to get alert statistics. The field "${args.field}" may not be aggregatable or the connection timed out.`);
    },
  • Zod schema defining the input parameters for the alertStatistics tool.
    parameters: z.object({
      timeRange: z.string().default("24h").describe("Time range (e.g., 1h, 24h, 7d)"),
      field: z.string().default("rule.level").describe("Field to aggregate by"),
      index: z.string().default("wazuh-alerts-*").describe("Index pattern"),
    }),
  • index.js:581-642 (registration)
    The server.addTool call that registers the alertStatistics tool with FastMCP.
    server.addTool({
      name: "alertStatistics",
      description: "Get statistics about security alerts",
      parameters: z.object({
        timeRange: z.string().default("24h").describe("Time range (e.g., 1h, 24h, 7d)"),
        field: z.string().default("rule.level").describe("Field to aggregate by"),
        index: z.string().default("wazuh-alerts-*").describe("Index pattern"),
      }),
      execute: async (args, { log }) => {
        log.info("Getting alert statistics", { timeRange: args.timeRange, field: args.field });
    
        return safeOpenSearchQuery(async () => {
          const timeRangeMs = parseTimeRange(args.timeRange);
          const now = new Date();
          const from = new Date(now.getTime() - timeRangeMs);
    
          const response = await client.search({
            index: args.index,
            body: {
              size: 0,
              query: {
                range: {
                  timestamp: {
                    gte: from.toISOString(),
                    lte: now.toISOString(),
                  },
                },
              },
              aggs: {
                stats: {
                  terms: {
                    field: args.field,
                    size: 20,
                  },
                },
              },
              timeout: "25s"
            },
          });
    
          const buckets = response.body.aggregations?.stats?.buckets || [];
          const total = buckets.reduce((sum, bucket) => sum + bucket.doc_count, 0);
    
          log.info(`Found statistics for ${total} alerts`, { count: total });
    
          if (total === 0) {
            return "No alerts found in the specified time range.";
          }
    
          let resultText = `## Alert Statistics for the past ${args.timeRange}\n\n`;
          resultText += `Total alerts: ${total}\n\n`;
          
          resultText += `### Breakdown by ${args.field}\n\n`;
          buckets.forEach(bucket => {
            const percentage = ((bucket.doc_count / total) * 100).toFixed(2);
            resultText += `- **${bucket.key}**: ${bucket.doc_count} (${percentage}%)\n`;
          });
    
          return resultText;
        }, `Failed to get alert statistics. The field "${args.field}" may not be aggregatable or the connection timed out.`);
      },
    });
  • Helper function used by the tool to safely execute OpenSearch queries with error handling.
    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}`);
      }
    }
  • Helper function used to parse time range strings (e.g., '24h') into milliseconds.
    function parseTimeRange(timeRange) {
      const unit = timeRange.slice(-1);
      const value = parseInt(timeRange.slice(0, -1));
      
      debugLog('Parsing time range:', timeRange, 'to milliseconds');
      
      switch (unit) {
        case 'h':
          return value * 60 * 60 * 1000; // hours to ms
        case 'd':
          return value * 24 * 60 * 60 * 1000; // days to ms
        case 'w':
          return value * 7 * 24 * 60 * 60 * 1000; // weeks to ms
        case 'm':
          return value * 30 * 24 * 60 * 60 * 1000; // months to ms (approximate)
        default:
          const error = `Invalid time range format: ${timeRange}`;
          debugLog('Error:', error);
          throw new Error(error);
      }
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states this is a 'Get' operation, implying read-only behavior, but doesn't mention any other traits like authentication requirements, rate limits, or what the statistics output looks like (e.g., aggregated counts, trends). 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, efficient sentence that directly states the tool's purpose without any fluff or redundancy. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

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 lack of annotations and output schema, the description is incomplete. It doesn't explain what kind of statistics are returned (e.g., counts, averages, distributions) or how they're formatted, which is critical for a statistical tool. The high schema coverage helps with inputs but not outputs or behavioral context.

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 all three parameters clearly documented in the schema itself. The description adds no additional parameter semantics beyond what's already in the schema, so it meets the baseline score of 3 without compensating or detracting.

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 verb ('Get') and resource ('statistics about security alerts'), making the purpose immediately understandable. However, it doesn't differentiate this tool from potential sibling tools like 'visualizeAlertTrend' or 'searchAlerts' that might also provide statistical insights, which prevents a perfect score.

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 like 'visualizeAlertTrend' or 'searchAlerts'. It lacks any context about use cases, prerequisites, or exclusions, leaving the agent to guess based on tool names alone.

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