Skip to main content
Glama
amittell

firewalla-mcp-server

get_rule_trends

Analyze historical rule creation trends to monitor security policy changes and identify patterns in firewall rule deployments over time.

Instructions

Get historical rule trend data (rules created per day)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
groupNoGet trends for a specific box group

Implementation Reference

  • The primary handler class implementing the get_rule_trends tool logic. Validates 'period' parameter, calls Firewalla API firewalla.getRuleTrends(), processes time-series data, computes summary statistics (avg, max, min active rules, stability score), and returns standardized response.
    export class GetRuleTrendsHandler extends BaseToolHandler {
      name = 'get_rule_trends';
      description =
        'Get historical rule activity trends over time with configurable periods. Optional period parameter. Data cached for 1 hour for performance.';
      category = 'analytics' as const;
    
      constructor() {
        super({
          enableGeoEnrichment: false, // No IP fields in rule trends
          enableFieldNormalization: true,
          additionalMeta: {
            data_source: 'rule_trends',
            entity_type: 'historical_rule_data',
            supports_geographic_enrichment: false,
            supports_field_normalization: true,
            standardization_version: '2.0.0',
          },
        });
      }
    
      async execute(
        _args: ToolArgs,
        firewalla: FirewallaClient
      ): Promise<ToolResponse> {
        try {
          const periodValidation = ParameterValidator.validateEnum(
            _args?.period,
            'period',
            ['1h', '24h', '7d', '30d'],
            false,
            '24h'
          );
    
          if (!periodValidation.isValid) {
            return this.createErrorResponse(
              'Parameter validation failed',
              ErrorType.VALIDATION_ERROR,
              undefined,
              periodValidation.errors
            );
          }
    
          const period = periodValidation.sanitizedValue!;
    
          const trends = await withToolTimeout(
            async () =>
              firewalla.getRuleTrends(period as '1h' | '24h' | '7d' | '30d'),
            this.name
          );
    
          // Validate trends response structure
          if (!trends || typeof trends !== 'object') {
            throw new Error('Invalid trends response: not an object');
          }
    
          if (
            !SafeAccess.getNestedValue(trends, 'results') ||
            !Array.isArray(trends.results)
          ) {
            throw new Error('Invalid trends response: results is not an array');
          }
    
          // Validate each trend item has required properties
          const validTrends = SafeAccess.safeArrayFilter(
            trends.results,
            (trend: any) =>
              trend &&
              typeof SafeAccess.getNestedValue(trend, 'ts') === 'number' &&
              typeof SafeAccess.getNestedValue(trend, 'value') === 'number'
          );
    
          const startTime = Date.now();
    
          const unifiedResponseData = {
            period,
            data_points: validTrends.length,
            trends: SafeAccess.safeArrayMap(validTrends, (trend: any) => ({
              timestamp: SafeAccess.getNestedValue(trend, 'ts', 0),
              timestamp_iso: unixToISOString(
                SafeAccess.getNestedValue(trend, 'ts', 0) as number
              ),
              active_rule_count: SafeAccess.getNestedValue(trend, 'value', 0),
            })),
            summary: {
              avg_active_rules:
                validTrends.length > 0
                  ? Math.round(
                      validTrends.reduce(
                        (sum: number, t: any) =>
                          sum +
                          (SafeAccess.getNestedValue(t, 'value', 0) as number),
                        0
                      ) / validTrends.length
                    )
                  : 0,
              max_active_rules:
                validTrends.length > 0
                  ? Math.max(
                      ...validTrends.map(
                        (t: any) =>
                          SafeAccess.getNestedValue(t, 'value', 0) as number
                      )
                    )
                  : 0,
              min_active_rules:
                validTrends.length > 0
                  ? Math.min(
                      ...validTrends.map(
                        (t: any) =>
                          SafeAccess.getNestedValue(t, 'value', 0) as number
                      )
                    )
                  : 0,
              rule_stability: this.calculateRuleStability(validTrends),
            },
          };
    
          const executionTime = Date.now() - startTime;
          return this.createUnifiedResponse(unifiedResponseData, {
            executionTimeMs: executionTime,
          });
        } catch (error: unknown) {
          const errorMessage =
            error instanceof Error ? error.message : 'Unknown error';
          return this.createErrorResponse(
            `Failed to get rule trends: ${errorMessage}`,
            ErrorType.API_ERROR,
            {
              period: _args?.period || '24h',
              troubleshooting:
                'Check if Firewalla API is accessible and firewall rules are available',
            }
          );
        }
      }
    
      private calculateRuleStability(
        trends: Array<{ ts: number; value: number }>
      ): number {
        if (trends.length < 2) {
          return 100;
        }
    
        const values = trends.map(
          t => SafeAccess.getNestedValue(t, 'value', 0) as number
        );
        const avgValue = values.reduce((sum, val) => sum + val, 0) / values.length;
    
        if (avgValue === 0) {
          return 100;
        }
    
        const variation =
          values.reduce((sum, val, i) => {
            return i > 0 ? sum + Math.abs(val - values[i - 1]) : sum;
          }, 0) /
          (values.length - 1);
    
        const variationPercent = variation / avgValue;
        return Math.max(0, Math.min(100, Math.round((1 - variationPercent) * 100)));
      }
    }
  • Registers the GetRuleTrendsHandler instance in the central ToolRegistry during automatic handler registration in the constructor.
    this.register(new GetRuleTrendsHandler());
  • Defines the MCP tool schema for get_rule_trends, including inputSchema with optional 'group' parameter, exposed in the ListTools response.
      name: 'get_rule_trends',
      description:
        'Get historical rule trend data (rules created per day)',
      inputSchema: {
        type: 'object',
        properties: {
          group: {
            type: 'string',
            description: 'Get trends for a specific box group',
          },
        },
        required: [],
      },
    },
  • Imports the GetRuleTrendsHandler class from './handlers/analytics.js' for use in registry.
    GetRuleTrendsHandler,
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 the tool retrieves historical data but does not specify whether it's read-only, requires authentication, has rate limits, or describes the return format (e.g., time-series data). This leaves significant gaps in understanding the tool's behavior beyond its basic function.

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 front-loads the core functionality ('Get historical rule trend data') and adds specific detail ('rules created per day') without any wasted words. It is appropriately sized for the tool's complexity and structured for quick comprehension.

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 insufficiently complete. It lacks details on behavioral traits (e.g., read-only nature, data format), usage context compared to siblings, and any limitations or prerequisites, making it inadequate for an agent to fully understand how to invoke and interpret results.

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 input schema has 100% description coverage, with the 'group' parameter documented as 'Get trends for a specific box group'. The description does not add any additional meaning beyond this, such as explaining what 'box group' entails or providing examples. Since schema coverage is high, a baseline score of 3 is appropriate as the description does not compensate but also does not detract.

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 ('historical rule trend data') with specific scope ('rules created per day'), making the purpose evident. However, it does not explicitly differentiate from sibling tools like 'get_network_rules' or 'get_network_rules_summary', which might also involve rules data, so it lacks sibling differentiation for 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, such as how it differs from other trend-related tools like 'get_alarm_trends' or rule-related tools like 'get_network_rules'. There is no mention of prerequisites, exclusions, or specific contexts for usage, leaving the agent with minimal 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

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/amittell/firewalla-mcp-server'

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