Skip to main content
Glama

find_in_file

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 });
      }
    });

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