Write content to file Args: file_path: File path, relative to workspace content: Content to write to file create_dirs: Whether to create directories if they don't exist create_backup: Whether to create backup file if file already exists Returns:
(
file_path: str, content: str, create_dirs: bool = True, create_backup: bool = False
)
| 401 | |
| 402 | @mcp.tool() |
| 403 | async def write_file( |
| 404 | file_path: str, content: str, create_dirs: bool = True, create_backup: bool = False |
| 405 | ) -> str: |
| 406 | """ |
| 407 | Write content to file |
| 408 | |
| 409 | Args: |
| 410 | file_path: File path, relative to workspace |
| 411 | content: Content to write to file |
| 412 | create_dirs: Whether to create directories if they don't exist |
| 413 | create_backup: Whether to create backup file if file already exists |
| 414 | |
| 415 | Returns: |
| 416 | JSON string of operation result |
| 417 | """ |
| 418 | try: |
| 419 | full_path = validate_path(file_path) |
| 420 | |
| 421 | # Create directories (if needed) |
| 422 | if create_dirs: |
| 423 | full_path.parent.mkdir(parents=True, exist_ok=True) |
| 424 | |
| 425 | # Backup existing file (only when explicitly requested) |
| 426 | backup_created = False |
| 427 | if full_path.exists() and create_backup: |
| 428 | backup_path = full_path.with_suffix(full_path.suffix + ".backup") |
| 429 | shutil.copy2(full_path, backup_path) |
| 430 | backup_created = True |
| 431 | |
| 432 | # Write file |
| 433 | with open(full_path, "w", encoding="utf-8") as f: |
| 434 | f.write(content) |
| 435 | |
| 436 | # Update current file record |
| 437 | CURRENT_FILES[file_path] = { |
| 438 | "last_modified": datetime.now().isoformat(), |
| 439 | "size_bytes": len(content.encode("utf-8")), |
| 440 | "lines": len(content.split("\n")), |
| 441 | } |
| 442 | |
| 443 | result = { |
| 444 | "status": "success", |
| 445 | "message": f"File written successfully: {file_path}", |
| 446 | "file_path": file_path, |
| 447 | "size_bytes": len(content.encode("utf-8")), |
| 448 | "lines_written": len(content.split("\n")), |
| 449 | "backup_created": backup_created, |
| 450 | } |
| 451 | |
| 452 | log_operation( |
| 453 | "write_file", |
| 454 | { |
| 455 | "file_path": file_path, |
| 456 | "size_bytes": len(content.encode("utf-8")), |
| 457 | "lines": len(content.split("\n")), |
| 458 | "backup_created": backup_created, |
| 459 | }, |
| 460 | ) |
nothing calls this directly
no test coverage detected