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 [];
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. While 'search' implies a read-only operation, the description doesn't specify important behavioral aspects: what 'allowed directories' means (permissions? configuration?), whether this is a recursive search, what the output format looks like, or any performance considerations. For a search tool with 6 parameters and no annotation coverage, this is insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise - a single sentence in Chinese that efficiently conveys the core purpose. Every word serves a purpose: 'search' (action), 'code' (target), 'containing specific text' (criteria), 'within allowed directories' (scope). There's no wasted verbiage or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a search tool with 6 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what parameters do, what the search returns, how results are formatted, or any constraints. While conciseness is good, the description lacks essential information needed for an agent to effectively use this tool, especially given the complexity implied by multiple parameters.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage for all 6 parameters, the description provides no information about any parameters. It mentions 'specific text' which loosely corresponds to 'searchText', but doesn't explain the other 5 parameters at all. The description fails to compensate for the complete lack of schema documentation, leaving most parameters completely unexplained.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('search') and target ('code containing specific text'), making the purpose understandable. It specifies 'within allowed directories' which adds useful scope information. However, it doesn't explicitly differentiate this from sibling tools like 'find_files' or 'localizationSearch' which might also search code or files.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides minimal guidance on when to use this tool. It mentions 'within allowed directories' which gives some context about scope, but offers no explicit comparison to alternatives like 'find_files' (which might search file names rather than content) or 'localizationSearch' (which might search localization strings). No guidance on when NOT to use this tool is provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

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

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