Skip to main content
Glama

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,

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