Skip to main content
Glama

githubSearchCode

Search code across GitHub repositories using GitHub's API. Optimize queries with single terms, filters, and parallel searches for comprehensive results.

Instructions

Search code across GitHub repositories using GitHub's code search API via GitHub CLI.

SEARCH STRATEGY FOR BEST RESULTS:

ALWAYS START WITH BROAD QUERIES!

TERM OPTIMIZATION:

  • BEST: Single terms for maximum coverage

  • GOOD: 2-3 minimal terms with AND logic (all must be present in same file)

  • AVOID: Complex multi-term combinations - they're restrictive

  • Start broad, then narrow with filters or separate queries

MULTI-SEARCH STRATEGY:

  • Use separate searches for different aspects

  • Multiple simple queries > one complex query

  • Each search targets different code patterns or concepts

  • Parallel execution provides comprehensive coverage

Filter Usage:

  • Use filters to narrow scope after broad initial searches

  • Combine strategically: language + owner/repo for precision

  • Start without filters, then refine based on results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queriesYesArray of up to 5 different search queries for parallel execution

Implementation Reference

  • Core handler logic for executing GitHub code searches across multiple queries. Calls the GitHub API, processes responses, filters ignored files, extracts repository information, and formats results.
    async function searchMultipleGitHubCode( queries: GitHubCodeSearchQuery[], authInfo?: AuthInfo, sessionId?: string ): Promise<CallToolResult> { return executeBulkOperation( queries, async (query: GitHubCodeSearchQuery, _index: number) => { try { const apiResult = await searchGitHubCodeAPI(query, authInfo, sessionId); const apiError = handleApiError(apiResult, query); if (apiError) return apiError; if (!('data' in apiResult)) { return handleCatchError( new Error('Invalid API response structure'), query ); } const { owner, repo } = extractOwnerAndRepo( getNameWithOwner(apiResult) ); const files = apiResult.data.items .filter(item => !shouldIgnoreFile(item.path)) .map(item => { if (query.match === 'path') { return { path: item.path, text_matches: [] }; } return { path: item.path, text_matches: item.matches.map(match => match.context), }; }); return createSuccessResult( query, { files, owner, repo, } satisfies SearchResult, files.length > 0, 'GITHUB_SEARCH_CODE' ); } catch (error) { return handleCatchError(error, query); } }, { toolName: TOOL_NAMES.GITHUB_SEARCH_CODE, keysPriority: ['files', 'error'] satisfies Array<keyof SearchResult>, } ); }
  • Zod schemas defining the input structure for single and bulk GitHub code search queries, including parameters for keywords, scope, filters, limits, and processing options.
    export const GitHubCodeSearchQuerySchema = BaseQuerySchema.extend({ keywordsToSearch: z .array(z.string()) .min(1) .max(5) .describe(GITHUB_SEARCH_CODE.search.keywordsToSearch), owner: z.string().optional().describe(GITHUB_SEARCH_CODE.scope.owner), repo: z.string().optional().describe(GITHUB_SEARCH_CODE.scope.repo), extension: z .string() .optional() .describe(GITHUB_SEARCH_CODE.filters.extension), stars: z.string().optional().describe(GITHUB_SEARCH_CODE.filters.stars), filename: z.string().optional().describe(GITHUB_SEARCH_CODE.filters.filename), path: z.string().optional().describe(GITHUB_SEARCH_CODE.filters.path), match: z .enum(['file', 'path']) .optional() .describe(GITHUB_SEARCH_CODE.filters.match), limit: z .number() .int() .min(1) .max(20) .default(10) .optional() .describe(GITHUB_SEARCH_CODE.resultLimit.limit), minify: z .boolean() .optional() .default(true) .describe(GITHUB_SEARCH_CODE.processing.minify), sanitize: z .boolean() .optional() .default(true) .describe(GITHUB_SEARCH_CODE.processing.sanitize), }); export const GitHubCodeSearchBulkQuerySchema = createBulkQuerySchema( TOOL_NAMES.GITHUB_SEARCH_CODE, GitHubCodeSearchQuerySchema );
  • Registers the 'githubSearchCode' tool with the MCP server, specifying input schema, annotations, and a security-wrapped handler function.
    export function registerGitHubSearchCodeTool( server: McpServer, callback?: ToolInvocationCallback ) { return server.registerTool( TOOL_NAMES.GITHUB_SEARCH_CODE, { description: DESCRIPTIONS[TOOL_NAMES.GITHUB_SEARCH_CODE], inputSchema: GitHubCodeSearchBulkQuerySchema, annotations: { title: 'GitHub Code Search', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true, }, }, withSecurityValidation( TOOL_NAMES.GITHUB_SEARCH_CODE, async ( args: { queries: GitHubCodeSearchQuery[]; }, authInfo, sessionId ): Promise<CallToolResult> => { const queries = args.queries || []; if (callback) { try { await callback(TOOL_NAMES.GITHUB_SEARCH_CODE, queries); } catch { // ignore } } return searchMultipleGitHubCode(queries, authInfo, sessionId); } ) ); }
  • Helper function that invokes the GitHub code search API via Octokit, applies caching, query building, result optimization, content sanitization, and minification.
    export async function searchGitHubCodeAPI( params: GitHubCodeSearchQuery, authInfo?: AuthInfo, sessionId?: string ): Promise<GitHubAPIResponse<OptimizedCodeSearchResult>> { const cacheKey = generateCacheKey('gh-api-code', params, sessionId); const result = await withDataCache< GitHubAPIResponse<OptimizedCodeSearchResult> >( cacheKey, async () => { return await searchGitHubCodeAPIInternal(params, authInfo); }, { shouldCache: (value: GitHubAPIResponse<OptimizedCodeSearchResult>) => 'data' in value && !(value as { error?: unknown }).error, } ); return result; }
  • Tool configuration entry that includes the githubSearchCode tool as a default tool, referencing its registration function.
    export const GITHUB_SEARCH_CODE: ToolConfig = { name: TOOL_NAMES.GITHUB_SEARCH_CODE, description: getDescription(TOOL_NAMES.GITHUB_SEARCH_CODE), isDefault: true, type: 'search', fn: registerGitHubSearchCodeTool, };

Other Tools

Related 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/bgauryy/octocode-mcp'

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