Skip to main content
Glama
akshat12000

File System Explorer MCP Server

by akshat12000

search_files

Search for files by name pattern using wildcards in a specified directory to locate specific documents or data.

Instructions

Search for files by name pattern in a directory

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
directoryYesThe directory to search in
patternYesThe filename pattern to search for (supports * wildcards)

Implementation Reference

  • Main handler for the 'search_files' tool in the CallToolRequestSchema switch statement. Parses args with schema, validates directory, calls searchFiles helper, and formats results.
    case "search_files": {
      const { directory, pattern } = SearchFilesArgsSchema.parse(args);
      const safePath = validatePath(directory);
      
      const stats = await fs.stat(safePath);
      if (!stats.isDirectory()) {
        throw new Error("Search path must be a directory");
      }
    
      const results = await searchFiles(safePath, pattern);
      
      if (results.length === 0) {
        return {
          content: [
            {
              type: "text",
              text: `No files matching pattern "${pattern}" found in ${safePath}`
            }
          ]
        };
      }
    
      return {
        content: [
          {
            type: "text",
            text: `Found ${results.length} files matching "${pattern}" in ${safePath}:\n\n` +
                  results.map(file => `📄 ${file}`).join('\n')
          }
        ]
      };
    }
  • Zod schema defining input validation for search_files tool arguments: directory and pattern.
    const SearchFilesArgsSchema = z.object({
      directory: z.string().describe("The directory to search in"),
      pattern: z.string().describe("The filename pattern to search for (supports wildcards)")
    });
  • src/index.ts:187-203 (registration)
    Tool registration in ListToolsRequestSchema response, defining name, description, and inputSchema mirroring the Zod schema.
      name: "search_files",
      description: "Search for files by name pattern in a directory",
      inputSchema: {
        type: "object",
        properties: {
          directory: {
            type: "string",
            description: "The directory to search in"
          },
          pattern: {
            type: "string",
            description: "The filename pattern to search for (supports * wildcards)"
          }
        },
        required: ["directory", "pattern"]
      }
    }
  • Core helper function implementing recursive file search with pattern matching, depth limit, and result cap. Called by the main handler.
    async function searchFiles(directory: string, pattern: string, maxResults: number = 50): Promise<string[]> {
      const results: string[] = [];
      
      async function searchRecursive(currentDir: string, depth: number = 0) {
        // Limit recursion depth to prevent infinite loops
        if (depth > 10 || results.length >= maxResults) return;
        
        try {
          const entries = await fs.readdir(currentDir, { withFileTypes: true });
          
          for (const entry of entries) {
            if (results.length >= maxResults) break;
            
            const fullPath = path.join(currentDir, entry.name);
            
            if (entry.isFile() && matchesPattern(entry.name, pattern)) {
              results.push(fullPath);
            } else if (entry.isDirectory()) {
              // Recursively search subdirectories
              await searchRecursive(fullPath, depth + 1);
            }
          }
        } catch (error) {
          // Skip directories we can't read
          console.error(`Unable to search directory ${currentDir}:`, error);
        }
      }
      
      await searchRecursive(directory);
      return results;
    }
  • Helper utility for glob-style pattern matching used within searchFiles.
    function matchesPattern(filename: string, pattern: string): boolean {
      // Convert glob pattern to regex, being more precise with extensions
      let regexPattern = pattern
        .replace(/\./g, '\\.')  // Escape dots first
        .replace(/\*/g, '.*')   // Convert * to .*
        .replace(/\?/g, '.');   // Convert ? to .
      
      const regex = new RegExp('^' + regexPattern + '$', 'i');
      return regex.test(filename);
    }
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 states the action ('search for files') but doesn't describe key behaviors such as whether the search is recursive, case-sensitive, or supports regex beyond wildcards, nor does it mention performance aspects like timeouts or result limits.

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 function without unnecessary words. It is appropriately sized and front-loaded, making it easy to understand 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 the tool returns (e.g., a list of file paths, metadata), error conditions, or behavioral nuances, leaving significant gaps for a search operation with two required parameters.

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, clearly documenting both parameters. The description adds minimal value beyond the schema by implying the search is based on filename patterns, but it doesn't provide additional context like examples of valid patterns or directory path formats.

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 with a specific verb ('search') and resource ('files'), specifying the search criteria ('by name pattern') and scope ('in a directory'). However, it doesn't explicitly differentiate from sibling tools like 'list_directory' or 'get_file_info', which might also involve file operations.

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 doesn't mention sibling tools like 'list_directory' (which might list all files) or 'get_file_info' (which might retrieve metadata), leaving the agent to infer usage context without explicit 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/akshat12000/FileSystem-MCPServer'

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