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

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

With no annotations, the description carries full burden but only states the basic action without disclosing critical behavioral traits. It doesn't mention whether the deletion is permanent, requires file permissions, handles errors (e.g., invalid line numbers), or affects file structure. This leaves significant gaps for a destructive operation.

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, clear sentence that efficiently conveys the core functionality without unnecessary details. It is front-loaded and wastes no words, making it easy to understand at a glance.

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?

Given the complexity of a destructive file operation with no annotations and no output schema, the description is inadequate. It lacks information on outcomes (e.g., success/failure indicators), error handling, or safety considerations, leaving the agent under-informed for proper tool invocation.

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 well-documented in the schema. The description adds minimal value by implying line-based deletion but doesn't provide additional context beyond what the schema already covers, such as how 'line_start_contents' verification works or edge cases.

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 ('Delete content') and resource ('from a file'), specifying the scope ('between specified line numbers'). It distinguishes from siblings like 'replace_in_file' or 'insert_into_file' by focusing on deletion rather than modification or addition, though it doesn't explicitly name alternatives.

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?

No guidance is provided on when to use this tool versus alternatives like 'replace_in_file' or 'replace_lines_in_file' for similar line-based operations. The description implies usage for deleting content between lines but lacks context on prerequisites, exclusions, or specific scenarios.

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