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 });
      }
    });
Behavior3/5

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

Annotations declare readOnlyHint=true and openWorldHint=false, indicating a safe, read-only operation with limited scope. The description adds minimal behavioral context beyond this, as it doesn't specify details like error handling, performance, or output format. It doesn't contradict annotations, but with annotations covering safety, the description adds little extra value, meeting the baseline for tools with good annotation coverage.

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 any wasted words. It is front-loaded and appropriately sized for a simple search tool, making it easy for an agent to parse quickly.

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 low complexity (simple search with 3 parameters), good annotations (read-only, closed-world), and no output schema, the description is minimally adequate. It covers the basic action but lacks details on output format or error cases, which could be helpful for the agent. It meets the minimum viable standard without being fully comprehensive.

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 all parameters (path, pattern, contextLines). The description adds no additional meaning beyond the schema, such as explaining regex capabilities or context line behavior. Given high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but doesn't need to due to the schema's completeness.

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 the resource 'occurrences of a pattern in a file', making the purpose specific and understandable. However, it does not explicitly differentiate from sibling tools like 'complex_find_replace' or 'smart_refactor', which might have overlapping search functionalities, so it lacks sibling differentiation for a perfect score.

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' for replacement operations or 'smart_refactor' for code-specific searches, there is no indication of context, exclusions, or prerequisites, leaving the agent to infer usage based on tool names alone.

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

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