write_file
Write content to files in Python environments. Specify file path, content, and whether to overwrite existing files.
Instructions
Write content to a file.
Args:
file_path: Path to the file to write
content: Content to write
overwrite: Whether to overwrite if exists
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| file_path | Yes | ||
| content | Yes | ||
| overwrite | No |
Implementation Reference
- mcp_python_interpreter/server.py:767-803 (handler)The main handler function for the 'write_file' tool, decorated with @mcp.tool() for registration in the MCP framework. It handles writing string content to a file path relative to the working directory, with security checks, overwrite option, directory creation, and detailed success/error responses.@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)}"