Skip to main content
Glama
pwilkin

MCP File Editor Server

by pwilkin

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
NameRequiredDescriptionDefault
contentsYesNew content to replace the lines with
file_pathYesAbsolute path to the file
line_endYesEnding line number (1-based)
line_startYesStarting line number (1-based)
line_start_contentsYesExpected content of the starting line (used for verification)

Implementation Reference

  • 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}`);
      }
    }
  • 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}`);
        }
      }
    });
  • 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)}`
        );
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the core action but omits critical details: whether the operation is destructive (likely yes, but not confirmed), what happens if line numbers are invalid, how 'line_start_contents' verification works, if changes are atomic or reversible, or what the tool returns. This is a significant gap for a file mutation tool.

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 function without unnecessary words. It's front-loaded with the core action and avoids redundancy, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a destructive file operation with 5 parameters and no annotations or output schema, the description is inadequate. It lacks information about behavioral traits (safety, error handling), output format, and differentiation from sibling tools. The agent would struggle to use this correctly without trial and error.

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%, so parameters are fully documented in the schema. The description adds no additional semantic context beyond implying line-based replacement, which is already clear from parameter names. It doesn't explain interactions between parameters (e.g., how 'line_start_contents' relates to 'line_start') or provide usage examples.

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 action ('Replace content') and target ('between specific line numbers in a file'), making the purpose understandable. It distinguishes from siblings like 'replace_in_file' (likely pattern-based) by specifying line-based replacement, but doesn't explicitly contrast with 'delete_from_file' or 'insert_into_file' which are also line-oriented operations.

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 like 'replace_in_file', 'delete_from_file', or 'insert_into_file'. It doesn't mention prerequisites (e.g., file must exist), error conditions, or typical use cases, leaving the agent to infer usage from the name and parameters 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

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

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