Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

write_file

Save or append content to a file by specifying its path and write mode using the Terminal Controller for MCP. Ideal for structured file updates or data logging tasks.

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
contentYes
modeNooverwrite
pathYes

Implementation Reference

  • The handler function for the 'write_file' tool. This async function writes content to a specified file path, handling overwrite/append modes, automatic directory creation, JSON serialization for complex content, and various error cases. It is registered as an MCP tool via the @mcp.tool() decorator.
    @mcp.tool() 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)}"

Other Tools

Related 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