Skip to main content
Glama

write_file

Write file content with security policy checks, audit logging, and automatic backup to ensure safe file operations.

Instructions

Write full file content with policy checks, logging, and backup support.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
contentYes
ctxNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The write_file function: the actual handler that writes file content with policy checks, logging, backup support, and Script Sentinel scanning.
    def write_file(path: str, content: str, ctx: Context | None = None) -> str:
        """Write full file content with policy checks, logging, and backup support."""
        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="write_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("write_file", result, path=path)
            append_log_entry(log_entry)
            if not result.allowed:
                return f"[POLICY BLOCK] {result.reason}"
    
            backup_location = None
            backup_enabled = bool(POLICY.get("audit", {}).get("backup_enabled", True))
            if backup_enabled and os.path.exists(path):
                backup_location = backup_paths([path])
                if backup_location:
                    append_log_entry(
                        {
                            **log_entry,
                            "source": "mcp-server",
                            "backup_location": backup_location,
                            "event": "backup_created",
                        }
                    )
    
            try:
                with open(path, "w") as f:
                    f.write(content)
            except OSError as e:
                return f"Error writing file: {e}"
    
            sentinel_scan = script_sentinel.scan_and_record_write(path, content, 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 wrote {len(content)} characters to {path}"
            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-31 (registration)
    Registration: write_file is imported from tools and registered as an MCP tool via mcp.tool()(tool) in the server loop.
    for tool in [
        server_info,
        restore_backup,
        execute_command,
        read_file,
        write_file,
        edit_file,
        delete_file,
        list_directory,
    ]:
        mcp.tool()(tool)
  • Re-export: write_file is re-exported from src/tools/__init__.py so it can be imported cleanly in server.py.
    from .command_tools import execute_command, server_info
    from .file_tools import delete_file, edit_file, list_directory, read_file, write_file
    from .restore_tools import restore_backup
    
    __all__ = [
        "server_info",
        "execute_command",
        "read_file",
        "write_file",
        "edit_file",
        "delete_file",
        "list_directory",
        "restore_backup",
    ]
  • No explicit schema file; write_file uses inline Python type hints (path: str, content: str, ctx) as implicit schema via FastMCP introspection.
    """Thin MCP entrypoint that wires tool handlers from modular components."""
    
    from mcp.server.fastmcp import FastMCP
    
    import approvals
    from tools import (
        delete_file,
        edit_file,
        execute_command,
        list_directory,
        read_file,
        restore_backup,
        server_info,
        write_file,
    )
    
    approvals.init_approval_store()
    
    mcp = FastMCP("ai-runtime-guard")
    
    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()
  • src/airg_hook.py:11-16 (registration)
    Hook redirect: the Write native tool redirects to mcp__ai-runtime-guard__write_file in the AIRG hook.
    REDIRECTS = {
        "Bash": "mcp__ai-runtime-guard__execute_command",
        "Shell": "mcp__ai-runtime-guard__execute_command",
        "Write": "mcp__ai-runtime-guard__write_file",
        "Edit": "mcp__ai-runtime-guard__edit_file",
        "MultiEdit": "mcp__ai-runtime-guard__edit_file",
Behavior2/5

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

No annotations are provided, so the description must convey behavioral traits. It mentions 'policy checks, logging, and backup support' but does not detail authorization requirements, file overwrite behavior, backup creation details, or size limits.

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, front-loaded sentence with no extraneous information. Every word earns its place, conveying the core action and key features efficiently.

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 three parameters (two required) and existing sibling tools like 'edit_file', the description lacks crucial details: how overwriting works, error conditions, backup behavior, and differentiation from similar tools. Although an output schema exists, the description does not supplement it.

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

Parameters2/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 minimal parameter semantics. 'content' is implied as the full text to write, but 'path' and 'ctx' are not described. No parameter definitions are provided in the description.

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 'Write full file content', identifying the verb and resource. It adds 'with policy checks, logging, and backup support', which hints at additional capabilities. However, it does not explicitly differentiate from the sibling tool 'edit_file', which might handle partial updates.

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?

There is no guidance on when to use this tool versus alternatives like 'edit_file' or 'delete_file'. The description implies full content overwriting but lacks explicit context or exclusions.

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