Skip to main content
Glama
safurrier

MCP Filesystem Server

write_file

Create new files or update existing ones by writing content to specified paths, with options for encoding and directory creation.

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
NameRequiredDescriptionDefault
pathYes
contentYes
encodingNoutf-8
create_dirsNo

Implementation Reference

  • MCP tool handler for 'write_file'. This is the entry point decorated with @mcp.tool() that handles the tool call, gets components, 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)}"
  • Core implementation of file writing logic in the FileOperations class. Validates path security, creates parent directories if specified, and writes content (supports str or bytes).
    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}")

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/safurrier/mcp-filesystem'

If you have feedback or need assistance with the MCP directory API, please join our Discord server