replace_lines_in_file
Modify specific lines in a file by replacing content between defined start and end line numbers. Verify changes using expected line content for accurate file manipulation.
Instructions
Replace content between specific line numbers in a file.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| contents | Yes | New content to replace the lines with | |
| file_path | Yes | Absolute path to the file | |
| line_end | Yes | Ending line number (1-based) | |
| line_start | Yes | Starting line number (1-based) | |
| line_start_contents | Yes | Expected content of the starting line (used for verification) |
Implementation Reference
- src/index.ts:223-257 (handler)The execute handler function implementing the core logic of the 'replace_lines_in_file' tool. It validates the file path and existence, verifies the starting line content, reads the file, replaces the specified line range with new contents, writes back to the file, and returns a success message.execute: async ({ file_path, line_start, line_end, line_start_contents, contents }) => { const absolutePath = validateAbsolutePath(file_path, 'file_path'); validateFileExists(absolutePath); try { // Verify the starting line content verifyLineContent(absolutePath, line_start, line_start_contents); const content = fs.readFileSync(absolutePath, 'utf-8'); const lines = content.split('\n'); if (line_start > lines.length || line_end > lines.length) { throw new UserError(`Line range ${line_start}-${line_end} is beyond file length (${lines.length} lines).`); } if (line_start > line_end) { throw new UserError('line_start must be less than or equal to line_end.'); } // Replace the specified lines const newLines = [ ...lines.slice(0, line_start - 1), // Lines before start contents, // New content ...lines.slice(line_end) // Lines after end ]; const newContent = newLines.join('\n'); fs.writeFileSync(absolutePath, newContent, 'utf-8'); return `Successfully replaced lines ${line_start}-${line_end} in "${absolutePath}".`; } catch (error: any) { if (error instanceof UserError) throw error; throw new UserError(`Error replacing content in file "${absolutePath}": ${error.message}`); } }
- src/index.ts:216-222 (schema)Zod schema defining the input parameters for the tool: file_path (string), line_start (positive int), line_end (positive int), line_start_contents (string for verification), contents (string for replacement).parameters: z.object({ file_path: z.string().describe('Absolute path to the file'), line_start: z.number().int().positive().describe('Starting line number (1-based)'), line_end: z.number().int().positive().describe('Ending line number (1-based)'), line_start_contents: z.string().describe('Expected content of the starting line (used for verification)'), contents: z.string().describe('New content to replace the lines with') }),
- src/index.ts:213-258 (registration)The server.addTool call that registers the 'replace_lines_in_file' tool with the FastMCP server, specifying name, description, parameters schema, and execute handler.server.addTool({ name: 'replace_lines_in_file', description: 'Replace content between specific line numbers in a file.', parameters: z.object({ file_path: z.string().describe('Absolute path to the file'), line_start: z.number().int().positive().describe('Starting line number (1-based)'), line_end: z.number().int().positive().describe('Ending line number (1-based)'), line_start_contents: z.string().describe('Expected content of the starting line (used for verification)'), contents: z.string().describe('New content to replace the lines with') }), execute: async ({ file_path, line_start, line_end, line_start_contents, contents }) => { const absolutePath = validateAbsolutePath(file_path, 'file_path'); validateFileExists(absolutePath); try { // Verify the starting line content verifyLineContent(absolutePath, line_start, line_start_contents); const content = fs.readFileSync(absolutePath, 'utf-8'); const lines = content.split('\n'); if (line_start > lines.length || line_end > lines.length) { throw new UserError(`Line range ${line_start}-${line_end} is beyond file length (${lines.length} lines).`); } if (line_start > line_end) { throw new UserError('line_start must be less than or equal to line_end.'); } // Replace the specified lines const newLines = [ ...lines.slice(0, line_start - 1), // Lines before start contents, // New content ...lines.slice(line_end) // Lines after end ]; const newContent = newLines.join('\n'); fs.writeFileSync(absolutePath, newContent, 'utf-8'); return `Successfully replaced lines ${line_start}-${line_end} in "${absolutePath}".`; } catch (error: any) { if (error instanceof UserError) throw error; throw new UserError(`Error replacing content in file "${absolutePath}": ${error.message}`); } } });
- src/utils.ts:90-124 (helper)The verifyLineContent helper function, crucial for safe editing, which reads the file, checks if the line exists, and verifies the content matches expected (after normalizing whitespace). Used in the handler at line 229.export function verifyLineContent(filePath: string, lineNumber: number, expectedContent: string): string { try { const content = fs.readFileSync(filePath, 'utf-8'); const lines = content.split('\n'); if (lineNumber < 1 || lineNumber > lines.length) { throw new UserError( `Line ${lineNumber} does not exist in file "${filePath}". The file has ${lines.length} lines. ` + `Please verify the line number and re-read the file with show_line_numbers=true to see the current content.` ); } const actualContent = lines[lineNumber - 1]; // Convert to 0-based index const normalizedActual = actualContent.trim().replace(/\s+/g, ' '); const normalizedExpected = expectedContent.trim().replace(/\s+/g, ' '); if (normalizedActual !== normalizedExpected) { throw new UserError( `Line content verification failed for line ${lineNumber} in "${filePath}".\n` + `Expected (normalized): "${normalizedExpected}"\n` + `Actual (normalized): "${normalizedActual}"\n` + `Please re-read the file with show_line_numbers=true to see the current content and update your request accordingly.` ); } return actualContent; } catch (error) { if (error instanceof UserError) { throw error; } throw new UserError( `Error reading file "${filePath}" for line verification: ${error instanceof Error ? error.message : String(error)}` ); } }