Skip to main content
Glama
amittell

firewalla-mcp-server

get_statistics_by_region

Retrieve top regions by blocked flows to analyze network security threats and identify geographical attack patterns for Firewalla firewall monitoring.

Instructions

Retrieve statistics by region (top regions by blocked flows)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
groupNoGet statistics for specific box group
limitNoMaximum number of results (optional, default: 5)

Implementation Reference

  • The GetStatisticsByRegionHandler class implements the core logic for the 'get_statistics_by_region' tool. It extends BaseToolHandler, calls firewalla.getStatisticsByRegion(), processes regional flow statistics, calculates percentages and top regions, and returns a standardized response.
    export class GetStatisticsByRegionHandler extends BaseToolHandler {
      name = 'get_statistics_by_region';
      description =
        'Get flow statistics grouped by country/region for geographic analysis. No required parameters. Data cached for 1 hour for performance.';
      category = 'analytics' as const;
    
      constructor() {
        super({
          enableGeoEnrichment: false, // Already contains geographic data
          enableFieldNormalization: true,
          additionalMeta: {
            data_source: 'regional_statistics',
            entity_type: 'geographic_flow_statistics',
            supports_geographic_enrichment: false,
            supports_field_normalization: true,
            standardization_version: '2.0.0',
          },
        });
      }
    
      async execute(
        _args: ToolArgs,
        firewalla: FirewallaClient
      ): Promise<ToolResponse> {
        try {
          const stats = await withToolTimeout(
            async () => firewalla.getStatisticsByRegion(),
            this.name
          );
    
          // Validate response structure with comprehensive null/undefined guards
          if (
            !stats ||
            !SafeAccess.getNestedValue(stats, 'results') ||
            !Array.isArray(stats.results)
          ) {
            return this.createSuccessResponse({
              total_regions: 0,
              regional_statistics: [],
              top_regions: [],
              error:
                'No regional statistics available - API response missing results array',
              debug_info: {
                stats_exists: !!stats,
                results_exists: !!stats?.results,
                results_is_array: !!stats?.results && Array.isArray(stats.results),
                actual_structure: stats ? Object.keys(stats) : 'null',
              },
            });
          }
    
          // Calculate total flow count for percentage calculations
          const totalFlowCount = stats.results.reduce((sum: number, stat: any) => {
            return (
              sum +
              (typeof SafeAccess.getNestedValue(stat, 'value') === 'number'
                ? stat.value
                : 0)
            );
          }, 0);
    
          // Process regional statistics with defensive programming
          const regionalStatistics = SafeAccess.safeArrayFilter(
            stats.results,
            (stat: any): stat is any =>
              stat &&
              typeof SafeAccess.getNestedValue(stat, 'value') === 'number' &&
              !!SafeAccess.getNestedValue(stat, 'meta')
          )
            .map((stat: any) => ({
              country_code: SafeAccess.getNestedValue(stat, 'meta.code', 'unknown'),
              flow_count: SafeAccess.getNestedValue(stat, 'value', 0),
              percentage:
                totalFlowCount > 0
                  ? Math.round(
                      ((SafeAccess.getNestedValue(stat, 'value', 0) as number) /
                        totalFlowCount) *
                        100
                    )
                  : 0,
            }))
            .sort((a: any, b: any) => b.flow_count - a.flow_count);
    
          // Get top 5 regions with defensive programming
          const topRegions = SafeAccess.safeArrayFilter(
            stats.results,
            (stat: any): stat is any =>
              stat &&
              typeof SafeAccess.getNestedValue(stat, 'value') === 'number' &&
              SafeAccess.getNestedValue(stat, 'meta')
          )
            .sort(
              (a: any, b: any) =>
                (SafeAccess.getNestedValue(b, 'value', 0) as number) -
                (SafeAccess.getNestedValue(a, 'value', 0) as number)
            )
            .slice(0, 5)
            .map((stat: any) => ({
              country_code: SafeAccess.getNestedValue(stat, 'meta.code', 'unknown'),
              flow_count: SafeAccess.getNestedValue(stat, 'value', 0),
            }));
    
          const startTime = Date.now();
    
          const unifiedResponseData = {
            total_regions: stats.results.length,
            regional_statistics: regionalStatistics,
            top_regions: topRegions,
            total_flow_count: totalFlowCount,
          };
    
          const executionTime = Date.now() - startTime;
          return this.createUnifiedResponse(unifiedResponseData, {
            executionTimeMs: executionTime,
          });
        } catch (error: unknown) {
          const errorMessage =
            error instanceof Error ? error.message : 'Unknown error occurred';
          return this.createErrorResponse(
            `Failed to get statistics by region: ${errorMessage}`,
            ErrorType.API_ERROR
          );
        }
      }
    }
  • The tool handler is registered in the ToolRegistry by instantiating GetStatisticsByRegionHandler and calling register() during registry construction.
    this.register(new GetStatisticsByRegionHandler());
  • The MCP tool schema definition including inputSchema with optional 'group' and 'limit' parameters is hardcoded in the ListToolsRequestHandler response.
    name: 'get_statistics_by_region',
    description:
      'Retrieve statistics by region (top regions by blocked flows)',
    inputSchema: {
      type: 'object',
      properties: {
        group: {
          type: 'string',
          description: 'Get statistics for specific box group',
        },
        limit: {
          type: 'number',
          description:
            'Maximum number of results (optional, default: 5)',
          minimum: 1,
          default: 5,
        },
      },
      required: [],
    },
  • Import of GetStatisticsByRegionHandler from './handlers/analytics.js' in the ToolRegistry module.
    GetStatisticsByRegionHandler,
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 retrieving statistics but doesn't cover critical aspects like whether this is a read-only operation, potential rate limits, authentication requirements, or what the output format looks like. The phrase 'top regions by blocked flows' hints at ranking but lacks detail on sorting or data freshness.

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 purpose ('Retrieve statistics by region') and adds clarifying context ('top regions by blocked flows') without unnecessary words. Every part of the sentence contributes meaning, 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 no annotations and no output schema, the description is incomplete for a tool with 2 parameters. It lacks behavioral details (e.g., read-only nature, error handling) and output information (e.g., what statistics are returned, format). While concise, it doesn't compensate for the missing structured data, leaving significant gaps for an AI agent to understand tool behavior.

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 already fully documents the 'group' and 'limit' parameters. The description adds no additional semantic context about these parameters beyond what's in the schema, such as examples of 'group' values or how 'limit' affects the 'top regions' ranking. Baseline 3 is appropriate when the schema handles parameter documentation.

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 'Retrieve' and the resource 'statistics by region', with additional context about 'top regions by blocked flows' that clarifies the type of statistics. However, it doesn't explicitly differentiate from sibling tools like 'get_simple_statistics' or 'get_statistics_by_box', which might offer similar statistical data.

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 'get_simple_statistics' and 'get_statistics_by_box', there's no indication of the specific use case for regional statistics or how it differs from other statistical tools in the server.

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