Skip to main content
Glama

edit_file

Apply targeted text replacements to files with automatic backup to prevent data loss.

Instructions

Apply targeted text replacements in an existing file with backups.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
old_textNo
new_textNo
replace_allNo
editsNo
ctxNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler function for the edit_file tool. Applies targeted text replacements (single or batch via 'edits' list) in existing files with policy checks, backup creation, and script-sentinel scanning.
    def edit_file(
        path: str,
        old_text: str = "",
        new_text: str = "",
        replace_all: bool = False,
        edits: list[dict[str, Any]] | None = None,
        ctx: Context | None = None,
    ) -> str:
        """Apply targeted text replacements in an existing file with backups."""
        context_tokens = activate_runtime_context(ctx)
        path = str(pathlib.Path(WORKSPACE_ROOT) / path) if not os.path.isabs(path) else path
    
        try:
            refresh_policy_if_changed()
            path_check = check_path_policy(path, tool="edit_file")
            if path_check:
                result = PolicyResult(allowed=False, reason=path_check[0], decision_tier="blocked", matched_rule=path_check[1])
            else:
                result = PolicyResult(allowed=True, reason="allowed", decision_tier="allowed", matched_rule=None)
    
            log_entry = build_log_entry("edit_file", result, path=path)
            append_log_entry(log_entry)
            if not result.allowed:
                return f"[POLICY BLOCK] {result.reason}"
    
            target = pathlib.Path(path)
            if not target.exists():
                return f"Error: file not found: {path}"
            if not target.is_file():
                return f"Error: '{path}' is not a regular file"
    
            try:
                original = target.read_text(errors="replace")
            except OSError as e:
                return f"Error reading file for edit: {e}"
    
            operations: list[tuple[str, str, bool]] = []
            if edits is not None:
                if not isinstance(edits, list):
                    return "Error: edits must be a list of {old_text, new_text, replace_all?} objects"
                for idx, item in enumerate(edits, start=1):
                    if not isinstance(item, dict):
                        return f"Error: edit #{idx} is not an object"
                    item_old = str(item.get("old_text", ""))
                    item_new = str(item.get("new_text", ""))
                    item_replace_all = bool(item.get("replace_all", False))
                    if not item_old:
                        return f"Error: edit #{idx} has empty old_text"
                    operations.append((item_old, item_new, item_replace_all))
            else:
                if not old_text:
                    return "Error: old_text is required when edits is not provided"
                operations.append((str(old_text), str(new_text), bool(replace_all)))
    
            updated = original
            total_replacements = 0
            for idx, (needle, replacement, replace_everywhere) in enumerate(operations, start=1):
                matches = updated.count(needle)
                if matches == 0:
                    return f"Error: edit #{idx} old_text not found in file"
                if not replace_everywhere and matches > 1:
                    return (
                        f"Error: edit #{idx} old_text matched {matches} times; "
                        "set replace_all=true for this edit to apply all matches"
                    )
                if replace_everywhere:
                    updated = updated.replace(needle, replacement)
                    total_replacements += matches
                else:
                    updated = updated.replace(needle, replacement, 1)
                    total_replacements += 1
    
            if updated == original:
                return f"No changes made to {path}"
    
            backup_location = None
            backup_enabled = bool(POLICY.get("audit", {}).get("backup_enabled", True))
            if backup_enabled:
                backup_location = backup_paths([path])
                if backup_location:
                    append_log_entry(
                        {
                            **log_entry,
                            "source": "mcp-server",
                            "backup_location": backup_location,
                            "event": "backup_created",
                        }
                    )
    
            try:
                target.write_text(updated)
            except OSError as e:
                return f"Error writing edited file: {e}"
    
            sentinel_scan = script_sentinel.scan_and_record_write(path, updated, writer_agent_id=AGENT_ID)
            if sentinel_scan.get("flagged"):
                append_log_entry(
                    {
                        **log_entry,
                        "source": "mcp-server",
                        "event": "script_sentinel_flagged",
                        "content_hash": sentinel_scan.get("content_hash", ""),
                        "matched_signatures": sentinel_scan.get("matched_signatures", []),
                        "script_sentinel_mode": POLICY.get("script_sentinel", {}).get("mode", "match_original"),
                        "script_sentinel_scan_mode": sentinel_scan.get("scan_mode", POLICY.get("script_sentinel", {}).get("scan_mode", "exec_context")),
                    }
                )
    
            msg = (
                f"Successfully edited {path} "
                f"({total_replacements} replacement{'s' if total_replacements != 1 else ''} across {len(operations)} edit operation{'s' if len(operations) != 1 else ''})"
            )
            if backup_location:
                msg += f" (previous version backed up to {backup_location})"
            else:
                msg += " (no content-change backup needed)"
            if sentinel_scan.get("flagged"):
                msg += " (Script Sentinel flagged content)"
            return msg
        finally:
            reset_runtime_context(context_tokens)
  • src/server.py:21-35 (registration)
    MCP server registers edit_file as a tool via mcp.tool()(edit_file) in the tool registration loop.
    for tool in [
        server_info,
        restore_backup,
        execute_command,
        read_file,
        write_file,
        edit_file,
        delete_file,
        list_directory,
    ]:
        mcp.tool()(tool)
    
    
    if __name__ == "__main__":
        mcp.run()
  • Re-exports edit_file from file_tools module so it can be imported by server.py.
    from .file_tools import delete_file, edit_file, list_directory, read_file, write_file
  • Function signature defines the schema: path (str), old_text (str), new_text (str), replace_all (bool), edits (list[dict]), ctx (Context).
    def edit_file(
        path: str,
        old_text: str = "",
        new_text: str = "",
        replace_all: bool = False,
        edits: list[dict[str, Any]] | None = None,
        ctx: Context | None = None,
    ) -> str:
  • Redirect mapping: both 'Edit' and 'MultiEdit' hook into the edit_file tool via 'mcp__ai-runtime-guard__edit_file'.
        "Edit": "mcp__ai-runtime-guard__edit_file",
        "MultiEdit": "mcp__ai-runtime-guard__edit_file",
        "Delete": "mcp__ai-runtime-guard__delete_file",
    }
Behavior2/5

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

No annotations are provided. The description only mentions backups but does not disclose replacement behavior, permissions, or side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness2/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is very short (one sentence) but under-specified given the tool's complexity with 6 parameters.

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?

The description is incomplete, lacking parameter explanations and contextual details despite having an output schema.

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

Parameters1/5

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

Schema description coverage is 0% and the description adds no meaning to any of the 6 parameters, including the required path.

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 does 'targeted text replacements in an existing file' and mentions backups, distinguishing it from write_file and delete_file.

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 on when or when not to use this tool compared to siblings like write_file or delete_file.

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/jimmyracheta/ai-runtime-guard'

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