Blog
searchCode function in git-mcp codebase.

searchCode function in git-mcp codebase.

In this article, we will review searchCode function in git-mcp codebase. We will look at: 

  1. searchRepositoryCode function

  2. searchCode function

  3. githubApiRequest function

searchRepositoryCode function

In git-mcp/src/api/tools/commonTools.ts, at line 578, you will find the following code:

export async function searchRepositoryCode({
  repoData,
  query,
  page = 1,
  env,
  ctx,
}: {
  repoData: RepoData;
  query: string;
  page?: number;
  env: Env;
  ctx: any;
}): Promise<{
  searchQuery: string;
  content: { type: "text"; text: string }[];
  pagination?: {
    totalCount: number;
    currentPage: number;
    perPage: number;
    hasMorePages: boolean;
  };
}> {
  try {
    // Initialize owner and repo from the provided repoData
    const owner = repoData.owner;
    const repo = repoData.repo;

This is an mcp tool that uses Github search API to find code matching a query. It also supports pagination for retrieving more results.

At line 625, you will find the following code:

const data = await searchCode(
      query,
      owner,
      repo,
      env,
      currentPage,
      resultsPerPage,
    );

This is calling a function named searchCode that is imported as shown below:

import { searchCode } from "../utils/githubClient.js";

searchCode function

In git-mcp/src/api/utils/githubClient.ts , at line 245, you will find the following code:

export async function searchCode(
  query: string,
  owner: string,
  repo: string,
  env: Env,
  page: number = 1,
  perPage: number = 20,
): Promise<any> {
  // GitHub API has a max per_page of 100
  const validPerPage = Math.min(Math.max(1, perPage), 100);

  const searchUrl = `https://api.github.com/search/code?q=${encodeURIComponent(query)}+repo:${owner}/${repo}&page=${page}&per_page=${validPerPage}`;

  const response = await githubApiRequest(searchUrl, {}, env);

  if (!response || !response.ok) {
    console.warn(
      `GitHub API code search failed: ${response?.status} ${response?.statusText}`,
    );
    return null;
  }

This function uses Github search API to search for a code in a Github repository.

At line 258, you will find the below code:

const response = await githubApiRequest(searchUrl, {}, env);

githubApiRequest function is defined in the same file.

githubApiRequest function

At line 125 you will find the following code 

/**
 * Make a GitHub API request with rate limit handling
 * @param url - API URL to fetch
 * @param options - Fetch options
 * @param env - Environment containing GitHub token if available
 * @param retryCount - Current retry attempt (used internally)
 * @param useAuth - Whether to include authorization header if token is available (default: true)
 * @returns The API response or null if failed
 */
export async function githubApiRequest(
  url: string,
  options: RequestInit = {},
  env: CloudflareEnvironment,
  retryCount = 1,
  useAuth = true,
): Promise<Response | null> {
  try {
    // Extract repository context for metrics
    const repoContext = extractRepoContextFromUrl(url);

    // Track GitHub query count using Cloudflare analytics
    if (env?.CLOUDFLARE_ANALYTICS && retryCount === 0) {
      env.CLOUDFLARE_ANALYTICS.writeDataPoint({
        blobs: [url, repoContext],
        doubles: [1],
        indexes: ["github_api_request"],
      });
    }

    // Wait for rate limit if necessary
    await respectRateLimits();
    ...

You can use this function to make a Github API request with rate limiting handled.

It has the following parameters 

 * @param url - API URL to fetch
 * @param options - Fetch options
 * @param env - Environment containing GitHub token if available
 * @param retryCount - Current retry attempt (used internally)
 * @param useAuth - Whether to include authorization header if token is available (default: true)

And it returns the following 

 * @returns The API response or null if failed

This is used in five places as shown below 

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Want to learn from open-source? Solve challenges inspired by open-source projects.

References:

  1. https://github.com/idosal/git-mcp/blob/main/src/api/tools/commonTools.ts#L625

  2. https://github.com/idosal/git-mcp/blob/main/src/api/utils/githubClient.ts#L258

  3. https://github.com/idosal/git-mcp/blob/main/src/api/utils/githubClient.ts#L170

  4. https://gitmcp.io/

  5. https://github.com/idosal/git-mcp/blob/main/src/api/utils/githubClient.ts#L245