Skip to main content
Glama

search_filesystem

Search for files and directories in the workspace filesystem using a case-insensitive pattern. Recursively scans subdirectories, returns matching paths, and supports excluding specific paths with glob patterns.

Instructions

Recursively search for files and directories within the workspace filesystem matching a pattern in their name. Searches through all subdirectories from the starting path. The search is case-insensitive and matches partial names. Returns full paths (relative to workspace) to all matching items. Supports excluding paths using glob patterns.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
excludePatternsNoAn array of glob patterns (e.g., 'node_modules', '*.log') to exclude from the search.
pathYesThe starting directory path for the search (relative to the workspace directory).
patternYesThe case-insensitive text pattern to search for in file/directory names.

Implementation Reference

  • Executes the search_filesystem tool: parses args with schema, validates path, initiates recursive search, formats and returns matching file paths.
    case "search_filesystem": {
      const parsed = SearchFilesArgsSchema.parse(args);
      const validPath = validateWorkspacePath(parsed.path);
      const results: string[] = [];
      await searchFilesRecursive(validPath, validPath, parsed.pattern, parsed.excludePatterns, results);
      resultText = results.length > 0 ? results.join("\n") : "No matches found";
      break;
    }
  • Recursive helper function that traverses directories, checks name pattern match (case-insensitive), applies exclude globs, collects relative paths of matches.
    async function searchFilesRecursive(
      rootPath: string,
      currentPath: string,
      pattern: string,
      excludePatterns: string[],
      results: string[]
    ): Promise<void> {
      const entries = await fs.readdir(currentPath, { withFileTypes: true });
    
      for (const entry of entries) {
        const fullPath = path.join(currentPath, entry.name);
        const relativePath = path.relative(rootPath, fullPath);
    
        const shouldExclude = excludePatterns.some(p => minimatch(relativePath, p, { dot: true, matchBase: true }));
        if (shouldExclude) {
          continue;
        }
    
        if (entry.name.toLowerCase().includes(pattern.toLowerCase())) {
          results.push(path.relative(process.cwd(), fullPath));
        }
    
        if (entry.isDirectory()) {
          try {
              const realPath = await fs.realpath(fullPath);
              if (realPath.startsWith(rootPath)) {
                 await searchFilesRecursive(rootPath, fullPath, pattern, excludePatterns, results);
              }
          } catch (e) {
              console.error(`Skipping search in ${fullPath}: ${(e as Error).message}`);
          }
        }
      }
    }
  • Zod schema for input validation: path (start dir), pattern (search string), excludePatterns (optional glob excludes).
    export const SearchFilesArgsSchema = z.object({
      path: z.string().describe("The starting directory path for the search (relative to the workspace directory)."),
      pattern: z.string().describe("The case-insensitive text pattern to search for in file/directory names."),
      excludePatterns: z.array(z.string()).optional().default([]).describe("An array of glob patterns (e.g., 'node_modules', '*.log') to exclude from the search.")
    });
  • ToolDefinition export including name 'search_filesystem', description, inputSchema reference, and buildPrompt for arg validation. Imported into tools/index.ts for allTools registration.
    export const searchFilesTool: ToolDefinition = {
        name: "search_filesystem", // Renamed slightly
        description:
          "Recursively search for files and directories within the workspace filesystem matching a pattern in their name. " +
          "Searches through all subdirectories from the starting path. The search " +
          "is case-insensitive and matches partial names. Returns full paths (relative to workspace) to all " +
          "matching items. Supports excluding paths using glob patterns.",
        inputSchema: SearchFilesJsonSchema as any, // Cast as any if needed
    
        // Minimal buildPrompt as execution logic is separate
        buildPrompt: (args: any, modelId: string) => {
            const parsed = SearchFilesArgsSchema.safeParse(args);
            if (!parsed.success) {
                throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for search_filesystem: ${parsed.error}`);
            }
            return {
                systemInstructionText: "",
                userQueryText: "",
                useWebSearch: false,
                enableFunctionCalling: false
            };
        },
        // No 'execute' function here
    };
  • Includes searchFilesTool in the allTools array, which is exported and used by the MCP server for tool listing and mapping.
    searchFilesTool,
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 of behavioral disclosure. It effectively describes key traits: the recursive nature, case-insensitive and partial matching, return format ('full paths relative to workspace'), and support for exclusion patterns. However, it lacks details on performance (e.g., speed, depth limits), error handling, or workspace-specific constraints, which would be valuable for an agent.

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 the core purpose in the first sentence, followed by supporting details in a logical flow (search behavior, matching rules, return values, exclusions). Each sentence adds unique value without redundancy, and the length is appropriate for the tool's complexity, making it efficient and easy to parse.

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 tool's moderate complexity (3 parameters, recursive operation), no annotations, and no output schema, the description is largely complete. It covers purpose, behavior, and parameters well, but lacks output details (e.g., format examples, pagination) and error scenarios, which would help an agent handle results and failures more effectively.

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?

Schema description coverage is 100%, with clear documentation for all parameters in the input schema. The description adds minimal value beyond the schema, mentioning 'exclude paths using glob patterns' (implied by 'excludePatterns') and reinforcing case-insensitivity (already in schema for 'pattern'). No additional syntax or format details are provided, so the baseline score of 3 is appropriate.

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') and resources ('within the workspace filesystem'), distinguishing it from siblings like 'list_directory_contents' (non-recursive listing) and 'get_directory_tree' (structured tree output). It specifies the matching criteria ('pattern in their name') and scope ('all subdirectories from the starting path').

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

Usage Guidelines3/5

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

The description implies usage through its functional details (e.g., 'recursively search' vs. non-recursive siblings) but does not explicitly state when to use this tool versus alternatives like 'list_directory_contents' (for simple listing) or 'get_directory_tree' (for hierarchical views). No explicit exclusions or prerequisites are mentioned, leaving usage context inferred rather than guided.

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/shariqriazz/vertex-ai-mcp-server'

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