Skip to main content
Glama

git_search_code

Search for specific code patterns within a Git repository using regex or strings, filter by file types, and include contextual lines for better analysis.

Instructions

Search for patterns in repository code.

Input Schema

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

Implementation Reference

  • Core handler function for git_search_code tool. Clones the Git repository, constructs and executes a git grep command with support for case sensitivity, context lines, and file pattern filtering. Parses the grep output into a structured JSON response with file matches, line numbers, and context lines.
    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, }; } }
  • Input schema definition for the git_search_code tool, specifying parameters like repo_url, pattern, optional 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-927 (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.
    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, };
  • Re-export of handleGitSearchCode from directory-operations.js, imported into server.js.
    handleGitDirectoryStructure, handleGitReadFiles, handleGitSearchCode, handleGitLocalChanges, } from "./directory-operations.js"; import { handleGitCommitHistory, handleGitCommitsDetails, handleGitCommit, handleGitTrack, } from "./commit-operations.js"; import { handleGitBranchDiff, handleGitCheckoutBranch, handleGitDeleteBranch, handleGitMergeBranch, } from "./branch-operations.js"; import { handleGitPush, handleGitPull, handleGitRemote, } from "./remote-operations.js"; import { handleGitStash } from "./stash-operations.js"; import { handleGitCreateTag } from "./tag-operations.js"; import { handleGitRebase, handleGitReset } from "./advanced-operations.js"; import { handleGitConfig } from "./config-operations.js"; import { handleGitArchive, handleGitAttributes, handleGitBlame, handleGitClean, handleGitHooks, handleGitLFS, handleGitLFSFetch, handleGitRevert, } from "./other-operations.js"; // Re-export all handlers 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