Skip to main content
Glama
mcollina

MCP Ripgrep Server

by mcollina

count-matches

Count pattern matches in files using ripgrep to track occurrences across directories or specific files.

Instructions

Count matches in files using ripgrep

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYesThe search pattern (regex by default)
pathYesDirectory or file(s) to search.
caseSensitiveNoUse case sensitive search (default: auto)
filePatternNoFilter by file type or glob
countLinesNoCount matching lines instead of total matches
useColorsNoUse colors in output (default: false)

Implementation Reference

  • Main handler logic for the 'count-matches' tool. Parses input arguments, builds a ripgrep command with appropriate flags for counting matches ( -c for lines or --count-matches for total), executes it via the exec function, processes output, and returns the count.
    case "count-matches": {
      const pattern = String(args.pattern || "");
      const path = String(args.path);
      const caseSensitive = typeof args.caseSensitive === 'boolean' ? args.caseSensitive : undefined;
      const filePattern = args.filePattern ? String(args.filePattern) : undefined;
      const countLines = typeof args.countLines === 'boolean' ? args.countLines : true;
      const useColors = typeof args.useColors === 'boolean' ? args.useColors : false;
      
      if (!pattern) {
        return {
          isError: true,
          content: [{ type: "text", text: "Error: Pattern is required" }]
        };
      }
      
      // Build the rg command with flags
      let command = "rg";
      
      // Add case sensitivity flag if specified
      if (caseSensitive === true) {
        command += " -s"; // Case sensitive
      } else if (caseSensitive === false) {
        command += " -i"; // Case insensitive
      }
      
      // Add file pattern if specified
      if (filePattern) {
        command += ` -g ${escapeShellArg(filePattern)}`;
      }
      
      // Add count flag
      if (countLines) {
        command += " -c"; // Count lines
      } else {
        command += " --count-matches"; // Count total matches
      }
      
      // Add color setting
      command += useColors ? " --color always" : " --color never";
      
      // Add pattern and path
      command += ` ${escapeShellArg(pattern)} ${escapeShellArg(path)}`;
      
      console.error(`Executing: ${command}`);
      const { stdout, stderr } = await exec(command);
      
      // If there's anything in stderr, log it for debugging
      if (stderr) {
        console.error(`ripgrep stderr: ${stderr}`);
      }
      
      return {
        content: [
          {
            type: "text",
            text: processOutput(stdout, useColors) || "No matches found"
          }
        ]
      };
    }
  • src/index.ts:139-154 (registration)
    Tool registration in the ListTools response, defining name, description, and input schema for 'count-matches'.
    {
      name: "count-matches",
      description: "Count matches in files using ripgrep",
      inputSchema: {
        type: "object",
        properties: {
          pattern: { type: "string", description: "The search pattern (regex by default)" },
          path: { type: "string", description: "Directory or file(s) to search." },
          caseSensitive: { type: "boolean", description: "Use case sensitive search (default: auto)" },
          filePattern: { type: "string", description: "Filter by file type or glob" },
          countLines: { type: "boolean", description: "Count matching lines instead of total matches" },
          useColors: { type: "boolean", description: "Use colors in output (default: false)" }
        },
        required: ["pattern", "path"]
      }
    },
  • Input schema definition for the 'count-matches' tool, specifying parameters like pattern, path, caseSensitive, etc.
    inputSchema: {
      type: "object",
      properties: {
        pattern: { type: "string", description: "The search pattern (regex by default)" },
        path: { type: "string", description: "Directory or file(s) to search." },
        caseSensitive: { type: "boolean", description: "Use case sensitive search (default: auto)" },
        filePattern: { type: "string", description: "Filter by file type or glob" },
        countLines: { type: "boolean", description: "Count matching lines instead of total matches" },
        useColors: { type: "boolean", description: "Use colors in output (default: false)" }
      },
      required: ["pattern", "path"]
    }
  • Flag addition for counting total matches (non-line based) in ripgrep command.
    command += " --count-matches"; // Count total matches
  • src/index.ts:185-185 (registration)
    Whitelist check for handling 'count-matches' tool in CallToolRequestSchema handler.
    if (!["search", "advanced-search", "count-matches", "list-files", "list-file-types"].includes(toolName)) {

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.1/5.0
Behavior2/5

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

With no annotations, the description carries full burden but only states the basic function. It fails to disclose behavioral details such as regex handling, line count vs match count behavior, or output format.

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?

Single sentence, no wasted words. Could benefit from slight expansion to include core purpose, but it is efficient.

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 and no output schema, the description is too minimal. Missing return format, error cases, and how it differs from sibling tools.

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 coverage is 100%, so baseline is 3. The description adds no additional parameter-level context beyond what the schema already provides.

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 counts matches in files and names the underlying engine (ripgrep). It distinguishes from siblings like 'search' which likely returns matches rather than counts.

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?

No guidance on when to use this tool versus alternatives like 'search' or 'advanced-search'. No mention of prerequisites, performance considerations, or limitations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.