Skip to main content
Glama
safurrier

MCP Filesystem Server

edit_file

Modify text files by applying line-based changes to specified content, with options to preview edits before saving.

Instructions

Make line-based edits to a text file.

Args:
    path: Path to the file
    edits: List of {oldText, newText} dictionaries
    encoding: Text encoding (default: utf-8)
    dry_run: If True, return diff but don't modify file
    ctx: MCP context

Returns:
    Git-style diff showing changes

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
editsYes
encodingNoutf-8
dry_runNo

Implementation Reference

  • Registration and handler for the 'edit_file' MCP tool. This thin wrapper validates the call and delegates to the FileOperations.edit_file method.
    @mcp.tool()
    async def edit_file(
        path: str,
        edits: List[Dict[str, str]],
        ctx: Context,
        encoding: str = "utf-8",
        dry_run: bool = False,
    ) -> str:
        """Make line-based edits to a text file.
    
        Args:
            path: Path to the file
            edits: List of {oldText, newText} dictionaries
            encoding: Text encoding (default: utf-8)
            dry_run: If True, return diff but don't modify file
            ctx: MCP context
    
        Returns:
            Git-style diff showing changes
        """
        try:
            components = get_components()
            return await components["operations"].edit_file(path, edits, encoding, dry_run)
        except Exception as e:
            return f"Error editing file: {str(e)}"
  • Core handler logic for edit_file tool. Performs string-based find-and-replace edits on file content, generates git-style unified diff output, supports dry-run mode, and handles file I/O with path validation.
    async def edit_file(
        self,
        path: Union[str, Path],
        edits: List[Dict[str, str]],
        encoding: str = "utf-8",
        dry_run: bool = False,
    ) -> str:
        """Edit a text file by replacing line sequences.
    
        Args:
            path: Path to the file
            edits: List of {oldText, newText} dictionaries
            encoding: Text encoding (default: utf-8)
            dry_run: If True, return diff but don't modify file
    
        Returns:
            Git-style diff showing changes
    
        Raises:
            ValueError: If path is outside allowed directories
            FileNotFoundError: If file does not exist
        """
        abs_path, allowed = await self.validator.validate_path(path)
        if not allowed:
            raise ValueError(f"Path outside allowed directories: {path}")
    
        try:
            # Read the file content
            current_content = await anyio.to_thread.run_sync(
                abs_path.read_text, encoding
            )
            new_content = current_content
    
            # Create a diff-style output
            diff_lines = [f"--- {path}", f"+++ {path}"]
    
            # Apply each edit
            for edit in edits:
                if "oldText" not in edit or "newText" not in edit:
                    continue
    
                old_text = edit["oldText"]
                new_text = edit["newText"]
    
                if old_text in new_content:
                    # Add to diff
                    context = new_content.split(old_text, 1)
                    line_number = context[0].count("\n") + 1
                    old_lines = old_text.count("\n") + 1
                    new_lines = new_text.count("\n") + 1
    
                    diff_lines.append(
                        f"@@ -{line_number},{old_lines} +{line_number},{new_lines} @@"
                    )
                    for line in old_text.splitlines():
                        diff_lines.append(f"-{line}")
                    for line in new_text.splitlines():
                        diff_lines.append(f"+{line}")
    
                    # Replace the text
                    new_content = new_content.replace(old_text, new_text, 1)
    
            # If this is not a dry run, write the changes
            if not dry_run and new_content != current_content:
                await anyio.to_thread.run_sync(
                    abs_path.write_text, new_content, encoding
                )
    
            if new_content == current_content:
                return "No changes made"
    
            return "\n".join(diff_lines)
    
        except FileNotFoundError:
            raise FileNotFoundError(f"File not found: {path}")
        except PermissionError:
            raise ValueError(f"Permission denied: {path}")
        except UnicodeDecodeError:
            raise ValueError(f"Cannot decode file as {encoding}: {path}")
  • Input schema defined by function signature: path (str), edits (List[Dict[str,str]] with oldText/newText), encoding (str), dry_run (bool). Output: str (diff).
    async def edit_file(
        path: str,
        edits: List[Dict[str, str]],
        ctx: Context,
        encoding: str = "utf-8",
        dry_run: bool = False,
    ) -> str:
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 of behavioral disclosure. It reveals that the tool can perform dry runs and returns Git-style diffs, which are valuable behavioral traits. However, it doesn't mention error conditions, file locking behavior, permission requirements, or what happens with non-existent files - significant gaps 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 perfectly structured and front-loaded: the first sentence states the core purpose, followed by clearly labeled Args and Returns sections. Every sentence earns its place - no redundant information, no wasted words. The formatting with clear section headers enhances readability.

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 file mutation tool with 4 parameters, 0% schema coverage, no annotations, and no output schema, the description does a decent job but has gaps. It explains parameters well and mentions the return format, but doesn't cover error handling, permission requirements, or edge cases. Given the complexity of file editing operations, more behavioral context would be helpful.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description compensates well by explaining all 4 parameters in the Args section. It clarifies that 'edits' expects dictionaries with 'oldText' and 'newText' keys, specifies the default for 'encoding' and 'dry_run', and explains what 'dry_run' does. The only gap is not explaining the 'ctx' parameter's purpose.

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 tool's purpose with specific verb ('Make line-based edits') and resource ('to a text file'), distinguishing it from siblings like 'edit_file_at_line' (which implies different editing granularity) and 'write_file' (which likely overwrites entire files). The phrase 'line-based edits' provides precise scope information.

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

Usage Guidelines4/5

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

The description provides clear context about when to use this tool (for making line-based edits to text files) but doesn't explicitly state when NOT to use it or name specific alternatives. It distinguishes from 'edit_file_at_line' by implying different editing approaches, but doesn't provide explicit guidance on choosing between them.

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

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