Skip to main content
Glama

grep_search

Search file contents using regex patterns to find specific text within files or directories, with options for case sensitivity, file filtering, and context lines around matches.

Instructions

Search file contents with regex

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYesRegex pattern to search for
pathNoFile or directory to search
globNoFile pattern filter (e.g., *.ts)
case_sensitiveNoCase sensitive search
max_resultsNoMaximum results (default: 100)
context_linesNoLines of context around matches

Implementation Reference

  • The grepSearchImpl function performs the regex-based content search across files.
    async function grepSearchImpl(input: GrepSearchInput): Promise<ToolResult> {
      try {
        const searchPath = input.path ? path.resolve(input.path) : process.cwd();
        const matches: GrepMatch[] = [];
    
        // Create regex
        const flags = input.case_sensitive ? '' : 'i';
        let regex: RegExp;
        try {
          regex = new RegExp(input.pattern, flags);
        } catch {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'INVALID_PATH',
                  message: `Invalid regex pattern: ${input.pattern}`,
                }),
              },
            ],
          };
        }
    
        // Determine files to search
        let files: string[];
    
        const stats = await fs.stat(searchPath);
        if (stats.isFile()) {
          files = [searchPath];
        } else {
          // Use glob to find files in directory
          const globPattern = input.glob ?? '**/*';
          files = await glob(globPattern, {
            cwd: searchPath,
            nodir: true,
            absolute: true,
            maxDepth: 20,
          });
        }
    
        // Search each file
        for (const file of files) {
          if (matches.length >= input.max_results) break;
    
          try {
            const content = await fs.readFile(file, 'utf-8');
            const lines = content.split('\n');
    
            for (let i = 0; i < lines.length; i++) {
              if (matches.length >= input.max_results) break;
    
              const line = lines[i];
              const match = regex.exec(line);
    
              if (match) {
                const grepMatch: GrepMatch = {
                  file,
                  line: i + 1,
                  column: match.index + 1,
                  match: line.trim(),
                };
    
                // Add context if requested
                if (input.context_lines > 0) {
                  const beforeStart = Math.max(0, i - input.context_lines);
                  const afterEnd = Math.min(lines.length, i + input.context_lines + 1);
    
                  grepMatch.context = {
                    before: lines.slice(beforeStart, i).map((l) => l.trim()),
                    after: lines.slice(i + 1, afterEnd).map((l) => l.trim()),
                  };
                }
    
                matches.push(grepMatch);
              }
            }
          } catch {
            // Skip files that can't be read (binary, permissions, etc.)
          }
        }
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  pattern: input.pattern,
                  count: matches.length,
                  truncated: matches.length >= input.max_results,
                  matches,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error) {
        const err = error as NodeJS.ErrnoException;
    
        if (err.code === 'ENOENT') {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'FILE_NOT_FOUND',
                  message: `Path not found: ${input.path}`,
                }),
              },
            ],
          };
        }
    
        return {
          isError: true,
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                code: 'UNKNOWN_ERROR',
                message: `Error in grep search: ${err.message}`,
              }),
            },
          ],
        };
      }
    }
  • Registration of the grep_search tool in the MCP server.
    // grep_search tool
    server.tool(
      'grep_search',
      'Search file contents with regex',
      {
        pattern: z.string().describe('Regex pattern to search for'),
        path: z.string().optional().describe('File or directory to search'),
        glob: z.string().optional().describe('File pattern filter (e.g., *.ts)'),
        case_sensitive: z.boolean().optional().describe('Case sensitive search'),
        max_results: z.number().optional().describe('Maximum results (default: 100)'),
        context_lines: z.number().optional().describe('Lines of context around matches'),
      },
      async (args) => {
        const input = GrepSearchInputSchema.parse(args);
        return await grepSearchImpl(input);
      }
    );
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 searching with regex but lacks details on permissions, rate limits, error handling, or output format (e.g., whether it returns matches, lines, or files). For a tool with 6 parameters and no output schema, 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 extremely concise with a single sentence, 'Search file contents with regex,' which is front-loaded and wastes no words. It efficiently communicates the core function without unnecessary elaboration, making it easy to parse 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 complexity of a search tool with 6 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain the return values, error cases, or behavioral traits like how context_lines or max_results affect output. This leaves critical gaps for an agent to invoke the tool correctly without trial and error.

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 all parameters well-documented in the input schema (e.g., pattern, path, glob). The description adds no additional semantic context beyond 'regex,' which is already implied by the schema. This meets the baseline for high schema coverage but doesn't enhance understanding of parameter interactions or usage.

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 file contents with regex,' which specifies the verb (search) and resource (file contents) with the method (regex). However, it doesn't differentiate from sibling tools like 'find_by_content' or 'glob_search,' which may offer similar or overlapping functionality, leaving room for ambiguity in tool selection.

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. With siblings like 'find_by_content' and 'glob_search' available, there's no indication of specific contexts, prerequisites, or exclusions for using grep_search, making it challenging for an agent to choose appropriately without additional context.

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/mcp-tool-shop-org/mcp-file-forge'

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