find_in_file
Search for specific patterns within a file using regular expressions, including optional context lines for better match visibility.
Instructions
Find occurrences of a pattern in a file
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| contextLines | No | Number of context lines to include before and after matches (default: 2) | |
| path | Yes | Path to the file to search in | |
| pattern | Yes | Regular expression pattern to search for |
Input Schema (JSON Schema)
{
"properties": {
"contextLines": {
"description": "Number of context lines to include before and after matches (default: 2)",
"type": "number"
},
"path": {
"description": "Path to the file to search in",
"type": "string"
},
"pattern": {
"description": "Regular expression pattern to search for",
"type": "string"
}
},
"required": [
"path",
"pattern"
],
"type": "object"
}
Implementation Reference
- Core handler function that executes the find_in_file tool logic: reads file content, searches line-by-line with RegExp, collects matches with context lines.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}`); } }
- src/index.ts:215-241 (registration)Registers the 'find_in_file' tool with MCP server, including name, description, input schema, 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 } }); }
- Uses findInFile as a helper in smart_refactor hybrid operation to locate occurrences before editing.operation.affectedFiles.map(file => this.fileSystemManager.findInFile( file, new RegExp(operation.params.oldName, 'g') ) ) );
- Defines the output structure for search results returned by the handler.export interface SearchResult { line: number; column: number; text: string; linesBefore: string[]; linesAfter: string[]; }