Skip to main content
Glama

find_in_file

Read-only

Search for text patterns in files using regular expressions, displaying matches with surrounding context lines for better analysis.

Instructions

Find occurrences of a pattern in a file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the file to search in
patternYesRegular expression pattern to search for
contextLinesNoNumber of context lines to include before and after matches (default: 2)

Implementation Reference

  • src/index.ts:215-240 (registration)
    Registers the 'find_in_file' MCP tool with its description, input schema (requiring path and pattern, optional contextLines), and read-only annotations.
    mcpServer.registerTool({
      name: 'find_in_file',
      description: 'Find occurrences of a pattern in a file',
      inputSchema: {
        type: 'object',
        properties: {
          path: {
            type: 'string',
            description: 'Path to the file to search in'
          },
          pattern: {
            type: 'string',
            description: 'Regular expression pattern to search for'
          },
          contextLines: {
            type: 'number',
            description: 'Number of context lines to include before and after matches (default: 2)'
          }
        },
        required: ['path', 'pattern']
      },
      annotations: {
        readOnlyHint: true,
        openWorldHint: false
      }
    });
  • Generic handler for all MCP tool calls ('tools/call'). Looks up the tool by name and currently returns a placeholder response indicating execution (intended location for specific tool logic).
    /**
     * Handles the tools/call request
     */
    private async handleToolsCall(params: { name: string, arguments?: any }): Promise<CallToolResult> {
      const { name, arguments: args } = params;
      
      if (!name) {
        throw new Error('Tool name is required');
      }
      
      const tool = this.tools.get(name);
      
      if (!tool) {
        throw new Error(`Tool not found: ${name}`);
      }
      
      // In a real implementation, we would execute the tool here
      // For now, we'll just return a placeholder
      
      return {
        content: [
          {
            type: 'text',
            text: `Executed tool ${name} with arguments: ${JSON.stringify(args)}`
          } as TextContent
        ]
      };
  • Core utility function that implements file search logic: reads file, splits into lines, finds RegExp matches, includes context lines before/after, returns structured SearchResult[] with line/column info. Matches 'find_in_file' tool signature exactly.
    public async findInFile(filePath: string, pattern: RegExp, contextLines: number = 2): Promise<SearchResult[]> {
      try {
        const content = await this.readFile(filePath);
        const lines = content.split('\n');
        const results: SearchResult[] = [];
    
        for (let i = 0; i < lines.length; i++) {
          const line = lines[i];
          const match = pattern.exec(line);
          
          if (match) {
            const linesBefore = lines.slice(Math.max(0, i - contextLines), i);
            const linesAfter = lines.slice(i + 1, Math.min(lines.length, i + contextLines + 1));
            
            results.push({
              line: i + 1,
              column: match.index + 1,
              text: line,
              linesBefore,
              linesAfter
            });
          }
        }
    
        return results;
      } catch (error: any) {
        throw new Error(`Failed to search in file ${filePath}: ${error.message}`);
      }
    }
Behavior3/5

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

Annotations indicate readOnlyHint=true and openWorldHint=false, so the agent knows this is a safe, non-destructive read operation with limited scope. The description adds minimal behavioral context beyond this, as it doesn't specify details like search behavior (e.g., case sensitivity, multiline matching) or output format, but it doesn't contradict the annotations either.

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 a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is front-loaded and wastes no space, making it highly concise and well-structured for quick comprehension.

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

Completeness3/5

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

Given the tool's moderate complexity (search with regex), lack of output schema, and rich annotations, the description is adequate but incomplete. It covers the basic action but doesn't address output details (e.g., match format, error handling) or advanced usage scenarios, leaving gaps that could hinder the agent in complex contexts.

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%, with clear descriptions for 'path', 'pattern', and 'contextLines' (including a default value). The description adds no additional meaning beyond the schema, such as explaining regex syntax or file path handling, so it meets the baseline for high schema coverage without enhancing parameter understanding.

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 verb ('Find') and resource ('occurrences of a pattern in a file'), making the purpose specific and understandable. However, it does not differentiate from sibling tools like 'complex_find_replace' or 'smart_refactor', which might offer similar search capabilities with additional features, so it misses full sibling differentiation.

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 no guidance on when to use this tool versus alternatives. With siblings like 'complex_find_replace' (which might include replacement) and 'smart_refactor' (which could involve refactoring), there is no explicit or implied context for choosing this simpler find tool over others, leaving the agent without usage direction.

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/mixelpixx/microsoft-edit-mcp'

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