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,
          });
        });
      });
    }

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