Skip to main content
Glama
A-Niranjan

MCP Filesystem Server

by A-Niranjan

edit_file

Modify text files by replacing specific line sequences with new content, generating a git-style diff to track changes within allowed directories.

Instructions

Make line-based edits to a text file. Each edit replaces exact line sequences with new content. Returns a git-style diff showing the changes made. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the file to edit
editsYesList of edit operations to perform
dryRunNoPreview changes using git-style diff format

Implementation Reference

  • The editFile function that executes the core logic of the 'edit_file' tool: validates path, reads file, applies sequential exact-match text replacements preserving indentation, generates unified diff, writes changes if not dry-run.
    export async function editFile(
      args: z.infer<typeof EditFileArgsSchema>,
      config: Config
    ): Promise<string> {
      const endMetric = metrics.startOperation('edit_file')
      try {
        const validPath = await validatePath(args.path, config)
    
        // Read the original content
        const content = await fs.readFile(validPath, 'utf-8')
        let modifiedContent = content
    
        // Track whether any edit was applied
        let appliedAnyEdit = false
    
        // Apply each edit
        for (const edit of args.edits) {
          const contentLines = modifiedContent.split('\n')
          let matchFound = false
    
          // Normalize line endings
          const normalizedOld = edit.oldText.replace(/\r\n/g, '\n')
          const normalizedNew = edit.newText.replace(/\r\n/g, '\n')
          const oldLines = normalizedOld.split('\n')
    
          // Validate edit
          if (oldLines.length === 0) {
            throw new InvalidArgumentsError('edit_file', 'Edit operation contains empty oldText')
          }
    
          // Find and replace the text
          for (let i = 0; i <= contentLines.length - oldLines.length; i++) {
            const potentialMatch = contentLines.slice(i, i + oldLines.length).join('\n')
            if (potentialMatch === normalizedOld) {
              // Preserve indentation
              const originalIndent = contentLines[i].match(/^\s*/)?.[0] || ''
              const newLines = normalizedNew.split('\n').map((line, j) => {
                if (j === 0) return originalIndent + line.trimStart()
                const oldIndent = oldLines[j]?.match(/^\s*/)?.[0] || ''
                const newIndent = line.match(/^\s*/)?.[0] || ''
                if (oldIndent && newIndent) {
                  const relativeIndent = newIndent.length - oldIndent.length
                  return originalIndent + ' '.repeat(Math.max(0, relativeIndent)) + line.trimStart()
                }
                return line
              })
    
              contentLines.splice(i, oldLines.length, ...newLines)
              modifiedContent = contentLines.join('\n')
              matchFound = true
              appliedAnyEdit = true
              break
            }
          }
    
          if (!matchFound) {
            throw new Error(`Could not find exact match for edit:\n${edit.oldText}`)
          }
        }
    
        // If no edits were applied, return early
        if (!appliedAnyEdit) {
          return 'No changes made - all edit patterns were empty or not found'
        }
    
        // Generate diff
        const diff = createUnifiedDiff(content, modifiedContent, validPath)
    
        // Write file if not a dry run
        if (!args.dryRun) {
          await fs.writeFile(validPath, modifiedContent, 'utf-8')
          await logger.debug(`Successfully edited file: ${validPath}`)
        }
    
        endMetric()
        return diff
      } catch (error) {
        metrics.recordError('edit_file')
        throw error
      }
    }
  • Zod schemas defining EditOperation (single replacement) and EditFileArgsSchema (full input: path, array of edits, dryRun flag).
    export const EditOperation = z.object({
      oldText: z.string().describe('Text to search for - must match exactly'),
      newText: z.string().describe('Text to replace with'),
    })
    
    /**
     * Schema for edit_file arguments
     */
    export const EditFileArgsSchema = z.object({
      path: z.string().describe('Path to the file to edit'),
      edits: z.array(EditOperation).describe('List of edit operations to perform'),
      dryRun: z.boolean().default(false).describe('Preview changes using git-style diff format'),
    })
  • src/index.ts:263-268 (registration)
    Tool registration in the list_tools handler: defines name 'edit_file', description, and converts EditFileArgsSchema to JSON schema for MCP protocol.
    name: 'edit_file',
    description:
      'Make line-based edits to a text file. Each edit replaces exact line sequences ' +
      'with new content. Returns a git-style diff showing the changes made. ' +
      'Only works within allowed directories.',
    inputSchema: zodToJsonSchema(EditFileArgsSchema) as ToolInput,
  • Dispatch handler case in main CallToolRequest handler: parses arguments with EditFileArgsSchema and invokes editFile function.
    case 'edit_file': {
      const parsed = EditFileArgsSchema.safeParse(a)
      if (!parsed.success) {
        throw new FileSystemError(`Invalid arguments for ${name}`, 'INVALID_ARGS', undefined, {
          errors: parsed.error.format(),
        })
      }
    
      const result = await editFile(parsed.data, config)
    
      endMetric()
      return {
        content: [{ type: 'text', text: result }],
      }
    }
  • createUnifiedDiff helper used by editFile to generate git-style unified diff wrapped in markdown code block.
    function createUnifiedDiff(
      originalContent: string,
      modifiedContent: string,
      filePath: string
    ): string {
      const diff = createTwoFilesPatch(
        filePath,
        filePath,
        originalContent,
        modifiedContent,
        'Original',
        'Modified'
      )
    
      // Find enough backticks to safely wrap the diff
      let numBackticks = 3
      while (diff.includes('`'.repeat(numBackticks))) {
        numBackticks++
      }
    
      return `${'`'.repeat(numBackticks)}diff\n${diff}${'`'.repeat(numBackticks)}\n\n`
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the line-based exact-match replacement mechanism, the git-style diff return format, and the directory restriction. However, it doesn't mention error conditions (e.g., file not found, permission issues), whether edits are atomic, or what happens with overlapping edits.

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?

Three tightly focused sentences with zero waste: first states core functionality, second clarifies the edit mechanism, third covers output and constraints. Every sentence adds essential information, and the description is appropriately sized for a tool with 3 parameters.

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

Completeness3/5

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

For a mutation tool with no annotations and no output schema, the description provides adequate but incomplete context. It covers the what (line-based edits), how (exact sequence replacement), and constraints (allowed directories), but lacks details about error handling, atomicity guarantees, or the exact structure of the returned diff. The absence of output schema increases the need for more behavioral detail.

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 the schema already fully documents all three parameters. The description adds no additional parameter semantics beyond what's in the schema descriptions. The baseline score of 3 reflects adequate coverage through the schema alone.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Make line-based edits'), the target resource ('to a text file'), and the mechanism ('Each edit replaces exact line sequences with new content'). It distinguishes itself from sibling tools like 'write_file' by focusing on in-place modifications rather than creating/overwriting entire files.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context through 'Only works within allowed directories' and the mention of git-style diff output, but doesn't explicitly state when to use this vs. alternatives like 'write_file' for full file replacement or 'bash_execute' for scripted edits. No explicit exclusions or named alternatives are provided.

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

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/A-Niranjan/mcp-filesystem'

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