Skip to main content
Glama
PWalaGov

Enhanced Directory Context MCP Server

by PWalaGov

search_files

Search for content within files using text or regex patterns to locate specific information across your project directory.

Instructions

Search for content within files using regex or text matching

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query (text or regex pattern)
file_typesNoFile extensions to search in
is_regexNoWhether the query is a regex pattern
max_resultsNoMaximum number of results to return

Implementation Reference

  • The main handler function for the 'search_files' tool. It parses the input arguments, delegates the search to the searchFiles helper method, and returns the results formatted as a JSON string in the MCP response format.
    async handleSearchFiles(args) {
      const { query, file_types, is_regex = false, max_results = 50 } = args;
      const results = await this.searchFiles(query, file_types, is_regex, max_results);
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(results, null, 2),
          },
        ],
      };
    }
  • Supporting utility that performs the actual recursive file search in the working directory. Supports regex and text search, filters by file types, limits results, and collects line-level matches with context.
    async searchFiles(query, fileTypes, isRegex, maxResults) {
      const results = [];
      const searchPattern = isRegex ? new RegExp(query, 'gim') : query.toLowerCase();
      
      async function searchInDirectory(dirPath) {
        try {
          const entries = await fs.readdir(dirPath, { withFileTypes: true });
          
          for (const entry of entries) {
            if (results.length >= maxResults) break;
            
            const fullPath = path.join(dirPath, entry.name);
            
            if (entry.isDirectory() && !entry.name.startsWith('.')) {
              await searchInDirectory(fullPath);
            } else if (entry.isFile()) {
              const ext = path.extname(entry.name);
              if (!fileTypes || fileTypes.includes(ext)) {
                try {
                  const content = await fs.readFile(fullPath, 'utf8');
                  const matches = [];
                  
                  if (isRegex) {
                    let match;
                    while ((match = searchPattern.exec(content)) !== null && matches.length < 10) {
                      const lineNumber = content.substring(0, match.index).split('\n').length;
                      const line = content.split('\n')[lineNumber - 1];
                      matches.push({
                        line: lineNumber,
                        content: line.trim(),
                        match: match[0],
                      });
                    }
                  } else {
                    const lines = content.split('\n');
                    lines.forEach((line, index) => {
                      if (line.toLowerCase().includes(searchPattern) && matches.length < 10) {
                        matches.push({
                          line: index + 1,
                          content: line.trim(),
                          match: query,
                        });
                      }
                    });
                  }
                  
                  if (matches.length > 0) {
                    results.push({
                      file: path.relative(this.workingDirectory, fullPath),
                      matches,
                    });
                  }
                } catch (error) {
                  // Skip files that can't be read as text
                }
              }
            }
          }
        } catch (error) {
          // Skip directories that can't be read
        }
      }
      
      await searchInDirectory(this.workingDirectory);
      return results;
    }
  • Input schema definition for the search_files tool, specifying parameters like query, file_types, is_regex, and max_results with types, descriptions, and defaults.
      name: 'search_files',
      description: 'Search for content within files using regex or text matching',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'Search query (text or regex pattern)',
          },
          file_types: {
            type: 'array',
            description: 'File extensions to search in',
            items: { type: 'string' },
          },
          is_regex: {
            type: 'boolean',
            description: 'Whether the query is a regex pattern',
            default: false,
          },
          max_results: {
            type: 'number',
            description: 'Maximum number of results to return',
            default: 50,
          },
        },
        required: ['query'],
      },
    },
  • server.js:463-464 (registration)
    Dispatch case in the central tool switch statement that routes 'search_files' calls to the handleSearchFiles method.
    case 'search_files':
      return await this.handleSearchFiles(args);
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the search method (regex or text matching) but lacks details on permissions required, rate limits, whether it's read-only or has side effects, or what the output looks like (e.g., list of matches with file paths). For a search tool with zero annotation coverage, this is a significant gap in transparency.

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 a single, efficient sentence that front-loads the core purpose without unnecessary words. It directly states what the tool does ('Search for content within files') and the method ('using regex or text matching'), making it easy to parse and understand quickly.

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

Completeness2/5

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

Given the tool's complexity (searching files with multiple parameters) and lack of annotations and output schema, the description is incomplete. It doesn't cover behavioral aspects like safety, permissions, or output format, and while the schema handles parameters well, the overall context for effective agent use is insufficient. A more comprehensive description would enhance usability.

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?

The input schema has 100% description coverage, clearly documenting all parameters (query, file_types, is_regex, max_results). The description adds minimal value beyond the schema by implying regex/text matching, but it doesn't provide additional context like search scope (e.g., current directory vs. recursive) or parameter interactions. With high schema coverage, 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.

Purpose4/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 as 'Search for content within files using regex or text matching,' which specifies the verb (search), resource (content within files), and method (regex or text matching). However, it doesn't explicitly distinguish this tool from sibling tools like 'get_file_contents' or 'analyze_project_context,' which might also involve file content access, so it lacks sibling differentiation.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention scenarios like searching for specific text across multiple files, filtering by file types, or how it differs from tools like 'get_file_contents' (which retrieves content) or 'analyze_project_context' (which might involve broader analysis). Without such context, the agent has minimal usage direction.

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/PWalaGov/File-Control-MCP'

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