Skip to main content
Glama

search_code

Find code containing specific text within allowed directories to locate functions, variables, or patterns in your codebase.

Instructions

在允許的目錄中搜尋包含特定文字的程式碼

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
searchTextYes
filePatternNo
excludeDirsNo
caseSensitiveNo
maxResultsNo
maxContextLinesNo

Implementation Reference

  • Core handler function that performs recursive code search in allowed directories, filters files, finds matching lines, and formats results with context.
    public static async searchInAllowedDirectories( searchText: string, excludeDirs: string[] = ['node_modules', '.git', 'dist', 'bin', 'obj'], caseSensitive: boolean = false, filePattern: string = '*', maxResults: number = 1000, maxContextLines: number = 5 ): Promise<string> { try { if (!searchText || searchText.trim() === '') { return '錯誤: 請提供要搜尋的文字'; } // 獲取允許的目錄 const allowedDirs = this.getAllowedDirectories(); // 檢查是否有允許的目錄 if (allowedDirs.length === 0) { return '錯誤:未提供允許的目錄參數。請在啟動時指定至少一個允許的目錄。'; } let totalResults = 0; let formattedResults = ''; let allFilesFound = 0; for (const dir of allowedDirs) { if (!fs.existsSync(dir)) { continue; } const dirResults = await this.searchInDirectory( dir, searchText, excludeDirs, caseSensitive, filePattern ); allFilesFound += dirResults.size; for (const [file, matches] of dirResults.entries()) { if (totalResults >= maxResults) { break; } const relativePath = file.replace(dir, dir.split(path.sep).pop() || path.basename(dir)); formattedResults += `\n檔案: ${relativePath} (${matches.length} 個匹配)\n`; // 限制每個檔案的匹配數量 const displayMatches = matches.slice(0, maxContextLines); for (const match of displayMatches) { formattedResults += ` 行 ${match.lineNumber}: ${match.line}\n`; totalResults++; } if (matches.length > maxContextLines) { formattedResults += ` ... 以及 ${matches.length - maxContextLines} 個更多匹配\n`; } formattedResults += '\n'; } if (totalResults >= maxResults) { formattedResults += `\n達到最大結果數量限制 (${maxResults}),可能還有更多匹配項未顯示。`; break; } } if (formattedResults === '') { return `在允許的目錄中未找到包含 "${searchText}" 的檔案`; } return `找到 ${totalResults} 個匹配項,分佈在 ${allFilesFound} 個檔案中:${formattedResults}`; } catch (error) { return `搜尋過程中發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } }
  • main.ts:512-550 (registration)
    Registers the 'search_code' MCP tool, providing description, input schema, and inline async handler that delegates to CodeSearchTool.
    server.tool("search_code", "在允許的目錄中搜尋包含特定文字的程式碼", { searchText: z.string(), filePattern: z.string().optional(), excludeDirs: z.array(z.string()).optional(), caseSensitive: z.boolean().optional(), maxResults: z.number().optional(), maxContextLines: z.number().optional() }, async ({ searchText, filePattern = '*', excludeDirs = ['node_modules', '.git', 'dist', 'bin', 'obj'], caseSensitive = false, maxResults = 1000, maxContextLines = 5 }) => { try { // 在允許的目錄中搜尋程式碼 const result = await CodeSearchTool.searchInAllowedDirectories( searchText, excludeDirs, caseSensitive, filePattern, maxResults, maxContextLines ); return { content: [{ type: "text", text: result }] }; } catch (error) { return { content: [{ type: "text", text: `搜尋程式碼失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }] }; } } );
  • Zod schema defining input parameters for the search_code tool.
    { searchText: z.string(), filePattern: z.string().optional(), excludeDirs: z.array(z.string()).optional(), caseSensitive: z.boolean().optional(), maxResults: z.number().optional(), maxContextLines: z.number().optional()
  • Helper method to retrieve allowed search directories from command-line arguments.
    private static getAllowedDirectories(): string[] { // 從命令行參數獲取允許的目錄(從第2個參數開始,因為第1個是Node路徑,第2個是腳本路徑) const args = process.argv.slice(2); // 如果命令行中有額外參數,則這些參數被視為允許的目錄 if (args && args.length > 0) { return args; } // 因沒有提供命令行參數,因此回報錯誤 console.error('錯誤:未提供允許的目錄參數。請在啟動時指定至少一個允許的目錄。'); console.error('使用範例:'); console.error('node [dist路徑]/main.js "C:\\path\\to\\allowed\\directory1" "C:\\path\\to\\allowed\\directory2"'); // 返回空陣列,表示沒有允許的目錄 return []; }

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/GonTwVn/GonMCPtool'

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