Skip to main content
Glama
amittell

firewalla-mcp-server

search_target_lists

Search and filter target lists in Firewalla MSP firewall by name, category, owner, or target domains to manage network security rules.

Instructions

Search target lists with client-side filtering (convenience wrapper around get_target_lists)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNoSearch query for target lists. Supported fields: name:*Social*, owner:global/box_gid, category:social/games/ad/porn/etc, targets:*.facebook.com, notes:"description text". Examples: "category:social", "owner:global AND name:*Block*", "targets:*.gaming.com"
categoryNoFilter by category
ownerNoFilter by owner (global or box gid)
limitNoMaximum number of target lists to return

Implementation Reference

  • SearchTargetListsHandler class implementing the 'search_target_lists' tool. Validates parameters using validateCommonSearchParameters, fetches data via searchTools.search_target_lists, standardizes response with target_lists array containing id, name, category, owner, entry_count, metadata, and query_info.
    export class SearchTargetListsHandler extends BaseToolHandler {
      name = 'search_target_lists';
      description = `Target list searching with comprehensive filtering for categories, ownership, and content analysis.
    
    Search through Firewalla target lists including domains, IPs, and security categories for policy management and analysis.
    
    QUERY EXAMPLES:
    - Category filtering: "category:ad", "category:social_media", "category:malware"
    - Ownership: "owner:global", "owner:custom", "owner:user_defined"
    - Content type: "type:domain", "type:ip", "type:url_pattern"
    - Size filtering: "target_count:>100", "active_targets:>50"
    - Status queries: "enabled:true", "updated:>=2024-01-01"
    
    TARGET LIST MANAGEMENT:
    - Ad blocking lists: "category:ad AND enabled:true"
    - Security lists: "category:malware OR category:phishing OR category:threat"
    - Social media controls: "category:social_media AND owner:custom"
    - Custom domain lists: "owner:user_defined AND type:domain"
    - Large lists analysis: "target_count:>1000 AND category:security"
    
    CONTENT ANALYSIS:
    - Popular categories: group_by:"category" for category distribution
    - List effectiveness: "hit_count:>0 AND enabled:true"
    - Maintenance needed: "updated:<=30d AND enabled:true"
    - Unused lists: "hit_count:0 AND enabled:true"
    
    PERFORMANCE CONSIDERATIONS:
    - Target lists cached for 10 minutes for optimal performance
    - Use specific category filters for faster searches
    - Large lists (>10,000 targets) may have slower response times
    - Aggregate queries provide faster overview statistics
    
    FIELD NORMALIZATION:
    - Categories standardized to lowercase with consistent naming
    - Target counts validated as non-negative numbers
    - Timestamps normalized to ISO format
    - Unknown values replaced with "unknown" for consistency
    
    See the Target List Management guide for configuration details.`;
      category = 'search' as const;
    
      constructor() {
        // Enable field normalization for target lists (no geographic enrichment needed)
        super({
          enableGeoEnrichment: false, // Target lists don't typically contain IP addresses
          enableFieldNormalization: true, // Ensure consistent snake_case field naming across all responses
          additionalMeta: {
            data_source: 'target_lists',
            entity_type: 'target_lists',
            supports_geographic_enrichment: false,
            supports_field_normalization: true,
            standardization_version: '2.0.0',
          },
        });
      }
    
      async execute(
        args: ToolArgs,
        firewalla: FirewallaClient
      ): Promise<ToolResponse> {
        const searchArgs = args as SearchTargetListsArgs;
        try {
          // Validate common search parameters
          const validation = validateCommonSearchParameters(
            searchArgs,
            this.name,
            'target_lists'
          );
    
          if (!validation.isValid) {
            return validation.response;
          }
    
          const searchTools = createSearchTools(firewalla);
          const searchParams: SearchParams = {
            query: searchArgs.query,
            limit: searchArgs.limit,
            offset: searchArgs.offset,
            cursor: searchArgs.cursor,
            sort_by: searchArgs.sort_by,
            sort_order: searchArgs.sort_order,
            group_by: searchArgs.group_by,
            aggregate: searchArgs.aggregate,
          };
    
          const result = await withToolTimeout(
            async () => searchTools.search_target_lists(searchParams),
            this.name
          );
    
          // Create unified response with standardized target list data
          const unifiedResponseData = {
            target_lists: SafeAccess.safeArrayMap(
              result.results,
              (list: TargetList) => ({
                id: SafeAccess.getNestedValue(list as any, 'id', 'unknown'),
                name: SafeAccess.getNestedValue(
                  list as any,
                  'name',
                  'Unknown List'
                ),
                category: SafeAccess.getNestedValue(
                  list as any,
                  'category',
                  'unknown'
                ),
                owner: SafeAccess.getNestedValue(list as any, 'owner', 'unknown'),
                entry_count: SafeAccess.safeArrayAccess(
                  list.targets,
                  arr => arr.length,
                  0
                ),
              })
            ),
            count: SafeAccess.safeArrayAccess(
              (result as any).results,
              arr => arr.length,
              0
            ),
            query_executed: SafeAccess.getNestedValue(result as any, 'query', ''),
            execution_time_ms: SafeAccess.getNestedValue(
              result as any,
              'execution_time_ms',
              0
            ),
            aggregations: SafeAccess.getNestedValue(
              result as any,
              'aggregations',
              null
            ),
            query_info: {
              original_query: searchArgs.query,
              applied_filters: {
                grouping: !!searchArgs.group_by,
                sorting: !!searchArgs.sort_by,
                aggregation: !!searchArgs.aggregate,
              },
            },
          };
    
          // Return unified response
          return this.createUnifiedResponse(unifiedResponseData);
        } catch (error: unknown) {
          if (error instanceof TimeoutError) {
            return createTimeoutErrorResponse(this.name, error.duration, 10000);
          }
    
          const errorMessage =
            error instanceof Error ? error.message : 'Unknown error occurred';
          return createErrorResponse(
            this.name,
            `Failed to search target lists: ${errorMessage}`,
            ErrorType.SEARCH_ERROR
          );
        }
      }
    }
  • Explicit registration of new SearchTargetListsHandler() instance in ToolRegistry constructor's registerHandlers() method, listed as convenience wrapper with client-side filtering.
    this.register(new SearchTargetListsHandler()); // wrapper with client-side filtering
    this.register(new GetNetworkRulesSummaryHandler()); // wrapper around get_network_rules
  • JSON Schema definition for 'search_target_lists' tool provided to MCP clients via ListToolsRequestHandler. Defines input parameters: query (search string), category, owner, limit (1-500, default 100).
    {
      name: 'search_target_lists',
      description:
        'Search target lists with client-side filtering (convenience wrapper around get_target_lists)',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description:
              'Search query for target lists. Supported fields: name:*Social*, owner:global/box_gid, category:social/games/ad/porn/etc, targets:*.facebook.com, notes:"description text". Examples: "category:social", "owner:global AND name:*Block*", "targets:*.gaming.com"',
          },
          category: {
            type: 'string',
            description: 'Filter by category',
          },
          owner: {
            type: 'string',
            description: 'Filter by owner (global or box gid)',
          },
          limit: {
            type: 'number',
            minimum: 1,
            maximum: 500,
            default: 100,
            description: 'Maximum number of target lists to return',
          },
        },
        required: [],
      },
    },
  • setupTools function called from server.ts that initializes ToolRegistry and registers all tools to MCP server by setting CallToolRequestHandler to lookup handlers by name and execute them with FirewallaClient.
    export function setupTools(server: Server, firewalla: FirewallaClient): void {
      // Initialize the tool registry with all 35 handlers
      const toolRegistry = new ToolRegistry();
    
      // Set up the main request handler using the registry
      server.setRequestHandler(CallToolRequestSchema, async request => {
        const { name, arguments: args } = request.params;
    
        const startTime = Date.now();
    
        try {
          // Get handler from the registry
          const handler = toolRegistry.getHandler(name);
          if (!handler) {
            const availableTools = toolRegistry.getToolNames() || [];
            throw new Error(
              `Unknown tool: ${name}. Available tools: ${availableTools.join(', ')}`
            );
          }
    
          // Execute the tool handler with proper error handling
          logger.debug(
            `Executing tool: ${name} with handler: ${handler.constructor.name}`
          );
          const response = await handler.execute(args || {}, firewalla);
    
          // <add success telemetry>
          metrics.count('tool.success');
          metrics.timing('tool.latency_ms', Date.now() - startTime);
          // </add>
    
          return response;
        } catch (error: unknown) {
          // <add error metric>
          metrics.count('tool.error');
          // </add>
          const errorMessage =
            error instanceof Error ? error.message : 'Unknown error occurred';
          logger.error(`Tool execution failed for ${name}:`, error as Error);
    
          // Use centralized error handling
          return createErrorResponse(name, errorMessage, ErrorType.UNKNOWN_ERROR, {
            timestamp: getCurrentTimestamp(),
            error_type:
              error instanceof Error ? error.constructor.name : 'UnknownError',
            available_tools: toolRegistry.getToolNames() || [],
          });
        }
      });
    
      const allToolNames = toolRegistry.getToolNames() || [];
      const categories = [
        'security',
        'network',
        'device',
        'rule',
        'analytics',
        'search',
      ];
      const totalCategories = categories.length;
    
      logger.info(
        `MCP tools setup complete. Registry contains ${allToolNames.length} handlers across ${totalCategories} categories.`
      );
      logger.info(`Registered tools: ${allToolNames.join(', ')}`);
    }
  • Shared validateCommonSearchParameters helper function used by SearchTargetListsHandler (and other search handlers) for input validation: limit, query syntax validation, field sanitization, cursor format, group_by enum checks.
    function validateCommonSearchParameters(
      args: BaseSearchArgs,
      toolName: string,
      entityType: 'flows' | 'alarms' | 'rules' | 'devices' | 'target_lists'
    ): CommonSearchValidationResult {
      // Validate optional limit parameter with default
      const limitValidation = ParameterValidator.validateNumber(
        args.limit,
        'limit',
        {
          required: false,
          defaultValue: 200,
          ...getLimitValidationConfig(toolName),
        }
      );
    
      if (!limitValidation.isValid) {
        return {
          isValid: false,
          response: createErrorResponse(
            toolName,
            'Parameter validation failed',
            ErrorType.VALIDATION_ERROR,
            undefined,
            limitValidation.errors
          ),
        };
      }
    
      // Validate required query parameter
      const queryValidation = ParameterValidator.validateRequiredString(
        args.query,
        'query'
      );
    
      if (!queryValidation.isValid) {
        return {
          isValid: false,
          response: createErrorResponse(
            toolName,
            'Query parameter validation failed',
            ErrorType.VALIDATION_ERROR,
            undefined,
            queryValidation.errors
          ),
        };
      }
    
      // Validate query syntax
      const querySyntaxValidation = validateFirewallaQuerySyntax(args.query);
    
      if (!querySyntaxValidation.isValid) {
        const examples = getExampleQueries(entityType);
        return {
          isValid: false,
          response: createErrorResponse(
            toolName,
            'Invalid query syntax',
            ErrorType.VALIDATION_ERROR,
            {
              query: args.query,
              syntax_errors: querySyntaxValidation.errors,
              examples: examples.slice(0, 3),
              hint: 'Use field:value syntax with logical operators (AND, OR, NOT)',
            },
            querySyntaxValidation.errors
          ),
        };
      }
    
      // Validate field names in the query
      const fieldValidation = QuerySanitizer.validateQueryFields(
        args.query,
        entityType
      );
    
      if (!fieldValidation.isValid) {
        return {
          isValid: false,
          response: createErrorResponse(
            toolName,
            'Query contains invalid field names',
            ErrorType.VALIDATION_ERROR,
            {
              query: args.query,
              documentation:
                entityType === 'alarms'
                  ? 'See /docs/error-handling-guide.md for troubleshooting'
                  : 'See /docs/query-syntax-guide.md for valid field names',
            },
            fieldValidation.errors
          ),
        };
      }
    
      // Validate cursor format if provided
      if (args.cursor !== undefined) {
        const cursorValidation = ParameterValidator.validateCursor(
          args.cursor,
          'cursor'
        );
        if (!cursorValidation.isValid) {
          return {
            isValid: false,
            response: createErrorResponse(
              toolName,
              'Invalid cursor format',
              ErrorType.VALIDATION_ERROR,
              undefined,
              cursorValidation.errors
            ),
          };
        }
      }
    
      // Validate group_by parameter if provided
      if (args.group_by !== undefined) {
        const groupByValidation = ParameterValidator.validateEnum(
          args.group_by,
          'group_by',
          SEARCH_FIELDS[entityType],
          false
        );
    
        if (!groupByValidation.isValid) {
          return {
            isValid: false,
            response: createErrorResponse(
              toolName,
              'Invalid group_by field',
              ErrorType.VALIDATION_ERROR,
              {
                group_by: args.group_by,
                valid_fields: SEARCH_FIELDS[entityType],
                documentation: 'See /docs/query-syntax-guide.md for valid fields',
              },
              groupByValidation.errors
            ),
          };
        }
      }
    
      return {
        isValid: true,
        limit: args.limit,
        query: args.query,
        cursor: args.cursor,
        groupBy: args.group_by,
      };
    }
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 'client-side filtering' and being a 'convenience wrapper', which hints at simplified usage but lacks details on performance implications, error handling, or what 'client-side' entails operationally. For a search tool with zero annotation coverage, this leaves significant behavioral gaps.

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 extremely concise—a single sentence that efficiently conveys the core functionality and relationship to another tool. It's front-loaded with the main purpose and wastes no words, making it easy 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 no annotations and no output schema, the description is incomplete for a search tool with 4 parameters. It lacks details on return values, error conditions, or how the 'client-side filtering' interacts with the parameters. While concise, it doesn't compensate for the missing structured data, leaving users with insufficient context for effective use.

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 all 4 parameters with examples and constraints. The description adds no parameter-specific information beyond what's in the schema, providing only general context about client-side filtering. This meets the baseline of 3 where the schema does the heavy lifting.

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 as 'Search target lists with client-side filtering' and identifies it as a 'convenience wrapper around get_target_lists'. This provides a specific verb (search) and resource (target lists) with operational context. However, it doesn't explicitly differentiate from sibling 'get_target_lists' beyond mentioning it's a wrapper, missing a clear distinction in functionality.

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 mentions 'get_target_lists' but doesn't explain when this wrapper is preferable (e.g., for simpler queries, client-side filtering benefits, or specific use cases). Without such context, users must infer usage from the name and parameters 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

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