Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

write_file

Write content to files using specified paths and modes (overwrite or append) for file system operations within the Terminal Controller MCP server.

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 handler function for the 'write_file' tool. It serializes non-string content to JSON, determines file open mode based on 'overwrite' or 'append', ensures directories exist, writes the content with UTF-8 encoding, verifies the file was created, and returns a status message with file size or error details.
    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 registers the write_file function as an available MCP tool, automatically generating schema from type hints and docstring.
    @mcp.tool()
  • Input schema defined by function parameters (path: str required, content: str required, mode: str optional default 'overwrite') and docstring. Output is str describing the operation result.
    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
        """

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