Skip to main content
Glama

search_files

Find notes by searching for files and directories matching a pattern in your notes directory. Returns full paths to matching items for easy access.

Instructions

Recursively search for files and directories matching a pattern in your notes directory. The search is case-insensitive and matches partial names. Returns full paths to all matching items. Great for finding notes when you don't know their exact location.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYesThe pattern to search for in file and directory names
excludePatternsNoGlob patterns to exclude from search results

Implementation Reference

  • Primary handler for the 'search_files' tool: validates arguments, calls searchFiles utility, formats and returns matching file paths relative to notes directory or error.
    export async function handleSearchFiles(notesPath: string, args: SearchFilesArgs): Promise<ToolCallResult> {
      try {
        // Validate pattern is provided
        if (!args.pattern) {
          throw new Error("'pattern' parameter is required");
        }
        
        // Always search in the notes directory
        const results = await searchFiles(
          notesPath, 
          args.pattern, 
          args.excludePatterns || []
        );
        
        if (results.length === 0) {
          return {
            content: [{ type: "text", text: "No files found matching the pattern." }]
          };
        }
        
        // Format results as relative paths
        const formattedResults = results.map((filePath: string) => 
          path.relative(notesPath, filePath)
        );
        
        return {
          content: [{ 
            type: "text", 
            text: `Found ${results.length} files matching "${args.pattern}":\n\n${formattedResults.join('\n')}` 
          }]
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        return {
          content: [{ type: "text", text: `Error searching files: ${errorMessage}` }],
          isError: true
        };
      }
    }
  • Tool definition including input schema (JSON Schema) for 'search_files' returned by getFilesystemToolDefinitions().
    {
      name: "search_files",
      description: "Recursively search for files and directories matching a pattern in your notes directory. " +
        "The search is case-insensitive and matches partial names. Returns full paths to all " +
        "matching items. Great for finding notes when you don't know their exact location.",
      inputSchema: {
        type: "object",
        properties: {
          pattern: { 
            type: "string",
            description: "The pattern to search for in file and directory names" 
          },
          excludePatterns: { 
            type: "array", 
            items: { type: "string" },
            description: "Glob patterns to exclude from search results",
            default: []
          }
        },
        required: ["pattern"]
      },
    },
  • Registration in main tool dispatcher (handleToolCall switch): routes 'search_files' calls to handleSearchFiles handler.
    case "search_files":
      return await handleSearchFiles(notesPath, args);
  • Core utility function implementing recursive case-insensitive file search with glob exclusion support, used by the handler.
    export async function searchFiles(rootPath: string, pattern: string, excludePatterns: string[] = []): Promise<string[]> {
      const results: string[] = [];
      
      // Normalize the search pattern for better matching
      const normalizedPattern = pattern.toLowerCase();
    
      // Make sure the root path exists
      try {
        const rootStats = await fs.stat(rootPath);
        if (!rootStats.isDirectory()) {
          console.error(`Search root is not a directory: ${rootPath}`);
          return [];
        }
      } catch (error) {
        console.error(`Error accessing search root path ${rootPath}:`, error);
        return [];
      }
    
      async function search(currentPath: string): Promise<void> {
        try {
          // Read directory entries
          const entries = await fs.readdir(currentPath, { withFileTypes: true });
    
          for (const entry of entries) {
            const fullPath = path.join(currentPath, entry.name);
            
            try {
              // 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;
              }
    
              // Match the name (case-insensitive)
              if (entry.name.toLowerCase().includes(normalizedPattern)) {
                results.push(fullPath);
              }
    
              // Recursively search subdirectories
              if (entry.isDirectory()) {
                await search(fullPath);
              }
            } catch (error) {
              // Skip problematic entries
              console.error(`Error processing ${fullPath}:`, error);
              continue;
            }
          }
        } catch (error) {
          console.error(`Error reading directory ${currentPath}:`, error);
        }
      }
    
      // Start the search
      await search(rootPath);
      
      // Log the number of results found
      console.error(`Search found ${results.length} results for pattern "${pattern}" in ${rootPath}`);
      
      return results;
    }
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 search is recursive, case-insensitive, matches partial names, and returns full paths. It does not mention potential limitations like performance impacts on large directories or file system permissions, but covers the core behavior well for a search tool.

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 appropriately sized and front-loaded, with the first sentence covering the core functionality and subsequent sentences adding useful details without redundancy. Every sentence earns its place by clarifying behavior and usage, making it efficient and well-structured.

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 (search with two parameters), no annotations, and no output schema, the description is largely complete. It explains what the tool does, how it behaves, and when to use it. However, it lacks details on output format beyond 'full paths' (e.g., structure or error handling), slightly reducing completeness.

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 both parameters (pattern and excludePatterns). The description adds some context by mentioning 'pattern' and 'partial names', but does not provide additional syntax or format details beyond what the schema provides. This meets the baseline of 3 for high schema coverage.

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 ('search for files and directories') and resources ('in your notes directory'), distinguishing it from siblings like list_directory (which lists without searching) or read_note (which reads specific files). It specifies the search is recursive and matches patterns, making the purpose unambiguous.

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 this tool ('Great for finding notes when you don't know their exact location'), which implicitly suggests alternatives like list_directory for browsing or read_note for known files. However, it does not explicitly state when not to use it or name specific alternatives, keeping it at a 4.

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/mikeysrecipes/mcp-notes'

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