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}")
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It mentions the tool can 'overwrite an existing file' which implies destructive behavior, but doesn't disclose critical details like permission requirements, whether overwrites are reversible, error handling for invalid paths, or rate limits. The return value description ('Success or error message') is vague about format.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is efficiently structured with a clear purpose statement followed by well-organized parameter and return value sections. Every sentence adds value without redundancy, and information is front-loaded appropriately.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description provides good parameter semantics but lacks sufficient behavioral context for a destructive file operation. It doesn't explain the return format, error conditions, or security implications, leaving gaps in completeness for a tool that modifies files.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description provides clear semantic explanations for all 4 parameters beyond their schema titles, including default values and purposes (e.g., 'encoding: File encoding (default: utf-8)', 'create_dirs: Whether to create parent directories if they don't exist'). This compensates well for the 0% schema description coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Create a new file or overwrite an existing file') and resource ('file with new content'), distinguishing it from sibling tools like read_file, edit_file, and move_file. It precisely defines the tool's function without being tautological.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for file creation or overwriting but doesn't explicitly state when to use this tool versus alternatives like edit_file or create_directory. No guidance is provided on prerequisites, exclusions, or specific scenarios where this tool is preferred over others.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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