Skip to main content
Glama
modelcontextprotocol

Filesystem MCP Server

Official

Search Files

search_files
Read-only

Recursively search for files and directories by glob patterns. Return full paths to matching items, solving the problem of locating files in unknown directories.

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

  • Registers the 'search_files' tool on the MCP server with title, description, input/output schemas, and the handler 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 }
        };
      }
    );
  • The async handler function for the 'search_files' tool. Validates the path, then delegates to searchFilesWithValidation to find matching files recursively. Returns joined results or 'No matches found'.
    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 }
      };
    }
  • Zod schema for search_files arguments: path (string), pattern (string), and optional excludePatterns (string array, default []).
    const SearchFilesArgsSchema = z.object({
      path: z.string(),
      pattern: z.string(),
      excludePatterns: z.array(z.string()).optional().default([])
    });
  • Core implementation of searchFilesWithValidation. Recursively walks the directory tree, uses minimatch glob matching against the pattern, and respects excludePatterns 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;
    }
Behavior4/5

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

Annotations already provide readOnlyHint=true, indicating no side effects. The description adds value by detailing recursive behavior, pattern syntax, and the constraint of searching only within allowed directories.

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 three sentences, front-loaded with the main purpose, followed by pattern examples and usage context. Every sentence adds value without extraneous information.

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 the existence of an output schema, the description adequately covers purpose, pattern syntax, and scope. It omits details on excludePatterns and potential performance considerations, but overall is sufficient for a search tool.

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?

With 0% schema description coverage, the description compensates by explaining the 'pattern' parameter with examples and the 'path' parameter in context of relative paths. However, 'excludePatterns' is not mentioned, leaving a 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 recursively searches for files and directories matching a glob pattern, specifying the verb and resource. It distinguishes from siblings like list_directory and directory_tree by emphasizing pattern matching and recursive search.

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 explicitly notes that the tool is great for finding files when exact location is unknown and restricts searches to allowed directories. However, it does not explicitly compare with sibling tools or provide when-not-to-use guidance.

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