Skip to main content
Glama
rawr-ai

Filesystem MCP Server

find_files_by_extension

Search directories recursively to locate files by specific extension, including subdirectories. Specify path, extension, depth, and results limit. Ideal for finding XML, JSON, or other file types efficiently.

Instructions

Recursively find all files with a specific extension. Searches through all subdirectories from the starting path. Extension matching is case-insensitive. Returns full paths to all matching files. Requires maxDepth (default 2) and maxResults (default 10) parameters. Perfect for finding all XML, JSON, or other file types in a directory structure. Only searches within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
excludePatternsNo
extensionYesFile extension to search for (e.g., "xml", "json", "ts")
maxDepthYesMaximum directory depth to search. Must be a positive integer. Handler default: 2.
maxResultsYesMaximum number of results to return. Must be a positive integer. Handler default: 10.
pathYes

Implementation Reference

  • Main handler function that executes the tool: parses input arguments using the schema, validates the starting path, calls the helper function findFilesByExtension, and returns the list of matching files or a no-match message.
    export async function handleFindFilesByExtension(
      args: unknown,
      allowedDirectories: string[],
      symlinksMap: Map<string, string>,
      noFollowSymlinks: boolean
    ) {
      const parsed = parseArgs(FindFilesByExtensionArgsSchema, args, 'find_files_by_extension');
      const { path: startPath, extension, excludePatterns, maxDepth, maxResults } = parsed;
      const validPath = await validatePath(startPath, allowedDirectories, symlinksMap, noFollowSymlinks);
      const results = await findFilesByExtension(
        validPath,
        extension,
        excludePatterns,
        maxDepth,
        maxResults
      );
      return {
        content: [{ type: "text", text: results.length > 0 ? results.join("\n") : "No matching files found" }],
      };
    }
  • TypeBox schema definition for the tool's input arguments, including path, extension, optional excludePatterns, maxDepth, and maxResults. Also exports the corresponding TypeScript type.
    export const FindFilesByExtensionArgsSchema = Type.Object({
      path: Type.String(),
      extension: Type.String({ description: 'File extension to search for (e.g., "xml", "json", "ts")' }),
      excludePatterns: Type.Optional(
        Type.Array(Type.String(), { default: [] })
      ),
      maxDepth: Type.Integer({
        minimum: 1,
        description: 'Maximum directory depth to search. Must be a positive integer. Handler default: 2.'
      }),
      maxResults: Type.Integer({
        minimum: 1,
        description: 'Maximum number of results to return. Must be a positive integer. Handler default: 10.'
      })
    });
    export type FindFilesByExtensionArgs = Static<typeof FindFilesByExtensionArgsSchema>;
  • Core utility function that recursively searches for files with the given extension starting from rootPath, respecting maxDepth, maxResults, and excludePatterns using minimatch.
    export async function findFilesByExtension(
      rootPath: string,
      extension: string,
      excludePatterns: string[] = [],
      maxDepth: number = 2, // Default depth
      maxResults: number = 10 // Default results
    ): Promise<ReadonlyArray<string>> {
      const results: string[] = [];
      
      // Normalize the extension (remove leading dot if present)
      let normalizedExtension = extension.toLowerCase();
      if (normalizedExtension.startsWith('.')) {
        normalizedExtension = normalizedExtension.substring(1);
      }
      
      async function searchDirectory(currentPath: string, currentDepth: number) {
        // Stop if max depth is reached
        if (currentDepth >= maxDepth) {
          return;
        }
        
        // Stop if max results are reached
        if (results.length >= maxResults) {
          return;
        }
        const entries = await fsPromises.readdir(currentPath, { withFileTypes: true });
    
        for (const entry of entries) {
          const fullPath = path.join(currentPath, entry.name);
    
          // Check if path matches any exclude pattern
          const relativePath = path.relative(rootPath, fullPath);
          const shouldExclude = excludePatterns.some(pattern => {
            const globPattern = pattern.includes('*') ? pattern : `**/${pattern}/**`;
            return minimatch(relativePath, globPattern, { dot: true });
          });
    
          if (shouldExclude) {
            continue;
          }
    
          if (entry.isFile()) {
            // Check if file has the requested extension
            const fileExtension = path.extname(entry.name).toLowerCase().substring(1);
            if (fileExtension === normalizedExtension) {
              if (results.length < maxResults) {
                results.push(fullPath);
              }
              // Check again if max results reached after adding
              if (results.length >= maxResults) {
                return; // Stop searching this branch
              }
            }
          } else if (entry.isDirectory()) {
            // Recursively search subdirectories
            // Check results length before recursing
            if (results.length < maxResults) {
              await searchDirectory(fullPath, currentDepth + 1);
            }
          }
        }
      }
    
      await searchDirectory(rootPath, 0); // Start search at depth 0
      return results;
    }
  • index.ts:238-244 (registration)
    Registration of the tool handler in the toolHandlers object, mapping 'find_files_by_extension' to the handleFindFilesByExtension function with server context parameters.
    find_files_by_extension: (a: unknown) =>
      handleFindFilesByExtension(
        a,
        allowedDirectories,
        symlinksMap,
        noFollowSymlinks,
      ),
  • index.ts:310-310 (registration)
    Tool metadata registration in the allTools array, defining the name and description used when adding the tool to the MCP server.
    { name: "find_files_by_extension", description: "Find files by extension" },
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden and does well by disclosing key behaviors: recursive search, case-insensitive matching, returns full paths, default parameter values, and the constraint 'Only searches within allowed directories.' It lacks details on error handling or performance limits, but covers essential operational traits.

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 front-loaded with core functionality, uses concise sentences without redundancy, and each sentence adds value (e.g., explaining defaults, use cases, and constraints). It is appropriately sized for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/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 provides good coverage of behavior, parameters, and constraints. It could improve by detailing the return format (e.g., list structure) or error conditions, but it is largely complete for a search tool with moderate complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 60%, and the description adds meaningful context beyond the schema: it explains that 'maxDepth' and 'maxResults' have defaults (2 and 10), clarifies the recursive nature and case-insensitivity of extension matching, and mentions the 'allowed directories' constraint, which compensates well for the coverage gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/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 specific verbs ('recursively find all files') and resources ('files with a specific extension'), distinguishing it from siblings like 'search_files' or 'list_directory' by emphasizing extension-based filtering and recursive traversal.

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

Usage Guidelines4/5

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

The description provides clear context for when to use it ('Perfect for finding all XML, JSON, or other file types in a directory structure') but does not explicitly mention when not to use it or name specific alternatives among the sibling tools, such as 'search_files' for broader searches.

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

Related 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/rawr-ai/mcp-filesystem'

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