Skip to main content
Glama
A-Niranjan

MCP Filesystem Server

by A-Niranjan

search_files

Find files and directories by name pattern across subdirectories. Search recursively from a starting path with case-insensitive matching for partial names.

Instructions

Recursively search for files and directories matching a pattern. Searches through all subdirectories from the starting path. The search is case-insensitive and matches partial names. 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
pathYesRoot path to start searching from
patternYesPattern to match against filenames and directories
excludePatternsNoPatterns to exclude from search results

Implementation Reference

  • The main handler for the 'search_files' tool. Validates input using SearchFilesArgsSchema, performs recursive search starting from the given path, matches filenames case-insensitively against the pattern, supports excludePatterns using minimatch globs, collects full paths of matches, and returns formatted results or 'No matches found'.
    case 'search_files': {
      const parsed = SearchFilesArgsSchema.safeParse(a)
      if (!parsed.success) {
        throw new FileSystemError(`Invalid arguments for ${name}`, 'INVALID_ARGS', undefined, {
          errors: parsed.error.format(),
        })
      }
    
      const validPath = await validatePath(parsed.data.path, config)
      const patternLower = parsed.data.pattern.toLowerCase()
      const results: string[] = []
    
      async function search(currentPath: string) {
        try {
          const entries = await fs.readdir(currentPath, { withFileTypes: true })
    
          for (const entry of entries) {
            const fullPath = path.join(currentPath, entry.name)
    
            try {
              await validatePath(fullPath, config)
              const relativePath = path.relative(validPath, fullPath)
    
              // Check if the path should be excluded
              const shouldExclude =
                parsed.data &&
                parsed.data.excludePatterns.some((excludePattern) => {
                  const globPattern = excludePattern.includes('*')
                    ? excludePattern
                    : `**/${excludePattern}**`
                  return minimatch(relativePath, globPattern, { nocase: true })
                })
    
              if (shouldExclude) {
                continue
              }
    
              // Check if the name matches the search pattern
              if (entry.name.toLowerCase().includes(patternLower)) {
                results.push(fullPath)
              }
    
              // Recursively search subdirectories
              if (entry.isDirectory()) {
                await search(fullPath)
              }
            } catch (error) {
              // Skip paths we can't access or validate
              continue
            }
          }
        } catch (error) {
          // Skip directories we can't read
          return
        }
      }
    
      await search(validPath)
      await logger.debug(`Search complete: ${parsed.data.pattern}`, {
        resultCount: results.length,
      })
    
      endMetric()
      return {
        content: [
          {
            type: 'text',
            text:
              results.length > 0
                ? `Found ${results.length} matches:\n${results.join('\n')}`
                : 'No matches found',
          },
        ],
      }
    }
  • Zod schema defining the input parameters for the search_files tool: required path (root to search from), pattern (string to match in names), and optional excludePatterns array.
    const SearchFilesArgsSchema = z.object({
      path: z.string().describe('Root path to start searching from'),
      pattern: z.string().describe('Pattern to match against filenames and directories'),
      excludePatterns: z
        .array(z.string())
        .optional()
        .default([])
        .describe('Patterns to exclude from search results'),
    })
  • src/index.ts:306-315 (registration)
    Registers the search_files tool in the ListTools response, providing name, detailed description, and inputSchema converted from SearchFilesArgsSchema.
    {
      name: 'search_files',
      description:
        'Recursively search for files and directories matching a pattern. ' +
        'Searches through all subdirectories from the starting path. The search ' +
        'is case-insensitive and matches partial names. 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: zodToJsonSchema(SearchFilesArgsSchema) as ToolInput,
    },
Behavior3/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 behaviors: recursive search, case-insensitive matching, partial name matching, and restriction to allowed directories. However, it doesn't mention performance implications (e.g., could be slow on large directories), error handling, or output format details beyond 'full paths.' For a search tool with no annotation coverage, this is adequate but leaves some behavioral aspects unspecified.

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 efficiently structured with five sentences, each adding distinct value: core functionality, search behavior, matching rules, return values, use case, and constraints. There's no redundancy or fluff. The information is front-loaded with the primary purpose in the first sentence. Every sentence earns its place by contributing unique context not found in the schema or annotations.

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, no output schema, no annotations), the description provides good contextual coverage. It explains the search scope, matching behavior, use case, and access restrictions. However, without an output schema, it doesn't detail the return format (e.g., array structure, error responses) or potential limitations like recursion depth. For a search tool, this is mostly complete but could benefit from more output information.

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%, so the schema already documents all three parameters thoroughly. The description adds minimal value beyond the schema: it implies 'pattern' applies to both files and directories and mentions recursion starting from 'path.' However, it doesn't provide additional syntax examples, regex capabilities, or practical usage tips. The baseline score of 3 is appropriate when the schema does most of the parameter documentation work.

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 ('files and directories matching a pattern'). It distinguishes from siblings like 'list_directory' (which lists contents without searching) and 'get_file_info' (which retrieves metadata for a specific file). The description explicitly mentions it's 'great for finding files when you don't know their exact location,' which further clarifies its unique role.

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 about when to use this tool ('when you don't know their exact location') and mentions constraints ('Only searches within allowed directories'). However, it doesn't explicitly contrast with alternatives like 'list_directory' for browsing known locations or 'bash_execute' for command-line searches. The guidance is helpful but lacks explicit 'when-not-to-use' comparisons with sibling tools.

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/A-Niranjan/mcp-filesystem'

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