write_file
Create or modify files by writing content to specified paths using a Python-based file management tool. Supports custom encoding and optional overwrite functionality.
Instructions
Write content to a file in the working directory or system-wide if allowed.
Args:
file_path: Path to the file to write (relative to working directory or absolute if system access is enabled)
content: Content to write to the file
overwrite: Whether to overwrite the file if it exists (default: False)
encoding: File encoding (default: utf-8)
Returns:
str: Status message about the file writing operation
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| content | Yes | ||
| encoding | No | utf-8 | |
| file_path | Yes | ||
| overwrite | No |
Implementation Reference
- mcp_python_interpreter/server.py:767-803 (handler)The complete implementation of the 'write_file' tool. Includes registration via @mcp.tool(), inline schema from type annotations and docstring, and the full handler logic that securely writes file content to the working directory with overwrite option, directory creation, and atomic write using fsync.@mcp.tool() def write_file( file_path: str, content: str, overwrite: bool = False ) -> str: """ Write content to a file. Args: file_path: Path to the file to write content: Content to write overwrite: Whether to overwrite if exists """ path = Path(file_path) if path.is_absolute(): if not is_path_allowed(path): return f"Access denied: Can only write files in working directory: {WORKING_DIR}" else: path = WORKING_DIR / path try: if path.exists() and not overwrite: return f"File '{path}' exists. Use overwrite=True to replace." path.parent.mkdir(parents=True, exist_ok=True) with open(path, 'w', encoding='utf-8') as f: f.write(content) f.flush() os.fsync(f.fileno()) file_size_kb = path.stat().st_size / 1024 return f"Successfully wrote to {path}. Size: {file_size_kb:.2f} KB" except Exception as e: return f"Error writing file: {str(e)}"