Skip to main content
Glama
247arjun

Grep MCP Server

by 247arjun

grep_advanced

Execute grep with custom arguments for advanced text search operations, enabling precise pattern matching and file filtering using command-line parameters.

Instructions

Execute grep with custom arguments (advanced usage)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
argsYesArray of grep arguments (excluding 'grep' itself)

Implementation Reference

  • The async handler function for the 'grep_advanced' tool. Validates input args against dangerous flags and executes the grep command via executeGrep helper, returning results or errors.
    async ({ args }) => {
      // Basic validation to prevent potentially dangerous operations
      const dangerousFlags = [
        '--devices=', // Device operations could be dangerous
        '--binary-files=', // Binary file operations
        '-f', '--file', // Reading patterns from files
        '-D', '--devices', // Device handling
      ];
      
      const hasUnsafeFlag = args.some(arg => 
        dangerousFlags.some(dangerous => arg.startsWith(dangerous))
      );
      
      if (hasUnsafeFlag) {
        return {
          content: [
            {
              type: "text",
              text: `Error: This command contains potentially unsafe flags. Please use the specific grep tools for safety.`,
            },
          ],
        };
      }
      
      try {
        const result = await executeGrep(['grep', ...args]);
        
        return {
          content: [
            {
              type: "text",
              text: `Exit 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 input schema for the 'grep_advanced' tool, defining a single parameter 'args' as an array of strings.
    {
      args: z.array(z.string()).describe("Array of grep arguments (excluding 'grep' itself)"),
    },
  • src/index.ts:528-580 (registration)
    Registration of the 'grep_advanced' MCP tool using server.tool, including name, description, schema, and inline handler.
    server.tool(
      "grep_advanced",
      "Execute grep with custom arguments (advanced usage)",
      {
        args: z.array(z.string()).describe("Array of grep arguments (excluding 'grep' itself)"),
      },
      async ({ args }) => {
        // Basic validation to prevent potentially dangerous operations
        const dangerousFlags = [
          '--devices=', // Device operations could be dangerous
          '--binary-files=', // Binary file operations
          '-f', '--file', // Reading patterns from files
          '-D', '--devices', // Device handling
        ];
        
        const hasUnsafeFlag = args.some(arg => 
          dangerousFlags.some(dangerous => arg.startsWith(dangerous))
        );
        
        if (hasUnsafeFlag) {
          return {
            content: [
              {
                type: "text",
                text: `Error: This command contains potentially unsafe flags. Please use the specific grep tools for safety.`,
              },
            ],
          };
        }
        
        try {
          const result = await executeGrep(['grep', ...args]);
          
          return {
            content: [
              {
                type: "text",
                text: `Exit 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)}`,
              },
            ],
          };
        }
      }
    );
  • Shared helper function to safely spawn and execute grep processes, capturing stdout, stderr, and exit code. Used by 'grep_advanced' and other grep tools.
    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?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'execute grep' which implies a read operation, but doesn't disclose critical traits like whether it modifies files, requires specific permissions, has rate limits, or what the output format is (e.g., text lines, error handling). For a tool with no annotations, this leaves significant gaps in understanding its behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the key information ('Execute grep with custom arguments') and adds a qualifier ('advanced usage'). There's no wasted text, making it appropriately concise, though it could be slightly more structured by explicitly stating the tool's core function upfront.

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 grep tool (which can involve various arguments and behaviors), no annotations, and no output schema, the description is incomplete. It doesn't explain what grep does, what the output looks like, or how to interpret results, leaving the agent under-informed for proper tool invocation in this context.

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 schema description coverage is 100%, with the parameter 'args' fully documented in the schema as 'Array of grep arguments (excluding 'grep' itself)'. The description adds no additional meaning beyond this, such as examples of common arguments or constraints. With high schema coverage, the baseline score of 3 is appropriate as the description doesn't compensate but doesn't detract either.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Execute grep with custom arguments (advanced usage)' states the action (execute grep) and scope (custom arguments, advanced usage), but it's vague about what 'grep' specifically does (text search) and doesn't clearly distinguish from siblings like 'grep_regex' or 'grep_search_intent' that might also involve advanced grep usage. It avoids tautology but lacks specificity.

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 'grep_regex' or 'grep_count', nor does it mention prerequisites or exclusions. The term 'advanced usage' implies a context but doesn't specify what makes it advanced or when it's appropriate, leaving the agent with no clear usage rules.

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