Skip to main content
Glama

grep

Search file contents using regular expressions to find specific patterns, with options to filter by file type and show surrounding context lines.

Instructions

Search file contents using regular expressions with ripgrep-style output

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYesThe regular expression pattern to search for in file contents
pathNoThe directory to search in. Defaults to the current working directory.
includeNoFile pattern to include in the search (e.g. "*.js", "*.{ts,tsx}", "!**/node_modules/**")
beforeContextNoShow NUM lines before each match
afterContextNoShow NUM lines after each match
contextNoShow NUM lines before and after each match
multilineNoEnable multiline pattern matching
maxCountNoMaximum number of matches per file (default: 5)

Implementation Reference

  • The primary handler function for the 'grep' tool. It validates inputs using Zod, handles single file or directory searches, performs regex matching with configurable context lines, limits matches and output size, and formats results in a ripgrep-like style with summaries.
    async execute(args: any): Promise<any> {
      try {
        // Validate and parse input using Zod schema
        const validatedArgs = GrepToolInputSchema.parse(args);
        const { pattern, path, include, beforeContext, afterContext, context, multiline, maxCount } =
          validatedArgs;
    
        // Reset output length for each execution
        this.outputLength = 0;
    
        // Calculate actual before/after context
        const actualBefore = context !== undefined ? context : beforeContext;
        const actualAfter = context !== undefined ? context : afterContext;
    
        // Path validation is handled by DirectoryUtils
    
        // Create regex pattern with enhanced error handling
        const regexFlags = multiline ? "gm" : "g";
        let regex: RegExp;
    
        try {
          regex = new RegExp(pattern, regexFlags);
        } catch (error: any) {
          throw new Error(this.createFriendlyRegexError(pattern, error.message));
        }
    
        let result = "";
        let totalMatches = 0;
        let filesWithMatches = 0;
        let filesSearched = 0;
    
        // Check if path is a single file or directory
        let filesToSearch: string[] = [];
        let results: any[] = [];
        const MAX_FILES = 20;
    
        try {
          const stats = await FileUtils.getFileStats(path);
          if (stats.isFile) {
            // Single file case
            filesToSearch = [path];
            filesSearched = 1;
          } else {
            throw new Error("Not a file");
          }
        } catch {
          // Not a file, treat as directory
          results = await DirectoryUtils.findFiles(path, include, {
            maxDepth: 3,
            includeIgnored: false,
            includeFiles: true,
            includeDirectories: false,
          });
    
          // Limit number of files to search for performance
          filesToSearch = results.slice(0, MAX_FILES).map((r) => r.path);
        }
    
        for (const file of filesToSearch) {
          if (filesSearched === 1 && filesToSearch.length === 1) {
            // Single file case, already counted
          } else {
            filesSearched++;
          }
    
          try {
            // Use FileUtils for safe file reading with built-in security checks
            const content = await FileUtils.safeReadFile(file, {
              maxSize: TOOL_CONSTANTS.OUTPUT_LIMIT,
              checkIsBinary: true,
            });
    
            // Search for matches
            const matches = this.searchContent(content, regex, actualBefore, actualAfter, maxCount);
    
            if (matches.length > 0) {
              filesWithMatches++;
              const relativePath = relative(process.cwd(), file);
    
              // Add file header
              const header = `${relativePath}\n`;
              result += header;
              this.addToOutput(header);
    
              // Add matches with context
              let displayedMatches = 0;
              let totalFileMatches = 0;
    
              for (const match of matches) {
                if (displayedMatches >= maxCount) {
                  totalFileMatches = this.countTotalMatches(content, regex);
                  break;
                }
    
                const line = `${match.lineNumber}${match.isMatch ? ":" : "-"}${match.content}\n`;
                result += line;
                this.addToOutput(line);
    
                if (match.isMatch) {
                  displayedMatches++;
                  totalMatches++;
                }
              }
    
              // Show continuation message if there are more matches
              if (totalFileMatches > maxCount) {
                const remaining = totalFileMatches - maxCount;
                const continuation = `\n... and ${remaining} more matches (showing first ${maxCount})\nUse maxCount=${Math.min(totalFileMatches, maxCount * 2)} to see more matches\n`;
                result += continuation;
                this.addToOutput(continuation);
              }
    
              const separator = "\n";
              result += separator;
              this.addToOutput(separator);
            }
          } catch (_error) {}
        }
    
        // Add summary
        let summary = "";
        if (totalMatches === 0) {
          summary = "No matches found";
        } else {
          summary = `${totalMatches} match${totalMatches === 1 ? "" : "es"} found in ${filesWithMatches} file${filesWithMatches === 1 ? "" : "s"}`;
          if (results.length > MAX_FILES) {
            summary += ` (limited to first ${MAX_FILES} files)`;
          }
        }
        summary += "\n";
        result += summary;
        this.addToOutput(summary);
    
        return ResultFormatter.createResponse(result);
      } catch (error: any) {
        // Handle Zod validation errors
        if (error instanceof Error && error.name === "ZodError") {
          throw ToolError.createValidationError("input", args, `Invalid input: ${error.message}`);
        }
        // If it's already our friendly regex error, don't wrap it
        if (error.message.includes("Regex pattern error:")) {
          throw error;
        }
        throw ToolError.wrapError("Grep search", error);
      }
    }
  • Zod input schema for the grep tool used for runtime validation of tool arguments including pattern, path, glob include, context lines, multiline flag, and max matches.
    export const GrepToolInputSchema = z.object({
      pattern: z.string().min(1, "Pattern cannot be empty"),
      path: FilePathSchema.default("."),
      include: z.string().optional(),
      beforeContext: z.number().int().min(0).default(0),
      afterContext: z.number().int().min(0).default(0),
      context: z.number().int().min(0).optional(),
      multiline: BooleanFlagSchema,
      maxCount: z.number().int().min(1).default(5),
    });
  • Tool registration: adds the grep tool's definition to the list of available MCP tools returned by listTools.
    protected getTools(): Tool[] {
      return [
        this.readTool.getDefinition(),
        this.findTool.getDefinition(),
        this.grepTool.getDefinition(),
        this.writeTool.getDefinition(),
        this.editTool.getDefinition(),
        this.moveTool.getDefinition(),
        this.copyTool.getDefinition(),
      ];
    }
  • Tool dispatch registration: handles 'grep' tool calls by invoking the GrepTool instance's execute method.
    case "grep":
      return await this.grepTool.execute(args);
  • Helper function that performs the actual content search: finds matching lines, adds before/after context without duplication, and returns structured matches for output formatting.
    private searchContent(
      content: string,
      regex: RegExp,
      beforeContext: number,
      afterContext: number,
      maxCount: number
    ): GrepMatch[] {
      const lines = content.split("\n");
      const matches: GrepMatch[] = [];
      const matchedLines = new Set<number>();
      let matchCount = 0;
    
      // Find all matches
      for (let i = 0; i < lines.length && matchCount < maxCount; i++) {
        const line = lines[i];
        if (line !== undefined && regex.test(line)) {
          matchedLines.add(i);
          matchCount++;
        }
      }
    
      // Build result with context
      const processedLines = new Set<number>();
    
      for (const matchLine of Array.from(matchedLines).sort((a, b) => a - b)) {
        // Add before context
        for (let i = Math.max(0, matchLine - beforeContext); i < matchLine; i++) {
          if (!processedLines.has(i)) {
            const line = lines[i];
            if (line !== undefined) {
              matches.push({
                lineNumber: i + 1,
                content: line,
                isMatch: false,
              });
              processedLines.add(i);
            }
          }
        }
    
        // Add match line
        if (!processedLines.has(matchLine)) {
          const line = lines[matchLine];
          if (line !== undefined) {
            matches.push({
              lineNumber: matchLine + 1,
              content: line,
              isMatch: true,
            });
            processedLines.add(matchLine);
          }
        }
    
        // Add after context
        for (let i = matchLine + 1; i <= Math.min(lines.length - 1, matchLine + afterContext); i++) {
          if (!processedLines.has(i)) {
            const line = lines[i];
            if (line !== undefined) {
              matches.push({
                lineNumber: i + 1,
                content: line,
                isMatch: false,
              });
              processedLines.add(i);
            }
          }
        }
      }
    
      return matches;
    }
Behavior2/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 mentions 'ripgrep-style output' but doesn't explain what that entails (e.g., format, line numbers, file paths). It doesn't disclose important behavioral traits like whether it searches recursively by default, error handling, performance characteristics, or what happens with binary files.

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's perfectly front-loaded with the core purpose. Every word earns its place - 'Search file contents' establishes the action, 'using regular expressions' specifies the method, and 'with ripgrep-style output' provides implementation context.

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?

For a tool with 8 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain the output format ('ripgrep-style' is vague), doesn't mention recursion behavior, and provides no examples of typical use cases. The agent would struggle to understand what results to expect or how to interpret them.

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 8 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain parameter interactions (e.g., how 'context' relates to 'beforeContext'/'afterContext') or provide usage examples for complex parameters like 'include' patterns.

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 a specific verb ('Search') and resource ('file contents'), and distinguishes it from siblings by specifying the search method ('using regular expressions with ripgrep-style output'). It goes beyond the tool name 'grep' to explain what type of search it performs.

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 like 'find' (which likely searches file names) or 'read' (which might read file contents without searching). It mentions 'ripgrep-style output' but doesn't explain what that means or when this specific implementation is preferable.

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/d-issy/mcp'

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