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);
    }

Tool Definition Quality

Score is being calculated. Check back soon.

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