Skip to main content
Glama
bsreeram08

Git Repo Browser MCP

git_search_code

Search for code patterns in Git repositories using regex or string matching, with options to filter by file type and include context lines.

Instructions

Search for patterns in repository code.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
repo_urlYesThe URL of the Git repository
patternYesSearch pattern (regex or string)
file_patternsNoOptional file patterns to filter (e.g., "*.js")
case_sensitiveNoWhether the search is case sensitive
context_linesNoNumber of context lines to include

Implementation Reference

  • The core handler function that clones the repository, executes `git grep` with options for case sensitivity, context lines, and file patterns, parses the output, and returns structured search results including matches with context.
    export async function handleGitSearchCode({
      repo_url,
      pattern,
      file_patterns = [],
      case_sensitive = false,
      context_lines = 2,
    }) {
      try {
        const repoPath = await cloneRepo(repo_url);
    
        // Build the grep command
        let grepCommand = `cd "${repoPath}" && git grep`;
    
        // Add options
        if (!case_sensitive) {
          grepCommand += " -i";
        }
    
        // Add context lines
        grepCommand += ` -n -C${context_lines}`;
    
        // Add pattern (escape quotes in the pattern)
        const escapedPattern = pattern.replace(/"/g, '\\"');
        grepCommand += ` "${escapedPattern}"`;
    
        // Add file patterns if provided
        if (file_patterns && file_patterns.length > 0) {
          grepCommand += ` -- ${file_patterns.join(" ")}`;
        }
    
        // Execute the command
        const { stdout, stderr } = await execPromise(grepCommand);
    
        if (stderr) {
          console.error(`Search error: ${stderr}`);
        }
    
        // Process the results
        const results = [];
        if (stdout) {
          // Split by file sections (git grep output format)
          const fileMatches = stdout.split(/^(?=\S[^:]*:)/m);
    
          for (const fileMatch of fileMatches) {
            if (!fileMatch.trim()) continue;
    
            // Extract file name and matches
            const lines = fileMatch.split("\n");
            const firstLine = lines[0];
            const fileNameMatch = firstLine.match(/^([^:]+):/);
    
            if (fileNameMatch) {
              const fileName = fileNameMatch[1];
              const matches = [];
    
              // Process each line
              let currentMatch = null;
              let contextLines = [];
    
              for (let i = 0; i < lines.length; i++) {
                const line = lines[i];
                // Skip empty lines
                if (!line.trim()) continue;
    
                // Check if this is a line number indicator
                const lineNumberMatch = line.match(/^([^-][^:]+):(\d+):(.*)/);
    
                if (lineNumberMatch) {
                  // If we have a previous match, add it to the results
                  if (currentMatch) {
                    currentMatch.context_after = contextLines;
                    matches.push(currentMatch);
                    contextLines = [];
                  }
    
                  // Start a new match
                  currentMatch = {
                    file: fileName,
                    line_number: parseInt(lineNumberMatch[2]),
                    content: lineNumberMatch[3],
                    context_before: contextLines,
                    context_after: [],
                  };
                  contextLines = [];
                } else {
                  // This is a context line
                  const contextMatch = line.match(/^([^:]+)-(\d+)-(.*)/);
                  if (contextMatch) {
                    contextLines.push({
                      line_number: parseInt(contextMatch[2]),
                      content: contextMatch[3],
                    });
                  }
                }
              }
    
              // Add the last match if there is one
              if (currentMatch) {
                currentMatch.context_after = contextLines;
                matches.push(currentMatch);
              }
    
              if (matches.length > 0) {
                results.push({
                  file: fileName,
                  matches: matches,
                });
              }
            }
          }
        }
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  pattern: pattern,
                  case_sensitive: case_sensitive,
                  context_lines: context_lines,
                  file_patterns: file_patterns,
                  results: results,
                  total_matches: results.reduce(
                    (sum, file) => sum + file.matches.length,
                    0
                  ),
                  total_files: results.length,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                { error: `Failed to search repository: ${error.message}` },
                null,
                2
              ),
            },
          ],
          isError: true,
        };
      }
    }
  • Tool schema definition including input parameters validation for repo_url, pattern, file_patterns, case_sensitive, and context_lines.
    {
      name: "git_search_code",
      description: "Search for patterns in repository code.",
      inputSchema: {
        type: "object",
        properties: {
          repo_url: {
            type: "string",
            description: "The URL of the Git repository",
          },
          pattern: {
            type: "string",
            description: "Search pattern (regex or string)",
          },
          file_patterns: {
            type: "array",
            items: { type: "string" },
            description: 'Optional file patterns to filter (e.g., "*.js")',
          },
          case_sensitive: {
            type: "boolean",
            description: "Whether the search is case sensitive",
            default: false,
          },
          context_lines: {
            type: "integer",
            description: "Number of context lines to include",
            default: 2,
          },
        },
        required: ["repo_url", "pattern"],
      },
    },
  • src/server.js:898-934 (registration)
    Registration of the handleGitSearchCode function to the 'git_search_code' tool name in the handlersMap used by the MCP server to dispatch tool calls. Also includes alias registration.
    this.handlersMap = {
      // Primary handlers
      git_directory_structure: handleGitDirectoryStructure,
      git_read_files: handleGitReadFiles,
      git_branch_diff: handleGitBranchDiff,
      git_commit_history: handleGitCommitHistory,
      git_commits_details: handleGitCommitsDetails,
      git_local_changes: handleGitLocalChanges,
      git_search_code: handleGitSearchCode,
      git_commit: handleGitCommit,
      git_track: handleGitTrack,
      git_checkout_branch: handleGitCheckoutBranch,
      git_delete_branch: handleGitDeleteBranch,
      git_merge_branch: handleGitMergeBranch,
      git_push: handleGitPush,
      git_pull: handleGitPull,
      git_stash: handleGitStash,
      git_create_tag: handleGitCreateTag,
      git_rebase: handleGitRebase,
      git_config: handleGitConfig,
      git_reset: handleGitReset,
      git_archive: handleGitArchive,
      git_attributes: handleGitAttributes,
      git_blame: handleGitBlame,
      git_clean: handleGitClean,
      git_hooks: handleGitHooks,
      git_lfs: handleGitLFS,
      git_lfs_fetch: handleGitLFSFetch,
      git_revert: handleGitRevert,
    };
    
    // Register aliases for O(1) lookup
    Object.entries(this.handlerAliases).forEach(([alias, target]) => {
      if (this.handlersMap[target]) {
        this.handlersMap[alias] = this.handlersMap[target];
      }
    });
  • src/server.js:7-10 (registration)
    Import of handleGitSearchCode into server.js via handlers/index.js
    } from "@modelcontextprotocol/sdk/types.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
    
    import {
  • Re-export of handleGitSearchCode from directory-operations.js in handlers index for convenient import in server.js
    export {
      // Directory operations
      handleGitDirectoryStructure,
      handleGitReadFiles,
      handleGitSearchCode,
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. While 'search' implies a read-only operation, the description doesn't mention important behavioral aspects like whether it requires repository access permissions, how it handles large repositories, whether results are paginated, or what format the output takes. This leaves significant gaps for a tool with 5 parameters.

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 with zero waste. It's appropriately sized for a search tool and front-loads the core functionality without unnecessary elaboration, making it easy for an agent to parse quickly.

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 search tool with 5 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the search returns (e.g., matches with line numbers, file paths), doesn't mention performance considerations for large codebases, and provides no context about error conditions or limitations.

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%, providing good documentation for all 5 parameters. The description adds no additional parameter semantics beyond what's in the schema, so it meets the baseline of 3 where the schema does the heavy lifting but doesn't compensate with extra insights.

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

Purpose4/5

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

The description 'Search for patterns in repository code' clearly states the verb ('search') and resource ('repository code'), making the purpose understandable. However, it doesn't specifically differentiate this tool from potential siblings like 'git_read_files' or 'git_directory_structure' that might also involve code examination, missing the highest clarity tier.

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. With many sibling tools available (e.g., git_read_files, git_commit_history), there's no indication of when pattern searching is preferred over other code inspection methods, leaving the agent without contextual usage cues.

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/bsreeram08/git-commands-mcp'

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