Safe Docx
About
Edit Word (.docx) documents with tracked changes, redlines, and formatting preservation. Built for AI coding agents. Surgical text replacement, comments, footnotes, and document comparison — all local, no cloud upload. MIT licensed.
Details
- Author
- UseJunior
- Downloads
- 536
- Categories
- Productivity, Other, File Management, AI
Jump to
- Deterministic, formatting‑preserving text replacement and paragraph insertion
- Tracked‑changes outputs for human review
- Comment and footnote workflows
- Revision extraction as structured JSON
- TypeScript runtime — no .NET, Python, or LibreOffice required
- Auditable behavior with test evidence and traceability artifacts
Setting up with Highlight
This MCP is not yet compatible with Highlight’s one-click setup. However, you can still use it with Highlight by following these steps:
- Download and install Highlight from highlightai.com/download
- Navigate to the plugins tab and select "Add Custom Plugin"
-
Configure the plugin with the settings below
Plugin Name
Safe DocxCommand (node, npx, python, etc.)Please refer to the README for specific instructions on how to obtain API keys or other required environment variables.
- Enable "Start Automatically" if you want the plugin to start when Highlight launches
From the repository
Install and run via npx -y @usejunior/safe-docx. For MCP clients (Claude Code, Claude Desktop, Gemini CLI, or any stdio‑based MCP client), configure the MCP server with command npx and args ["-y", "@usejunior/safe-docx"]. The server provides typed MCP tools that agents call automatically — no manual integration code needed.
read_file
Read document content (DOCX, ODT, or Google Doc). Output is token-limited (~14k tokens) by default with pagination metadata (has_more, next_offset). Use offset/limit to paginate.
get_document_outline
Get a compact structural map of a document's headings (DOCX only). Each entry is `{paragraph_id, text, level, source}`. Deterministic sources are `word_style`, `list_metadata`, and `outline_level`, selected in that precedence order and included by default. Heuristic sources are `run_in_header`, `title_with_period`, `title_with_colon`, `title_caps_centered`, and `title_bare`; set include_heuristic_headings=true to include them. JSON preserves levels 1-9; Markdown clamps visual ATX depth to 6. Read-only.
grep
Search paragraphs with regex. Use file_path for session-based search, file_paths for stateless multi-file search, or google_doc_id for Google Docs. ODT supported via file_path (single-file) only.
batch_edit
Single-agent front door for applying multiple edit steps (replace_text, insert_paragraph) to a document in one call. Validates all steps first, rejects conflicts before applying anything, then executes valid steps sequentially. Accepts inline steps or a plan_file_path JSON array. Surface: revisionable — every applied step emits native OOXML tracked changes.
replace_text
Replace text in a paragraph by provider paragraph id, preserving formatting where supported. Supports DOCX, ODT, and Google Docs. Surface: revisionable — DOCX edits emit native OOXML tracked changes (w:ins/w:del/w:rPrChange).
insert_paragraph
Insert a paragraph before/after an anchor paragraph by paragraph id. Supports DOCX, ODT, and Google Docs. (ODT paragraph ids are positional and shift after insertion — re-read before further edits.) Surface: revisionable — DOCX insertions emit native OOXML tracked changes.
save
Persist the current in-memory document session. For DOCX: saves clean and/or tracked changes output. For ODT: saves an .odt package. For Google Docs: checkpoint (default) returns revisionId, or snapshot exports as DOCX. Surface: revisionable — the save report lists both the AI revisions applied and a non-revision change manifest of any package-level mutations (comment/footnote side parts, relationships) that have no tracked-change wrapper.
export
Export a document to a portable rendering (Markdown, semantic HTML, or plain text). Writes an output file (default: source path with the format extension, e.g. .md, .html, or .txt) and returns its path, byte count, and the rendered content (under `content`). Intentionally lossy (no round-trip); HTML is the semantic tier, not pixel-faithful. DOCX only — Google Docs is not supported.
convert_to_odt
Convert a DOCX document to OpenDocument Text (.odt) using the native model-to-model converter (no LibreOffice involved). Writes the .odt (default: source path with the .odt extension), validates ODF packaging safety before writing, and returns the output path plus a `lossiness` summary itemizing every downgraded construct. Conversion is semantic and intentionally lossy: text, headings, bold/italic/underline, hyperlinks, lists, and tables are mapped; richer styling, tracked changes, comments, and headers/footers are not. DOCX in, ODT out — Google Docs and .odt inputs are not supported.
format_layout
Apply layout controls (paragraph spacing, table row height, cell padding). Google Docs supports paragraph spacing only. Surface: revisionable — DOCX geometry edits emit native property-change revisions (w:pPrChange/w:trPrChange/w:tcPrChange).
accept_changes
Accept all tracked changes in the document body, producing a clean document with no revision markup. Returns acceptance stats.
accept_ai_edits
Selectively accept tracked changes by revision id or author in the in-memory session, leaving all other (e.g. third-party reviewer) revisions byte-untouched. This does not write file_path; call save to persist the mutation. Provide revision_ids (array of w:id values) to target specific revisions, or author to accept every revision by one actor. Sweeps document.xml and supported side-story parts (footnotes, endnotes, comments). An ambiguous overlap — a targeted revision structurally containing, or contained by, a non-targeted revision (nested ins/del/move) — hard-errors with code AMBIGUOUS_REVISION_OVERLAP and a structured `overlaps` list unless normalize_first is set (best-effort, no byte-identical promise).
reject_ai_edits
Selectively reject tracked changes by revision id or author in the in-memory session (restoring their pre-edit state), leaving all other revisions byte-untouched. This does not write file_path; call save to persist the mutation. Symmetric to accept_ai_edits: provide revision_ids or author, sweeps document.xml and supported side-story parts, and hard-errors on an ambiguous overlap (code AMBIGUOUS_REVISION_OVERLAP with a structured `overlaps` list) unless normalize_first is set.
has_tracked_changes
Check whether the document body contains tracked-change markers (insertions, deletions, moves, and property-change records). Read-only.
get_file_status
Get file/session metadata including edit count, normalization stats, and cache info. Supports DOCX, ODT, and Google Docs.
close_file
Close an open file session, or close all sessions with explicit confirmation. Supports DOCX, ODT, and Google Docs.
add_comment
Add a comment or threaded reply to a document. Provide target_paragraph_id + anchor_text for root comments, or parent_comment_id for replies. Supports DOCX and ODT (ODT backs comments with office:annotation; threaded replies are DOCX-only). Surface: revisionable + package-mutation — the body-story comment reference is tracked (w:ins), while comment text and author metadata are recorded in the save report non-revision change manifest.
get_comments
Get all comments from the document with IDs, authors, dates, text, and anchored paragraph IDs. Range-anchored DOCX comments also expose optional end_paragraph_id, start_run_index, start_char_offset, end_run_index, and end_char_offset fields describing the covered span. Includes threaded replies (DOCX). Supports DOCX and ODT. Read-only.
delete_comment
Delete a comment and all its threaded replies from the document. Cascade-deletes all descendants. Surface: revisionable + package-mutation — the body-story comment reference removal is tracked (w:del), while comment/reply text cleanup is recorded in the save report non-revision change manifest.
compare_documents
Compare two documents and produce a tracked-changes output document. Provide original_file_path + revised_file_path for standalone comparison, or file_path to compare session edits against the original. DOCX and ODF (.odt) support both modes. DOCX stats count insertions/deletions as contiguous ranges, expose atom totals as insertedAtoms/deletedAtoms, and report formatChanges separately from modifiedParagraphs. ODF compares at inline granularity (a modified paragraph is marked up in place — only the changed spans are struck or inserted).
get_footnotes
Get all footnotes from the document with IDs, display numbers, text, and anchored paragraph IDs. Read-only.
add_footnote
Add a footnote anchored to a paragraph. Optionally position the reference after specific text using after_text. Note: [^N] markers in read_file output are display-only and not part of the editable text used by replace_text. Surface: revisionable + package-mutation — the footnote reference and note text are tracked (w:ins), while footnote-part creation and registration are recorded in the save report non-revision change manifest.
update_footnote
Update the text content of an existing footnote. Surface: revisionable — note-text changes emit native OOXML tracked changes (w:ins/w:del) inside the footnote body.
delete_footnote
Delete a footnote and its reference from the document. Surface: revisionable — the reference and note text are removed as native OOXML tracked deletions (w:del).
clear_formatting
Clear specific run-level formatting (bold, italic, underline, highlight, color, font) from paragraphs. Surface: revisionable — clearing emits a native run-property-change revision (w:rPrChange).
extract_revisions
Extract tracked changes as structured JSON with before/after text per paragraph, revision details, and comments. Supports pagination via offset and limit. Read-only - does not modify the document.
Claude Desktop / Cursor
Paste into your MCP client config file to install this server.
{
"mcpServers": {
"safe docx": {
"safe-docx": {
"command": "npx",
"args": [
"-y",
"@usejunior/safe-docx"
]
}
}
}
}
McpServers
{
"safe-docx": {
"command": "npx",
"args": [
"-y",
"@usejunior/safe-docx"
]
}
}
Safe DOCX Suite
English | Español | 简体中文 | Português (Brasil) | Deutsch
safe-docx by UseJunior — use coding agents for paperwork too.
Part of the UseJunior developer tools.
Safe Docx is an open-source TypeScript stack for surgical editing of existing Microsoft Word .docx files. It is built for workflows where an agent proposes changes and a human still needs reliable, formatting-preserving document edits.
If you review contracts with AI, the slowest step is often applying accepted recommendations in Word. Safe Docx turns that into deterministic tool calls.
Why This Exists
AI coding CLIs are great with code and text files but weak on brownfield .docx editing. Business and legal workflows still run on Word documents, so we built a native TypeScript path for:
- reading and searching existing documents in token-efficient formats
- making surgical edits without destroying formatting
- producing clean/tracked outputs and revision extraction artifacts
Mission: enable coding agents to do paperwork too. Safe Docx focuses on deterministic edits to existing Word files where formatting and review semantics must survive automation.
Positioning
Safe Docx is optimized for agent workflows that need deterministic, local-first edits on existing .docx files:
- typed MCP tools for edit, compare, revision extraction, comments, footnotes, and layout
- auditable behavior with test evidence and traceability artifacts
- TypeScript runtime distribution without requiring Python or LibreOffice for supported usage
Safe Docx is not intended to replace generation-first .docx libraries.
Trusted By
- Am Law top-10 firm — multistep contract translation pipeline
- 150-lawyer regional firm — 22M+ tokens of contract markup processed
- Gemini CLI — compatible Word editing MCP extension
Start Here
npx -y @usejunior/safe-docx
For detailed setup and tool reference, see packages/docx-mcp/README.md.
Example: Agent Editing a Contract
When you prompt a coding agent (Claude Code, Cursor, Gemini CLI) with Safe Docx installed, the agent makes MCP tool calls like these:
User: Edit the NDA at ~/docs/NDA.docx — change the governing law
from "State of New York" to "State of Delaware" and save both
a clean copy and a tracked-changes copy.
Agent calls:
1. read_file(file_path="~/docs/NDA.docx", format="toon")
→ Returns paragraphs with stable IDs: _bk_1, _bk_2, ...
2. grep(file_path="~/docs/NDA.docx", pattern="State of New York")
→ Match in paragraph _bk_47
3. replace_text(
file_path="~/docs/NDA.docx",
target_paragraph_id="_bk_47",
old_string="State of New York",
new_string="State of Delaware",
instruction="Change governing law to Delaware"
)
4. save(
file_path="~/docs/NDA.docx",
save_to_local_path="~/docs/NDA-clean.docx",
tracked_save_to_local_path="~/docs/NDA-tracked.docx",
save_format="both"
)
The agent handles the tool calls automatically. You get a clean file and a tracked-changes file for human review.
MCP Quickstart
Claude Code
claude mcp add safe-docx -- npx -y @usejunior/safe-docx
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"safe-docx": {
"command": "npx",
"args": ["-y", "@usejunior/safe-docx"]
}
}
}
Gemini CLI
{
"mcpServers": {
"safe-docx": {
"command": "npx",
"args": ["-y", "@usejunior/safe-docx"]
}
}
}
Any MCP Client
- Command: npx
- Args: ["-y", "@usejunior/safe-docx"]
- Transport: stdio
What Safe Docx Is Optimized For
- Brownfield editing of existing .docx files
- Formatting-preserving text replacement and paragraph insertion
- Comment and footnote workflows
- Tracked-changes outputs for review (download, compare_documents)
- Revision extraction as structured JSON (extract_revisions)
What Safe Docx Is Not Optimized For
Safe Docx is not a from-scratch document generation toolkit.
If your primary need is generating new .docx files from templates/programmatic layout, use packages such as docx.
The local Safe Docx runtime also intentionally rejects Word template files (.dotx) for now. Convert the template to a normal .docx document before opening it here.
Document Families
Automated fixture coverage in this repo
- Common Paper style mutual NDA fixtures
- Bonterms mutual NDA fixture
- Letter of Intent fixture
- ILPA limited partnership agreement redline fixtures
Designed for complex legal and business .docx classes
- NVCA financing forms
- YC SAFEs
- Offering memoranda
- Order forms and services agreements
- Limited partnership agreements
Packages
- @usejunior/docx-core: primitives + comparison engine for existing .docx documents
- @usejunior/docx-mcp: MCP server implementation and tool surface
- @usejunior/safe-docx: canonical end-user install name (npx -y @usejunior/safe-docx)
- @usejunior/safedocx-mcpb: private MCP bundle wrapper
Reliability and Trust Surface
- Tool schemas are generated from packages/docx-mcp/src/tool_catalog.ts.
- OpenSpec traceability matrix: packages/docx-mcp/src/testing/SAFE_DOCX_OPENSPEC_TRACEABILITY.md
- Assumption matrix: packages/docx-mcp/assumptions.md
- Conformance guide: docs/safe-docx/sprint-3-conformance.md
FAQ
What is Safe Docx?
A TypeScript-first DOCX editing stack for coding-agent workflows that need deterministic, formatting-preserving edits on existing Word documents.
Does this preserve formatting during edits?
That is a core design goal. The tool surface is built around surgical operations (replace_text, insert_paragraph, layout controls) that preserve document structure and formatting semantics as much as possible.
Does this require .NET, Python, or LibreOffice in normal runtime usage?
No. Supported runtime usage is JavaScript/TypeScript with jszip + @xmldom/xmldom.
Can this generate contracts from scratch?
Not the primary focus. For from-scratch generation, use packages such as docx.
What document types has this been tested on in-repo fixtures?
Mutual NDAs (including Common Paper/Bonterms-style fixtures), Letter of Intent, and ILPA limited partnership agreement redline fixtures.
Is this only for lawyers?
No. The same brownfield .docx editing problems appear in HR, procurement, finance, sales ops, and other paperwork-heavy workflows.
Where should I start as an MCP user?
Use @usejunior/safe-docx via npx, then follow setup examples in packages/docx-mcp/README.md.
Where can I inspect the tool schemas?
See the generated reference at packages/docx-mcp/docs/tool-reference.generated.md.
Development
npm ci
npm run build
npm run lint --workspaces --if-present
npm run test:run
npm run check:spec-coverage
npm run test:coverage:packages
npm run coverage:packages:check
npm run coverage:matrix
See Also
- Open Agreements — fill standard legal templates with coding agents (NDAs, SAFEs, NVCA)
- UseJunior Developer Tools — product page with install options and tool catalog
Privacy
Safe Docx runs entirely on your local machine. No document content is sent to external servers. See our Privacy Policy for details.
Governance
- Contributing Guide
- Code of Conduct
- Security Policy
- Changelog
Sign in to leave a review
Use Google, GitHub, or an email account so ratings stay tied to real people.
No reviews posted yet.




