Skip to main content
Glama
pwilkin

MCP File Editor Server

by pwilkin

delete_from_file

Remove specific lines from a file by specifying the start and end line numbers, with content verification to ensure accuracy. Simplifies file editing and data cleanup tasks.

Instructions

Delete content from a file between specified line numbers.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
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 main handler function that performs the deletion of lines from the file after validating the path, file existence, and starting line content.
    execute: async ({ file_path, line_start, line_end, line_start_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.');
        }
    
        // Remove the specified lines (inclusive)
        const newLines = [
          ...lines.slice(0, line_start - 1), // Lines before start
          ...lines.slice(line_end) // Lines after end
        ];
    
        const newContent = newLines.join('\n');
        fs.writeFileSync(absolutePath, newContent, 'utf-8');
    
        return `Successfully deleted lines ${line_start}-${line_end} from "${absolutePath}".`;
      } catch (error: any) {
        if (error instanceof UserError) throw error;
        throw new UserError(`Error deleting content from file "${absolutePath}": ${error.message}`);
      }
    }
  • Zod schema defining the input parameters for the delete_from_file tool.
    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)')
    }),
  • src/index.ts:124-167 (registration)
    Registration of the delete_from_file tool using server.addTool.
    server.addTool({
      name: 'delete_from_file',
      description: 'Delete content from a file between specified line numbers.',
      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)')
      }),
      execute: async ({ file_path, line_start, line_end, line_start_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.');
          }
    
          // Remove the specified lines (inclusive)
          const newLines = [
            ...lines.slice(0, line_start - 1), // Lines before start
            ...lines.slice(line_end) // Lines after end
          ];
    
          const newContent = newLines.join('\n');
          fs.writeFileSync(absolutePath, newContent, 'utf-8');
    
          return `Successfully deleted lines ${line_start}-${line_end} from "${absolutePath}".`;
        } catch (error: any) {
          if (error instanceof UserError) throw error;
          throw new UserError(`Error deleting content from file "${absolutePath}": ${error.message}`);
        }
      }
    });
  • Helper function to verify the content of the starting line before deletion, ensuring safety and correctness.
    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)}`
        );
      }
    }
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