Skip to main content
Glama
amittell

firewalla-mcp-server

get_network_rules_summary

Retrieve categorized statistics and counts of network rules to analyze firewall configurations and monitor security policies.

Instructions

Get overview statistics and counts of network rules by category (convenience wrapper)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
active_onlyNoOnly include active rules in summary (default: true)
rule_typeNoFilter by rule type

Implementation Reference

  • Core handler implementation. Validates inputs (limit up to 2000, rule_type, active_only), calls firewalla.getNetworkRules(), processes rules into summary statistics (counts by action/direction/status/target_type, hit stats, age stats), returns structured ToolResponse.
    export class GetNetworkRulesSummaryHandler extends BaseToolHandler {
      name = 'get_network_rules_summary';
      description =
        'Get overview statistics and counts of network rules by category. Requires limit parameter. Data cached for 10 minutes for performance.';
      category = 'rule' as const;
    
      constructor() {
        super({
          enableGeoEnrichment: false, // No IP fields in rule summary statistics
          enableFieldNormalization: true,
          additionalMeta: {
            data_source: 'rule_summary',
            entity_type: 'rule_statistics',
            supports_geographic_enrichment: false,
            supports_field_normalization: true,
            standardization_version: '2.0.0',
          },
        });
      }
    
      async execute(
        args: ToolArgs,
        firewalla: FirewallaClient
      ): Promise<ToolResponse> {
        try {
          // Parameter validation with standardized limits
          const limitValidation = ParameterValidator.validateNumber(
            args?.limit,
            'limit',
            {
              required: false,
              defaultValue: 200,
              ...getLimitValidationConfig(this.name),
            }
          );
          const ruleTypeValidation = ParameterValidator.validateEnum(
            args?.rule_type,
            'rule_type',
            ['block', 'allow', 'timelimit', 'all'],
            false,
            'all'
          );
          const activeOnlyValidation = ParameterValidator.validateBoolean(
            args?.active_only,
            'active_only',
            true
          );
    
          const validationResult = ParameterValidator.combineValidationResults([
            limitValidation,
            ruleTypeValidation,
            activeOnlyValidation,
          ]);
    
          if (!validationResult.isValid) {
            return createErrorResponse(
              this.name,
              'Parameter validation failed',
              ErrorType.VALIDATION_ERROR,
              undefined,
              validationResult.errors
            );
          }
    
          const limit = limitValidation.sanitizedValue! as number;
          const ruleType = ruleTypeValidation.sanitizedValue!;
          const activeOnly = activeOnlyValidation.sanitizedValue!;
    
          // Statistical Analysis Buffer Strategy: User-controlled limit for rule analysis
          //
          // Problem: Rule summary analysis requires processing potentially thousands
          // of rules to generate meaningful statistics. Without limits, this could:
          // - Consume excessive memory for large rule sets (10k+ rules)
          // - Cause slow API responses
          // - Risk timeout failures on resource-constrained systems
          //
          // Solution: Use user-specified limit (validated 1-10000) for statistical analysis.
          // This provides:
          // - User control over memory usage and response time
          // - Predictable memory usage based on user's choice
          // - Consistent with other rule tools' validation patterns
          //
          // The limit is validated to ensure reasonable bounds (1-10000) which allows
          // both lightweight queries and comprehensive enterprise-level analysis.
          const allRulesResponse = await withToolTimeout(
            async () => firewalla.getNetworkRules(undefined, limit),
            this.name
          );
          const allRules = SafeAccess.getNestedValue(
            allRulesResponse,
            'results',
            []
          ) as any[];
    
          // Group rules by various categories for overview
          const rulesByAction = allRules.reduce(
            (acc: Record<string, number>, rule: any) => {
              const action = SafeAccess.getNestedValue(
                rule,
                'action',
                'unknown'
              ) as string;
              acc[action] = (acc[action] || 0) + 1;
              return acc;
            },
            {}
          );
    
          const rulesByDirection = allRules.reduce(
            (acc: Record<string, number>, rule: any) => {
              const direction = SafeAccess.getNestedValue(
                rule,
                'direction',
                'unknown'
              ) as string;
              acc[direction] = (acc[direction] || 0) + 1;
              return acc;
            },
            {}
          );
    
          const rulesByStatus = allRules.reduce(
            (acc: Record<string, number>, rule: any) => {
              const status = SafeAccess.getNestedValue(
                rule,
                'status',
                'active'
              ) as string;
              acc[status] = (acc[status] || 0) + 1;
              return acc;
            },
            {}
          );
    
          const rulesByTargetType = allRules.reduce(
            (acc: Record<string, number>, rule: any) => {
              const targetType = SafeAccess.getNestedValue(
                rule,
                'target.type',
                'unknown'
              ) as string;
              acc[targetType] = (acc[targetType] || 0) + 1;
              return acc;
            },
            {}
          );
    
          // Calculate hit statistics
          const rulesWithHits = allRules.filter((rule: any) => {
            const hitCount = SafeAccess.getNestedValue(
              rule,
              'hit.count',
              0
            ) as number;
            return hitCount > 0;
          });
          const totalHits = allRules.reduce(
            (sum: number, rule: any) =>
              sum + (SafeAccess.getNestedValue(rule, 'hit.count', 0) as number),
            0
          );
          const avgHitsPerRule =
            allRules.length > 0
              ? Math.round((totalHits / allRules.length) * 100) / 100
              : 0;
    
          // Find most recent rule activity
          let mostRecentRuleTs: number | undefined = undefined;
          let oldestRuleTs: number | undefined = undefined;
    
          if (allRules.length > 0) {
            const validTimestamps = allRules
              .map((rule: any) => {
                const ts = SafeAccess.getNestedValue(rule, 'ts', 0) as number;
                const updateTs = SafeAccess.getNestedValue(
                  rule,
                  'updateTs',
                  0
                ) as number;
                return Math.max(ts, updateTs);
              })
              .filter((ts: number) => ts > 0);
    
            const creationTimestamps = allRules
              .map(
                (rule: any) => SafeAccess.getNestedValue(rule, 'ts', 0) as number
              )
              .filter((ts: number) => ts > 0);
    
            if (validTimestamps.length > 0) {
              mostRecentRuleTs = Math.max(...validTimestamps);
            }
    
            if (creationTimestamps.length > 0) {
              oldestRuleTs = Math.min(...creationTimestamps);
            }
          }
    
          const startTime = Date.now();
    
          const unifiedResponseData = {
            total_rules: allRules.length,
            limit_applied: limit,
            summary_timestamp: getCurrentTimestamp(),
            breakdown: {
              by_action: rulesByAction,
              by_direction: rulesByDirection,
              by_status: rulesByStatus,
              by_target_type: rulesByTargetType,
            },
            hit_statistics: {
              total_hits: totalHits,
              rules_with_hits: rulesWithHits.length,
              rules_with_no_hits: allRules.length - rulesWithHits.length,
              average_hits_per_rule: avgHitsPerRule,
              hit_rate_percentage:
                allRules.length > 0
                  ? Math.round((rulesWithHits.length / allRules.length) * 100)
                  : 0,
            },
            age_statistics: {
              most_recent_activity: safeUnixToISOString(
                mostRecentRuleTs,
                undefined
              ),
              oldest_rule_created: safeUnixToISOString(oldestRuleTs, undefined),
              has_timestamp_data:
                mostRecentRuleTs !== undefined || oldestRuleTs !== undefined,
            },
            filters_applied: {
              rule_type: ruleType || 'all',
              active_only: activeOnly,
            },
          };
    
          const executionTime = Date.now() - startTime;
          return this.createUnifiedResponse(unifiedResponseData, {
            executionTimeMs: executionTime,
          });
        } catch (error: unknown) {
          if (error instanceof TimeoutError) {
            return createTimeoutErrorResponse(
              this.name,
              error.duration,
              10000 // Default timeout
            );
          }
    
          const errorMessage =
            error instanceof Error ? error.message : 'Unknown error occurred';
          return this.createErrorResponse(
            `Failed to get network rules summary: ${errorMessage}`
          );
        }
      }
    }
  • MCP protocol input schema definition for the tool, specifying parameters active_only (boolean, default true) and rule_type (string). Used in listTools response.
    {
      name: 'get_network_rules_summary',
      description:
        'Get overview statistics and counts of network rules by category (convenience wrapper)',
      inputSchema: {
        type: 'object',
        properties: {
          active_only: {
            type: 'boolean',
            description:
              'Only include active rules in summary (default: true)',
            default: true,
          },
          rule_type: {
            type: 'string',
            description: 'Filter by rule type',
          },
        },
        required: [],
      },
    },
  • Tool handler registration in ToolRegistry constructor. Instantiates and registers GetNetworkRulesSummaryHandler.
    this.register(new GetNetworkRulesSummaryHandler()); // wrapper around get_network_rules
  • Parameter limit configuration (max 2000 rules for analysis) used by getLimitValidationConfig in the handler for input validation.
    get_network_rules_summary: STANDARD_LIMITS.RULES_SUMMARY,
  • Import of the GetNetworkRulesSummaryHandler class from rules.ts, enabling its registration.
      GetNetworkRulesSummaryHandler,
    } from './handlers/rules.js';
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 mentions the tool is a 'convenience wrapper' and provides 'overview statistics and counts,' but doesn't cover critical aspects like whether it's read-only, its performance characteristics, error handling, or output format. For a tool with no annotation coverage, this is a significant gap in transparency.

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: 'Get overview statistics and counts of network rules by category (convenience wrapper).' It's front-loaded with the core purpose and includes a helpful qualifier. There's no wasted text, 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.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (2 parameters, no output schema, no annotations), the description is minimally adequate. It covers the basic purpose but lacks details on behavior, output, or sibling differentiation. Without annotations or an output schema, more context on what the summary includes would improve completeness, but it's not entirely incomplete.

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%, so the schema fully documents both parameters ('active_only' and 'rule_type'). The description doesn't add any parameter-specific information beyond what's in the schema, such as examples or usage tips. With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't 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 tool's purpose: 'Get overview statistics and counts of network rules by category.' It specifies the verb ('Get') and resource ('network rules'), and adds context about being a 'convenience wrapper.' However, it doesn't explicitly differentiate from siblings like 'get_network_rules' or 'get_rule_trends,' which slightly limits clarity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by mentioning it's a 'convenience wrapper,' suggesting it's for quick summaries rather than detailed data. But it lacks explicit guidance on when to use this tool versus alternatives like 'get_network_rules' or 'get_rule_trends,' and doesn't specify prerequisites or exclusions, leaving usage context somewhat vague.

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