How DOCX Support Works for Word Document Editing with Surgical XML Editing in Desktop Commander MCP

Desktop Commander MCP enables precise Word document editing by treating DOCX files as ZIP archives containing XML parts, allowing surgical modifications through pretty-printed XML fragments using the DocxFileHandler class.

Desktop Commander MCP, developed by wonderwhy-er, provides robust DOCX support for Word document editing through direct XML manipulation rather than simple text extraction. Unlike conventional tools that flatten document structure, this system parses the underlying ZIP archive of .docx files to enable surgical editing at the XML level. The implementation centers on the DocxFileHandler class located in src/utils/files/docx.ts, which orchestrates reading, writing, and precise modification operations while preserving document integrity and formatting.

Core Architecture and Registration

The DocxFileHandler Implementation

The DocxFileHandler class in src/utils/files/docx.ts implements three primary file operations: read, write, and edit. This handler treats DOCX files as ZIP archives containing XML parts within the word/ directory, specifically targeting word/document.xml along with headers and footers. By operating directly on these WordprocessingML components rather than rendered text, the system maintains complete control over document structure, styles, and relationships.

Factory Pattern and Capability Declaration

The generic file-handler factory in src/utils/files/factory.ts lazily instantiates DocxFileHandler singletons for any path ending in .docx. This registration ensures that all DOCX operations route through the specialized handler rather than generic text processors. Additionally, the plugin.yaml file declares the docx capability and the docx-support feature flag that enables this functionality throughout the system.

Reading DOCX Files: Dual Mode Architecture

The reading implementation supports two distinct modes depending on the offset parameter, enabling both high-level inspection and low-level surgical access.

Human-Readable Outline Mode (offset = 0)

When invoked with default parameters (offset = 0), the handler returns a structured outline of the document by parsing word/document.xml. It extracts top-level elements including w:p paragraphs, w:tbl tables, and other WordprocessingML tags, presenting each with style attributes, text fragments, and raw XML previews. The output includes header/footer snippets and a summary indicating total XML lines and file size, providing quick document navigation without exposing full markup complexity.

Surgical XML Mode (offset > 0)

Supplying a non-zero offset (or explicit length) triggers raw XML pagination, returning pretty-printed XML segments line-by-line. This mode displays the literal WordprocessingML markup—such as <w:t> text runs and <w:pPr> paragraph properties—enabling precise identification of targets for surgical editing. The pretty-printed format ensures human readability while maintaining the exact structural integrity required for subsequent modification operations.

Surgical XML Editing Workflow

The edit_block tool enables precise modifications through a validated literal replacement process that preserves all unrelated document content.

The workflow begins with retrieving the target XML fragment using read_file with a specific offset to obtain pretty-printed markup. Users then invoke edit_block with the file_path, old_string containing the exact XML fragment (e.g., <w:t>Q1 Revenue</w:t>), new_string with the replacement markup, and expected_replacements to validate occurrence counts.

Internally, DocxFileHandler.editRange loads the ZIP archive, pretty-prints the target XML part, validates that the search string occurs exactly the expected number of times, performs the literal find-replace operation, compacts the XML back to single-line format, and repacks the ZIP. This ensures that only the specified XML nodes change while surrounding formatting, relationships, and binary content remain untouched.

Creating Word Documents from Scratch

The write operation generates valid DOCX files from plain text or Markdown-style input. Lines prefixed with # convert to heading styles (Heading1, Heading2, etc.), while regular lines become <w:p> paragraphs. The handler constructs a minimal ZIP archive including [Content_Types].xml, relationship files (_rels/.rels), and style definitions, producing standards-compliant Word documents programmatically without requiring Microsoft Office installation.

Practical Usage Examples

// Get human-readable outline of a DOCX (offset = 0)
await client.callTool('read_file', {
  path: '/home/user/report.docx',
});
/* Returns:
   [0] w:p style="Heading1"
   Text: Executive Summary
   Raw XML: 1234 lines, 45.2KB.
*/

// Retrieve pretty-printed XML for surgical editing
await client.callTool('read_file', {
  path: '/home/user/report.docx',
  offset: 200,
  length: 20,
});
// Returns lines 200-220 of word/document.xml in pretty-printed format

// Perform surgical XML replacement
await client.callTool('edit_block', {
  file_path: '/home/user/report.docx',
  old_string: '<w:t>Q1 Revenue</w:t>',
  new_string: '<w:t>Q1 Revenue – Updated</w:t>',
  expected_replacements: 1,
});

// Create new DOCX from Markdown-style content
await client.callTool('write_file', {
  path: '/home/user/new-report.docx',
  content: `

# Executive Summary

This report covers Q1 performance.

## Highlights

- Revenue grew 12%
`,
  mode: 'rewrite',
});

Document Metadata and Statistics

The getInfo method provides comprehensive document intelligence without full content extraction. It reports word counts, paragraph tallies, table and image quantities, and basic file statistics. This metadata retrieval enables automated document analysis workflows and precondition checks before initiating surgical editing operations.

Summary

  • Desktop Commander MCP implements DOCX support through the DocxFileHandler class in src/utils/files/docx.ts, treating Word documents as ZIP archives containing XML parts like word/document.xml.
  • Dual-mode reading provides human-readable outlines when offset = 0 or pretty-printed surgical XML when offset > 0 for precise targeting.
  • The edit_block tool performs validated literal replacements on XML fragments, compacting and repacking the ZIP while preserving document structure and relationships.
  • Document creation supports Markdown-to-DOCX conversion with automatic heading style mapping and complete ZIP archive generation.
  • Factory registration in src/utils/files/factory.ts ensures transparent routing of all .docx operations to the specialized handler.

Frequently Asked Questions

What is surgical XML editing in Desktop Commander MCP?

Surgical XML editing refers to the precise modification of specific XML fragments within a DOCX file's internal ZIP structure. Rather than replacing entire documents, the system allows users to target individual WordprocessingML elements—such as specific <w:t> text runs or <w:pPr> paragraph properties—using pretty-printed XML coordinates. This ensures minimal disruption to surrounding content, formatting, and document relationships.

How does the DocxFileHandler handle read operations differently based on offset values?

When the offset parameter equals zero, the handler parses word/document.xml to generate a human-readable outline showing paragraphs, tables, and styles with summaries. When offset is greater than zero, it returns pretty-printed XML lines starting at the specified position, exposing the raw WordprocessingML markup necessary for surgical editing via the edit_block tool.

Can Desktop Commander MCP create new Word documents from scratch?

Yes, the write_file tool with .docx extension supports creating new Word documents from plain text or Markdown-formatted content. The system automatically converts Markdown headings (lines starting with #) to appropriate Word styles (Heading1, Heading2, etc.) and generates a complete ZIP archive with necessary XML relationship files and content type definitions.

What validation occurs during DOCX editing operations?

The edit_block implementation validates that the old_string occurs exactly the number of times specified by expected_replacements before performing any modifications. After validation, DocxFileHandler.editRange pretty-prints the target XML part, executes the literal find-replace operation, compacts the XML back to the required single-line format, and repacks the ZIP archive to ensure structural validity according to the DesktopCommanderMCP source code.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →