Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

write_file

Write or append content to a specified file. Supports overwrite and append modes for flexible file updates.

Instructions

Write content to a file

Args:
    path: Path to the file
    content: Content to write (string or JSON object)
    mode: Write mode ('overwrite' or 'append')

Returns:
    Operation result information

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
contentYes
modeNooverwrite

Implementation Reference

  • The actual handler function for the 'write_file' tool. Writes content to a file with support for 'overwrite' and 'append' modes, handles non-string content via JSON serialization, creates directories if needed, and verifies write success.
    async def write_file(path: str, content: str, mode: str = "overwrite") -> str:
        """
        Write content to a file
        
        Args:
            path: Path to the file
            content: Content to write (string or JSON object)
            mode: Write mode ('overwrite' or 'append')
        
        Returns:
            Operation result information
        """
        try:
            # Handle different content types
            if not isinstance(content, str):
                try:
                    import json
                    # Advanced JSON serialization with better handling of complex objects
                    content = json.dumps(content, 
                                        indent=4, 
                                        sort_keys=False, 
                                        ensure_ascii=False, 
                                        default=lambda obj: str(obj) if hasattr(obj, '__dict__') else repr(obj))
                except Exception as e:
                    # Try a more aggressive approach if standard serialization fails
                    try:
                        # Convert object to dictionary first if it has __dict__
                        if hasattr(content, '__dict__'):
                            import json
                            content = json.dumps(content.__dict__, 
                                               indent=4, 
                                               sort_keys=False, 
                                               ensure_ascii=False)
                        else:
                            # Last resort: convert to string representation
                            content = str(content)
                    except Exception as inner_e:
                        return f"Error: Unable to convert complex object to writable string: {str(e)}, then tried alternative method and got: {str(inner_e)}"
            
            # Choose file mode based on the specified writing mode
            file_mode = "w" if mode.lower() == "overwrite" else "a"
            
            # Ensure content ends with a newline if it doesn't already
            if content and not content.endswith('\n'):
                content += '\n'
            
            # Ensure directory exists
            directory = os.path.dirname(os.path.abspath(path))
            if directory and not os.path.exists(directory):
                os.makedirs(directory, exist_ok=True)
                
            with open(path, file_mode, encoding="utf-8") as file:
                file.write(content)
            
            # Verify the write operation was successful
            if os.path.exists(path):
                file_size = os.path.getsize(path)
                return f"Successfully wrote {file_size} bytes to '{path}' in {mode} mode."
            else:
                return f"Write operation completed, but unable to verify file exists at '{path}'."
        
        except FileNotFoundError:
            return f"Error: The directory in path '{path}' does not exist and could not be created."
        except PermissionError:
            return f"Error: No permission to write to file '{path}'."
        except Exception as e:
            return f"Error writing to file: {str(e)}"
  • The @mcp.tool() decorator that registers the write_file function as an MCP tool on the FastMCP server instance.
    @mcp.tool()
Behavior2/5

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

With no annotations, the description must disclose behaviors but only says 'Write content to a file' and mentions modes. It fails to address what happens if the file doesn't exist, whether it truncates, encoding, or user permissions. This lack of context for a mutation tool is a significant gap.

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 extremely concise, using a docstring format with clear sections. It front-loads the one-line summary, and every part adds value without repetition or fluff.

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 tool with 3 parameters and no output schema, the description covers the basics but lacks details on error conditions, file creation behavior, and return value specifics. It is adequate but not fully complete.

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?

Schema description coverage is 0%, so the description provides necessary semantics for parameters: 'Path to the file', 'Content to write', and 'Write mode'. It adds value over bare titles, though could clarify content format and path constraints.

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 'Write content to a file' clearly states the action and resource, distinguishing it from siblings like read_file or delete_file_content. The docstring provides specific parameter explanations, confirming the tool's purpose.

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 given on when to use this tool vs alternatives like update_file_content or insert_file_content. The description does not explain the difference between overwrite and append modes or when each is appropriate.

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/GongRzhe/terminal-controller-mcp'

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