Skip to main content
Glama
modelcontextprotocol

Filesystem MCP Server

Official

Search Files

search_files
Read-only

Find files and directories by pattern across folders. Use glob patterns like '.txt' or '**/.log' to locate items when you don't know their exact location.

Instructions

Recursively search for files and directories matching a pattern. The patterns should be glob-style patterns that match paths relative to the working directory. Use pattern like '.ext' to match files in current directory, and '**/.ext' to match files in all subdirectories. Returns full paths to all matching items. Great for finding files when you don't know their exact location. Only searches within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
patternYes
excludePatternsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYes

Implementation Reference

  • Core implementation of the search_files tool logic: recursively searches for files matching a glob pattern within validated paths, respecting exclude patterns and allowed directories.
    export async function searchFilesWithValidation(
      rootPath: string,
      pattern: string,
      allowedDirectories: string[],
      options: SearchOptions = {}
    ): Promise<string[]> {
      const { excludePatterns = [] } = options;
      const results: string[] = [];
    
      async function search(currentPath: string) {
        const entries = await fs.readdir(currentPath, { withFileTypes: true });
    
        for (const entry of entries) {
          const fullPath = path.join(currentPath, entry.name);
    
          try {
            await validatePath(fullPath);
    
            const relativePath = path.relative(rootPath, fullPath);
            const shouldExclude = excludePatterns.some(excludePattern =>
              minimatch(relativePath, excludePattern, { dot: true })
            );
    
            if (shouldExclude) continue;
    
            // Use glob matching for the search pattern
            if (minimatch(relativePath, pattern, { dot: true })) {
              results.push(fullPath);
            }
    
            if (entry.isDirectory()) {
              await search(fullPath);
            }
          } catch {
            continue;
          }
        }
      }
    
      await search(rootPath);
      return results;
    }
  • Zod schema defining the input arguments for the search_files tool: path (search root), pattern (glob pattern), and optional excludePatterns.
    const SearchFilesArgsSchema = z.object({
      path: z.string(),
      pattern: z.string(),
      excludePatterns: z.array(z.string()).optional().default([])
    });
  • Registers the 'search_files' tool with the MCP server, providing title, description, input/output schemas, annotations, and a thin wrapper handler that calls the core search function.
    server.registerTool(
      "search_files",
      {
        title: "Search Files",
        description:
          "Recursively search for files and directories matching a pattern. " +
          "The patterns should be glob-style patterns that match paths relative to the working directory. " +
          "Use pattern like '*.ext' to match files in current directory, and '**/*.ext' to match files in all subdirectories. " +
          "Returns full paths to all matching items. Great for finding files when you don't know their exact location. " +
          "Only searches within allowed directories.",
        inputSchema: {
          path: z.string(),
          pattern: z.string(),
          excludePatterns: z.array(z.string()).optional().default([])
        },
        outputSchema: { content: z.string() },
        annotations: { readOnlyHint: true }
      },
      async (args: z.infer<typeof SearchFilesArgsSchema>) => {
        const validPath = await validatePath(args.path);
        const results = await searchFilesWithValidation(validPath, args.pattern, allowedDirectories, { excludePatterns: args.excludePatterns });
        const text = results.length > 0 ? results.join("\n") : "No matches found";
        return {
          content: [{ type: "text" as const, text }],
          structuredContent: { content: text }
        };
      }
    );
Behavior4/5

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

The annotations indicate readOnlyHint=true, which the description aligns with by describing a search operation without implying modification. The description adds valuable behavioral context beyond annotations: it specifies recursive searching, glob-style pattern usage, path matching relative to the working directory, and the limitation to allowed directories. This enhances the agent's understanding of how the tool behaves in practice.

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 well-structured and front-loaded, starting with the core functionality and following with pattern examples, return value, usage context, and constraints. Each sentence adds value without redundancy, making it efficient and easy for an agent to parse quickly.

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

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity, the presence of annotations (readOnlyHint), and an output schema (which handles return values), the description is complete enough. It covers key aspects like recursive behavior, pattern syntax, use case, and search limitations, providing sufficient context for an agent to invoke the tool correctly without over-explaining.

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?

With 0% schema description coverage, the description compensates by explaining the 'pattern' parameter with examples ('*.ext', '**/*.ext') and its relation to paths. However, it does not detail the 'path' or 'excludePatterns' parameters, leaving gaps in parameter understanding. The baseline is 3 because the description adds some meaning but does not fully cover all parameters.

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 search for files and directories matching a pattern') and resources ('files and directories'). It distinguishes itself from siblings like list_directory or get_file_info by emphasizing pattern-based searching across directories rather than listing or retrieving specific files.

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 on when to use this tool ('Great for finding files when you don't know their exact location') and mentions a constraint ('Only searches within allowed directories'). However, it does not explicitly state when not to use it or name specific alternatives among sibling tools, such as list_directory for simple directory listing without pattern matching.

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/modelcontextprotocol/filesystem'

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