Skip to main content
Glama

search_code

Search for patterns in code within a specified directory. Use a query or regex, optionally filter by file pattern like *.py or *.js. Ideal for locating specific code snippets across projects.

Instructions

Search for patterns in code

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query or regex
pathYesDirectory to search in
file_patternNoFile pattern (e.g., *.py, *.js)
regexNoUse regex search

Implementation Reference

  • Main handler function for the 'search_code' tool. Accepts SearchCodeArgs (query, path, file_pattern, regex), resolves the search path via WorkspaceService, then recursively searches directories for matching patterns. Returns results as JSON string.
    async searchCode(args: SearchCodeArgs): Promise<ToolResult> {
      const { query, path: searchPath, file_pattern, regex = false } = args;
      ValidationUtils.validateRequired({ query, path: searchPath }, ['query', 'path']);
      
      const fullPath = this.workspaceService.resolvePath(searchPath);
      const results: SearchResult[] = [];
      
      try {
        await this.searchInDirectory(fullPath, query, file_pattern, regex, results);
        
        return {
          content: [{
            type: 'text',
            text: JSON.stringify(results, null, 2),
          }],
        };
      } catch (error) {
        throw new Error(`Failed to search code: ${error instanceof Error ? error.message : 'Unknown error'}`);
      }
    }
  • Helper that recursively walks directories, skips hidden files, applies file_pattern filter, restricts to known text/code file extensions, and calls searchInFile on each matching file.
    private async searchInDirectory(
      dirPath: string, 
      query: string, 
      filePattern?: string, 
      regex: boolean = false, 
      results: SearchResult[] = []
    ): Promise<void> {
      try {
        const entries = await fs.readdir(dirPath, { withFileTypes: true });
        
        for (const entry of entries) {
          if (entry.name.startsWith('.')) continue; // Skip hidden files
          
          const fullPath = path.join(dirPath, entry.name);
          
          if (entry.isDirectory()) {
            await this.searchInDirectory(fullPath, query, filePattern, regex, results);
          } else if (entry.isFile()) {
            // Check file pattern if specified
            if (filePattern && !entry.name.match(new RegExp(filePattern))) {
              continue;
            }
            
            // Only search in text files
            const ext = path.extname(entry.name).toLowerCase();
            if (!['.js', '.jsx', '.ts', '.tsx', '.py', '.java', '.c', '.cpp', '.txt', '.md'].includes(ext)) {
              continue;
            }
            
            await this.searchInFile(fullPath, query, regex, results);
          }
        }
      } catch (error) {
        // Skip directories we can't read
      }
    }
  • Helper that reads a single file, splits into lines, matches against the query (plain text or regex), and pushes SearchResult objects with file, line, column, content, and match text.
    private async searchInFile(filePath: string, query: string, regex: boolean, results: SearchResult[]): Promise<void> {
      try {
        const content = await fs.readFile(filePath, 'utf8');
        const lines = content.split('\n');
        
        const searchPattern = regex ? new RegExp(query, 'gi') : query.toLowerCase();
        
        lines.forEach((line, index) => {
          let match = false;
          let matchText = '';
          
          if (regex && searchPattern instanceof RegExp) {
            const regexMatch = line.match(searchPattern);
            if (regexMatch) {
              match = true;
              matchText = regexMatch[0];
            }
          } else {
            const lowerLine = line.toLowerCase();
            if (lowerLine.includes(searchPattern as string)) {
              match = true;
              matchText = query;
            }
          }
          
          if (match) {
            results.push({
              file: filePath,
              line: index + 1,
              column: line.indexOf(matchText) + 1,
              content: line.trim(),
              match: matchText
            });
          }
        });
      } catch (error) {
        // Skip files we can't read
      }
    }
  • TypeScript interface defining the input arguments for search_code: query (string, required), path (string, required), file_pattern (optional), regex (optional boolean).
    export interface SearchCodeArgs {
      query: string;
      path: string;
      file_pattern?: string;
      regex?: boolean;
    }
  • src/index.ts:231-232 (registration)
    Dispatch in the main server's executeToolCommand switch-case that routes 'search_code' to this.analysisService.searchCode(args as SearchCodeArgs).
    case 'search_code':
      return await this.analysisService.searchCode(args as SearchCodeArgs);
  • Tool definition/schema registration for 'search_code' including its description and inputSchema (query, path, file_pattern, regex properties).
    {
      name: 'search_code',
      description: 'Search for patterns in code',
      inputSchema: {
        type: 'object',
        properties: {
          query: { type: 'string', description: 'Search query or regex' },
          path: { type: 'string', description: 'Directory to search in' },
          file_pattern: { type: 'string', description: 'File pattern (e.g., *.py, *.js)' },
          regex: { type: 'boolean', description: 'Use regex search' },
        },
        required: ['query', 'path'],
      },
    },
Behavior2/5

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

No annotations provided; the description carries the burden but only states 'Search for patterns in code'. It does not disclose traits like read-only behavior, recursion depth, or performance impact.

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

Conciseness3/5

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

The description is very concise (one sentence), which is appropriate for a simple tool, but it could include more context without being verbose.

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?

No output schema and the description does not mention return values (e.g., matched lines or file paths). The tool is incomplete for an agent that needs to know what to expect.

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

Parameters3/5

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

Schema description coverage is 100%, so baseline is 3. The description does not add meaning beyond the schema, but the schema itself adequately describes the parameters.

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

Purpose3/5

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

The description states the verb 'search' and resource 'patterns in code', which is clear but vague. It does not differentiate from sibling tools like 'find_and_replace' or 'analyze_code' that also deal with code patterns.

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?

No guidance on when to use this tool vs alternatives. The description lacks context about when it is appropriate to use search_code versus other search or analysis tools.

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/agentics-ai/code-mcp'

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