Skip to main content
Glama
247arjun

Grep MCP Server

by 247arjun

grep_search_intent

Search files using plain English descriptions like 'email addresses' or 'TODO comments' to find patterns without writing complex regex.

Instructions

Search for patterns using plain English descriptions (e.g., 'email addresses', 'phone numbers', 'TODO comments')

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
intentYesPlain English description of what to search for
targetYesFile or directory path to search in
case_sensitiveNoWhether the search should be case sensitive
max_resultsNoMaximum number of results to return
show_contextNoShow surrounding lines for context
context_linesNoNumber of context lines to show before/after matches

Implementation Reference

  • The main execution logic for the 'grep_search_intent' tool. Validates the input path, converts the plain English intent to a regex pattern using interpretSearchIntent, constructs the appropriate grep command arguments (including flags for regex, case-insensitivity, recursion, line numbers, context, etc.), executes the command via executeGrep, and returns the formatted results or error.
    async ({ intent, target, case_sensitive, max_results, show_context, context_lines }) => {
      // Validate target path
      const pathValidation = validatePath(target);
      if (!pathValidation.isValid) {
        return {
          content: [
            {
              type: "text",
              text: `Error: ${pathValidation.error}`,
            },
          ],
        };
      }
    
      const args = ['grep'];
      
      // Convert intent to regex pattern
      const pattern = interpretSearchIntent(intent);
      args.push('-E'); // Use extended regex
      args.push(pattern);
      
      // Add case sensitivity option
      if (!case_sensitive) {
        args.push('-i');
      }
      
      // Add recursive search if target is directory
      if (pathValidation.isDirectory) {
        args.push('-r');
      }
      
      // Add line numbers
      args.push('-n');
      
      // Add context if requested
      if (show_context && context_lines > 0) {
        args.push(`-C${context_lines}`);
      }
      
      // Add max results limit
      if (max_results) {
        args.push('-m', max_results.toString());
      }
      
      // Add target path
      args.push(target);
      
      try {
        const result = await executeGrep(args);
        
        return {
          content: [
            {
              type: "text",
              text: `Search Intent: "${intent}"\nPattern Used: ${pattern}\nExit Code: ${result.exitCode}\n\nResults:\n${result.stdout}${result.stderr ? `\n\nErrors:\n${result.stderr}` : ''}`,
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error executing grep: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
        };
      }
    }
  • Zod-based input schema defining parameters for the tool: intent (string), target (path), case_sensitive (bool), max_results (number), show_context (bool), context_lines (number).
    {
      intent: z.string().describe("Plain English description of what to search for"),
      target: z.string().describe("File or directory path to search in"),
      case_sensitive: z.boolean().optional().default(false).describe("Whether the search should be case sensitive"),
      max_results: z.number().optional().describe("Maximum number of results to return"),
      show_context: z.boolean().optional().default(false).describe("Show surrounding lines for context"),
      context_lines: z.number().optional().default(2).describe("Number of context lines to show before/after matches"),
    },
  • src/index.ts:155-234 (registration)
    Registration of the 'grep_search_intent' tool on the MCP server, including name, description, input schema, and inline handler function.
      "grep_search_intent",
      "Search for patterns using plain English descriptions (e.g., 'email addresses', 'phone numbers', 'TODO comments')",
      {
        intent: z.string().describe("Plain English description of what to search for"),
        target: z.string().describe("File or directory path to search in"),
        case_sensitive: z.boolean().optional().default(false).describe("Whether the search should be case sensitive"),
        max_results: z.number().optional().describe("Maximum number of results to return"),
        show_context: z.boolean().optional().default(false).describe("Show surrounding lines for context"),
        context_lines: z.number().optional().default(2).describe("Number of context lines to show before/after matches"),
      },
      async ({ intent, target, case_sensitive, max_results, show_context, context_lines }) => {
        // Validate target path
        const pathValidation = validatePath(target);
        if (!pathValidation.isValid) {
          return {
            content: [
              {
                type: "text",
                text: `Error: ${pathValidation.error}`,
              },
            ],
          };
        }
    
        const args = ['grep'];
        
        // Convert intent to regex pattern
        const pattern = interpretSearchIntent(intent);
        args.push('-E'); // Use extended regex
        args.push(pattern);
        
        // Add case sensitivity option
        if (!case_sensitive) {
          args.push('-i');
        }
        
        // Add recursive search if target is directory
        if (pathValidation.isDirectory) {
          args.push('-r');
        }
        
        // Add line numbers
        args.push('-n');
        
        // Add context if requested
        if (show_context && context_lines > 0) {
          args.push(`-C${context_lines}`);
        }
        
        // Add max results limit
        if (max_results) {
          args.push('-m', max_results.toString());
        }
        
        // Add target path
        args.push(target);
        
        try {
          const result = await executeGrep(args);
          
          return {
            content: [
              {
                type: "text",
                text: `Search Intent: "${intent}"\nPattern Used: ${pattern}\nExit Code: ${result.exitCode}\n\nResults:\n${result.stdout}${result.stderr ? `\n\nErrors:\n${result.stderr}` : ''}`,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error executing grep: ${error instanceof Error ? error.message : String(error)}`,
              },
            ],
          };
        }
      }
    );
  • Core helper function specific to this tool that interprets natural language search intents (e.g., 'email addresses', 'phone numbers', 'TODOs') into corresponding regex patterns for grep.
    function interpretSearchIntent(intent: string): string {
      const lowerIntent = intent.toLowerCase().trim();
      
      // Common search patterns
      const patterns: Record<string, string> = {
        // Email patterns
        'email': '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}',
        'email address': '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}',
        'emails': '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}',
        
        // URL patterns  
        'url': 'https?://[^\\s]+',
        'urls': 'https?://[^\\s]+',
        'website': 'https?://[^\\s]+',
        'link': 'https?://[^\\s]+',
        'links': 'https?://[^\\s]+',
        
        // IP addresses
        'ip address': '\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b',
        'ip addresses': '\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b',
        'ip': '\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b',
        
        // Phone numbers
        'phone number': '\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b',
        'phone numbers': '\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b',
        'phone': '\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b',
        
        // Dates
        'date': '\\b\\d{1,2}[/-]\\d{1,2}[/-]\\d{2,4}\\b',
        'dates': '\\b\\d{1,2}[/-]\\d{1,2}[/-]\\d{2,4}\\b',
        
        // Numbers
        'number': '\\b\\d+\\b',
        'numbers': '\\b\\d+\\b',
        'integer': '\\b\\d+\\b',
        'integers': '\\b\\d+\\b',
        
        // Common code patterns
        'function': '\\bfunction\\s+\\w+\\s*\\(',
        'functions': '\\bfunction\\s+\\w+\\s*\\(',
        'class': '\\bclass\\s+\\w+',
        'classes': '\\bclass\\s+\\w+',
        'import': '^\\s*import\\b',
        'imports': '^\\s*import\\b',
        'export': '^\\s*export\\b',
        'exports': '^\\s*export\\b',
        
        // Common file types
        'todo': '\\b(TODO|FIXME|HACK|XXX)\\b',
        'todos': '\\b(TODO|FIXME|HACK|XXX)\\b',
        'comment': '^\\s*(/\\*|//|#)',
        'comments': '^\\s*(/\\*|//|#)',
        
        // Error patterns
        'error': '\\b(error|Error|ERROR)\\b',
        'errors': '\\b(error|Error|ERROR)\\b',
        'warning': '\\b(warning|Warning|WARNING)\\b',
        'warnings': '\\b(warning|Warning|WARNING)\\b',
      };
      
      // Check for exact matches first
      if (patterns[lowerIntent]) {
        return patterns[lowerIntent];
      }
      
      // Check for partial matches
      for (const [key, pattern] of Object.entries(patterns)) {
        if (lowerIntent.includes(key)) {
          return pattern;
        }
      }
      
      // If no pattern matches, treat as literal string search (escaped for regex)
      return intent.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
  • Shared utility function to safely execute grep commands via child_process.spawn, capturing stdout, stderr, and exit code.
    async function executeGrep(args: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
      return new Promise((resolve) => {
        // Ensure we're only calling grep with safe arguments
        if (!args.includes('grep')) {
          args.unshift('grep');
        }
        
        const child = spawn('grep', args.slice(1), {
          stdio: ['pipe', 'pipe', 'pipe'],
          shell: false,
        });
    
        let stdout = '';
        let stderr = '';
    
        child.stdout.on('data', (data) => {
          stdout += data.toString();
        });
    
        child.stderr.on('data', (data) => {
          stderr += data.toString();
        });
    
        child.on('close', (code) => {
          resolve({
            stdout,
            stderr,
            exitCode: code || 0,
          });
        });
    
        child.on('error', (error) => {
          resolve({
            stdout: '',
            stderr: error.message,
            exitCode: 1,
          });
        });
      });
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While it mentions the search functionality, it doesn't describe what happens when matches are found (e.g., returns matches with line numbers), performance characteristics, error conditions, or whether the search is recursive through directories. For a tool with 6 parameters and no annotation coverage, this leaves significant behavioral gaps.

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 immediately communicates the core functionality with relevant examples. Every element earns its place - the main action, the input method, and concrete examples all contribute to understanding without any wasted words or unnecessary elaboration.

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 6 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (matches, counts, files?), how results are formatted, error handling, or performance considerations. The high parameter count and lack of structured metadata mean the description should provide more behavioral context to be truly helpful.

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 parameters thoroughly. The description adds value by explaining the 'intent' parameter's purpose ('plain English descriptions') with helpful examples, but doesn't provide additional semantic context beyond what's in the schema for other parameters. This meets the baseline 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 specific action ('Search for patterns') and resource ('using plain English descriptions'), with concrete examples ('email addresses', 'phone numbers', 'TODO comments') that help distinguish it from regex-based sibling tools like grep_regex. It precisely communicates the tool's unique capability of intent-based pattern matching.

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

Usage Guidelines3/5

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

The description implies usage context through the examples of plain English descriptions, suggesting this tool is for high-level pattern matching rather than precise regex patterns. However, it doesn't explicitly state when to use this vs. alternatives like grep_advanced or grep_regex, nor does it mention any exclusions or prerequisites for usage.

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/247arjun/mcp-grep'

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