write_file
Create or overwrite files on the MCP Filesystem Server by specifying path, content, encoding, and parent directory creation options.
Instructions
Create a new file or overwrite an existing file with new content.
Args:
path: Path to write to
content: Content to write
encoding: File encoding (default: utf-8)
create_dirs: Whether to create parent directories if they don't exist
ctx: MCP context
Returns:
Success or error message
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| content | Yes | ||
| create_dirs | No | ||
| encoding | No | utf-8 | |
| path | Yes |
Implementation Reference
- mcp_filesystem/server.py:144-170 (handler)MCP tool handler and registration for 'write_file'. Decorated with @mcp.tool(), defines input schema via args/docstring, handles errors, and delegates to FileOperations.write_file.@mcp.tool() async def write_file( path: str, content: str, ctx: Context, encoding: str = "utf-8", create_dirs: bool = False, ) -> str: """Create a new file or overwrite an existing file with new content. Args: path: Path to write to content: Content to write encoding: File encoding (default: utf-8) create_dirs: Whether to create parent directories if they don't exist ctx: MCP context Returns: Success or error message """ try: components = get_components() await components["operations"].write_file(path, content, encoding, create_dirs) return f"Successfully wrote to {path}" except Exception as e: return f"Error writing file: {str(e)}"
- mcp_filesystem/operations.py:161-205 (helper)Core helper implementation of write_file in FileOperations class. Validates path security, optionally creates parent directories, and writes content to file using anyio for async I/O.async def write_file( self, path: Union[str, Path], content: Union[str, bytes], encoding: str = "utf-8", create_dirs: bool = False, ) -> None: """Write to a file. Args: path: Path to the file content: Content to write (string or bytes) encoding: Text encoding for string content create_dirs: Whether to create parent directories if they don't exist Raises: ValueError: If path is outside allowed directories PermissionError: If file cannot be written """ abs_path, allowed = await self.validator.validate_path(path) if not allowed: raise ValueError(f"Path outside allowed directories: {path}") # Create parent directories if requested if create_dirs: parent_dir = abs_path.parent if not parent_dir.exists(): try: await anyio.to_thread.run_sync( partial(parent_dir.mkdir, parents=True) ) except (PermissionError, FileNotFoundError) as e: raise ValueError(f"Cannot create parent directories: {e}") # Write content try: if isinstance(content, str): await anyio.to_thread.run_sync( partial(abs_path.write_text, content, encoding=encoding) ) else: await anyio.to_thread.run_sync(partial(abs_path.write_bytes, content)) except PermissionError as e: raise ValueError(f"Cannot write to file: {e}")