Skip to main content
Glama

find_in_file

Read-only

Search for text patterns in files using regular expressions to locate specific content within documents.

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)
    Registration of the 'find_in_file' MCP tool including schema definition and 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
      }
    });
  • Input schema for the 'find_in_file' tool defining parameters: path, pattern, contextLines
      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
      }
    });
  • Core implementation of file search logic: reads file content, matches RegExp pattern per line, collects context lines around matches
    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}`);
      }
    }
  • Generic handler for all tool calls via 'tools/call'; currently placeholder but would dispatch to specific tool logic like findInFile
    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
        ]
      };
    }
  • HTTP endpoint /api/search that proxies requests to the 'find_in_file' MCP tool
    this.app.post('/api/search', async (req, res) => {
      try {
        const searchRequest = parseMessage({
          jsonrpc: '2.0',
          method: 'tools/call',
          params: {
            name: 'find_in_file',
            arguments: {
              path: req.body.path,
              pattern: req.body.pattern,
              contextLines: req.body.contextLines || 2
            }
          },
          id: 'rest-' + Date.now()
        });
        const response = await this.mcpServer.handleMessage(searchRequest);
        res.json(response);
      } catch (error: any) {
        res.status(500).json({ error: error.message });
      }
    });

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.3/5.0
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.