# How to Write to a File in Append or Rewrite Mode with Desktop Commander MCP

> Learn how to write to a file in append or rewrite mode with Desktop Commander MCP using the versatile write_file tool. Safely overwrite or add content to your files.

- Repository: [Eduard Ruzga/DesktopCommanderMCP](https://github.com/wonderwhy-er/DesktopCommanderMCP)
- Tags: how-to-guide
- Published: 2026-07-15

---

**Desktop Commander MCP provides a unified `write_file` tool that supports both `'rewrite'` (default) and `'append'` modes, with built-in safety guards to prevent accidental data loss when overwriting existing files.**

Desktop Commander MCP is a Model Context Protocol (MCP) server that enables AI assistants to interact with the local filesystem through a secure, structured API. When you need to programmatically create new files or modify existing ones, the server offers precise control over write behaviors through explicit mode specifications. Understanding these modes is essential for preventing data corruption and ensuring content is inserted correctly according to your workflow requirements.

## Core File Write Architecture

The file writing system in Desktop Commander MCP operates through a layered architecture that separates low-level I/O operations from the LLM-facing command interface.

### The writeFile Implementation

At the foundation lies the **`writeFile`** function defined in [`src/tools/filesystem.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/tools/filesystem.ts) (lines 638–661). This core routine accepts three key parameters: the target path, the content string, and a **`mode`** argument that accepts either `'rewrite'` or `'append'`. The function validates the path, handles telemetry logging, and delegates the actual write operation to a file-type-specific handler determined by the extension and MIME type.

### The LLM-Facing Handler

The tool exposed to language models is **`write_file`**, implemented through **`handleWriteFile`** in [`src/handlers/filesystem-handlers.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/handlers/filesystem-handlers.ts) (lines 5–51). This handler parses incoming JSON arguments, validates the optional `mode` flag, enforces configurable line-count limits for safety, and invokes the core `writeFile` routine. It serves as the gatekeeper between AI agents and the filesystem, ensuring all writes are explicit and authorized.

## Understanding Write Modes

Desktop Commander MCP implements two distinct write behaviors that control how new content interacts with existing file data.

### Rewrite Mode (Default)

When **`mode`** is set to `'rewrite'` or omitted entirely, the server replaces the entire contents of the target file with the supplied data. Behind the scenes, the `TextFileHandler` (located in [`src/utils/files/text.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/utils/files/text.ts)) invokes **`fs.writeFile`** with the `w` flag, truncating any existing content. This mode is ideal for generating fresh configuration files, overwriting logs, or creating new documents where previous content is irrelevant.

### Append Mode

When **`mode`** is explicitly set to `'append'`, the server concatenates the new content to the end of the existing file without modifying the original data. The `TextFileHandler` executes **`fs.appendFile`** to preserve the existing bytes and add the new content at the EOF marker. Use this mode for logging applications, adding entries to existing notes, or progressively building data files where history must be maintained.

### Safety Guard Mechanism

If you attempt to write to an existing file that already contains data without specifying a `mode`, the system triggers a protective error. The `handleWriteFile` logic detects this ambiguous state and rejects the request, prompting you to explicitly choose either `"mode": "append"` or `"mode": "rewrite"`. This guard prevents AI agents from accidentally overwriting critical system files or user data through implicit defaults.

## Practical Implementation Examples

The following examples demonstrate how to invoke write operations through both direct API calls and LLM tool schemas.

### Rewriting a File Completely

```typescript
await writeFile('/Users/alice/config.json', '{"setting": "value"}');

```

Because `mode` defaults to `'rewrite'`, this call replaces any existing content in [`config.json`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/config.json) with the new JSON object. If the file did not exist, it is created atomically.

### Appending to an Existing Log

```typescript
await writeFile('/var/log/app.log', '\n[2024-01-15] New event occurred', 'append');

```

This invocation adds a new log line to the end of `app.log` while preserving all previous entries. The newline character ensures proper formatting when viewing the file sequentially.

### Using the LLM Tool Interface

When interacting through the MCP protocol, structure your tool call as follows:

```json
{
  "tool": "write_file",
  "args": {
    "path": "/Users/alice/notes.txt",
    "content": "Meeting notes from today...",
    "mode": "append"
  }
}

```

The `handleWriteFile` routine parses this JSON, verifies the path against allowed directories, and routes the request to `writeFile` with the specified `'append'` flag.

### Triggering the Safety Guard

Attempting to write without a mode to an existing file produces a protective error:

```json
{
  "tool": "write_file",
  "args": { 
    "path": "/Users/alice/important.txt", 
    "content": "New content" 
  }
}

```

If [`important.txt`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/important.txt) already contains data, the server responds with an error message requiring you to specify `"mode": "rewrite"` to overwrite or `"mode": "append"` to extend the file, ensuring intentional data modification.

## Summary

- **Core Function**: The `writeFile` function in [`src/tools/filesystem.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/tools/filesystem.ts) handles both rewrite and append operations through a unified API.
- **LLM Interface**: The `write_file` tool in [`src/handlers/filesystem-handlers.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/handlers/filesystem-handlers.ts) provides the external entry point with argument validation.
- **Mode Options**: Use `'rewrite'` (default) to replace file contents or `'append'` to add to existing data.
- **Safety Feature**: The system requires explicit mode selection when overwriting non-empty files to prevent accidental data loss.
- **Implementation Detail**: Text files are processed by `TextFileHandler` using Node.js `fs.writeFile` for rewrites and `fs.appendFile` for appends.

## Frequently Asked Questions

### What happens if I omit the mode parameter when writing to a file?

If the target file is empty or does not exist, the write proceeds using the default `'rewrite'` mode. However, if the file already contains data, Desktop Commander MCP rejects the operation and returns an error requesting explicit mode specification. This safety mechanism prevents unintended overwrites of existing content.

### Can I use append mode with binary files or only text files?

While the architecture supports multiple file types through the handler factory in [`src/utils/files/factory.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/utils/files/factory.ts), the append behavior is primarily implemented in `TextFileHandler` at [`src/utils/files/text.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/utils/files/text.ts). Binary file handlers may implement append differently or reject the operation depending on file type constraints, so always verify handler support for non-text formats.

### How does the safety guard determine if a file has existing content?

The `handleWriteFile` routine checks the file size or reads existing content before writing. If any data is detected and no `mode` is specified in the arguments, it halts execution and returns an instructional error. This check occurs before any write lock is acquired, ensuring atomic decision-making without partial writes.

### Is there a performance difference between rewrite and append operations?

Append operations using `fs.appendFile` are generally more efficient for large files because they do not require reading or rewriting existing data blocks to disk; they simply seek to the end-of-file marker and write new bytes. Rewrite operations using `fs.writeFile` truncate and replace the entire file, which consumes more I/O bandwidth for large datasets but ensures cleaner file allocation.