safe-docx
Safe DOCX Suite
English | Español | 简体中文 | Português (Brasil) | Deutsch
safe-docx by UseJunior — 코딩 에이전트를 활용한 문서 작업 자동화 도구입니다.
UseJunior 개발자 도구의 일부입니다.
Safe Docx는 기존 Microsoft Word .docx 파일을 정밀하게 편집하기 위한 오픈 소스 TypeScript 스택입니다. 에이전트가 변경 사항을 제안하고 사람이 서식을 유지하면서 안정적으로 문서를 편집해야 하는 워크플로우를 위해 구축되었습니다.
AI로 계약서를 검토할 때 가장 느린 단계는 Word에서 승인된 권장 사항을 적용하는 것입니다. Safe Docx는 이를 결정론적인 도구 호출로 변환합니다.
이 도구가 필요한 이유
AI 코딩 CLI는 코드 및 텍스트 파일에는 뛰어나지만 기존 .docx 편집에는 취약합니다. 비즈니스 및 법률 워크플로우는 여전히 Word 문서 기반으로 운영되므로, 다음과 같은 작업을 위한 네이티브 TypeScript 경로를 구축했습니다:
토큰 효율적인 형식으로 기존 문서 읽기 및 검색
서식을 파괴하지 않고 정밀하게 편집
깔끔한/변경 사항이 추적된 출력물 및 수정 사항 추출 아티팩트 생성
목표: 코딩 에이전트가 문서 작업도 수행할 수 있도록 지원합니다. Safe Docx는 자동화 과정에서도 서식과 검토 의미론이 유지되어야 하는 기존 Word 파일의 결정론적 편집에 중점을 둡니다.
Related MCP server: docx-mcp
포지셔닝
Safe Docx는 기존 .docx 파일에 대해 결정론적이고 로컬 우선 편집이 필요한 에이전트 워크플로우에 최적화되어 있습니다:
편집, 비교, 수정 사항 추출, 주석, 각주 및 레이아웃을 위한 타입 지정된 MCP 도구
테스트 증거 및 추적성 아티팩트를 통한 감사 가능한 동작
지원되는 사용 사례에서 Python이나 LibreOffice를 요구하지 않는 TypeScript 런타임 배포
Safe Docx는 생성 우선 .docx 라이브러리를 대체하기 위한 것이 아닙니다.
신뢰하는 기업
Am Law 상위 10대 로펌 — 다단계 계약서 번역 파이프라인
150명 규모의 지역 로펌 — 2,200만 개 이상의 토큰 계약서 마크업 처리
Gemini CLI — 호환 가능한 Word 편집 MCP 확장 기능
시작하기
npx -y @usejunior/safe-docx자세한 설정 및 도구 참조는 packages/docx-mcp/README.md를 참조하세요.
예시: 에이전트의 계약서 편집
Safe Docx가 설치된 코딩 에이전트(Claude Code, Cursor, Gemini CLI)에 프롬프트를 입력하면, 에이전트는 다음과 같은 MCP 도구 호출을 수행합니다:
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"
)에이전트가 도구 호출을 자동으로 처리합니다. 사용자는 깔끔한 파일과 사람이 검토할 수 있는 변경 사항 추적 파일을 얻게 됩니다.
MCP 퀵스타트
Claude Code
claude mcp add safe-docx -- npx -y @usejunior/safe-docxClaude Desktop
~/Library/Application Support/Claude/claude_desktop_config.json(macOS) 또는 %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"]
}
}
}모든 MCP 클라이언트
명령어:
npx인자:
["-y", "@usejunior/safe-docx"]전송: stdio
Safe Docx 최적화 대상
기존
.docx파일의 브라운필드 편집서식을 유지하는 텍스트 교체 및 단락 삽입
주석 및 각주 워크플로우
검토를 위한 변경 사항 추적 출력물(
download,compare_documents)구조화된 JSON으로 수정 사항 추출(
extract_revisions)
Safe Docx 최적화 대상 아님
Safe Docx는 처음부터 문서를 생성하는 툴킷이 아닙니다.
템플릿/프로그래밍 방식의 레이아웃에서 새로운 .docx 파일을 생성하는 것이 주 목적이라면 docx와 같은 패키지를 사용하세요.
또한 로컬 Safe Docx 런타임은 현재 의도적으로 Word 템플릿 파일(.dotx)을 거부합니다. 여기서 열기 전에 템플릿을 일반 .docx 문서로 변환하세요.
문서 제품군
이 저장소의 자동화된 픽스처 커버리지
Common Paper 스타일 상호 NDA 픽스처
Bonterms 상호 NDA 픽스처
의향서(LOI) 픽스처
ILPA 유한책임조합 계약서 레드라인 픽스처
복잡한 법률 및 비즈니스 .docx 클래스를 위해 설계됨
NVCA 자금 조달 양식
YC SAFE
투자 설명서
주문서 및 서비스 계약서
유한책임조합 계약서
패키지
@usejunior/docx-core: 기존.docx문서를 위한 기본 요소 + 비교 엔진@usejunior/docx-mcp: MCP 서버 구현 및 도구 인터페이스@usejunior/safe-docx: 표준 최종 사용자 설치 이름 (npx -y @usejunior/safe-docx)@usejunior/safedocx-mcpb: 비공개 MCP 번들 래퍼
신뢰성 및 보안
도구 스키마는
packages/docx-mcp/src/tool_catalog.ts에서 생성됩니다.OpenSpec 추적성 매트릭스:
packages/docx-mcp/src/testing/SAFE_DOCX_OPENSPEC_TRACEABILITY.md가정 매트릭스:
packages/docx-mcp/assumptions.md준수 가이드:
docs/safe-docx/sprint-3-conformance.md
FAQ
Safe Docx란 무엇인가요?
기존 Word 문서에 대해 결정론적이고 서식을 유지하는 편집이 필요한 코딩 에이전트 워크플로우를 위한 TypeScript 우선 DOCX 편집 스택입니다.
편집 중에 서식이 유지되나요?
그것이 핵심 설계 목표입니다. 도구 인터페이스는 문서 구조와 서식 의미론을 최대한 보존하는 정밀한 작업(replace_text, insert_paragraph, 레이아웃 제어)을 중심으로 구축되었습니다.
일반적인 런타임 사용 시 .NET, Python 또는 LibreOffice가 필요한가요?
아니요. 지원되는 런타임 사용 환경은 jszip + @xmldom/xmldom을 사용하는 JavaScript/TypeScript입니다.
처음부터 계약서를 생성할 수 있나요?
주요 목적이 아닙니다. 처음부터 생성하려면 docx와 같은 패키지를 사용하세요.
저장소 내 픽스처에서 어떤 문서 유형을 테스트했나요?
상호 NDA(Common Paper/Bonterms 스타일 픽스처 포함), 의향서, ILPA 유한책임조합 계약서 레드라인 픽스처 등을 테스트했습니다.
변호사만을 위한 도구인가요?
아니요. 동일한 브라운필드 .docx 편집 문제는 인사, 조달, 재무, 영업 운영 및 기타 문서 작업이 많은 워크플로우에서도 발생합니다.
MCP 사용자로서 어디서부터 시작해야 하나요?
npx를 통해 @usejunior/safe-docx를 사용하고 packages/docx-mcp/README.md의 설정 예시를 따르세요.
도구 스키마는 어디서 확인할 수 있나요?
packages/docx-mcp/docs/tool-reference.generated.md에서 생성된 참조를 확인하세요.
개발
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참고 자료
Open Agreements — 코딩 에이전트로 표준 법률 템플릿(NDA, SAFE, NVCA) 채우기
UseJunior Developer Tools — 설치 옵션 및 도구 카탈로그가 포함된 제품 페이지
개인정보 보호
Safe Docx는 전적으로 로컬 컴퓨터에서 실행됩니다. 문서 내용은 외부 서버로 전송되지 않습니다. 자세한 내용은 개인정보 처리방침을 참조하세요.
거버넌스
Available Tools
30 toolsaccept_ai_editsADestructive
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).
Inputs: file_path (required), author, revision_ids, normalize_first.
accept_changesBDestructive
Accept every supported tracked change in the document body, including inserted and deleted table-row revisions. Returns acceptance stats; unresolvedRowRevisions remains 0 for supported row markers.
Inputs: file_path (required).
add_commentADestructive
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.
Inputs: text (required), author (required), file_path (required), initials, +3 more.
add_footnoteADestructive
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.
Inputs: text (required), file_path (required), target_paragraph_id (required), after_text.
batch_editADestructive
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. Two source-proven bonded heading/body insertions may share an anchor and position when both declare the same bonded_pair_id and distinct style_source_id values; unrelated same-slot inserts remain conflicts. Accepts inline steps or a plan_file_path JSON array. Surface: revisionable — every applied step emits native OOXML tracked changes.
Inputs: file_path (required), steps, plan_file_path.
clear_formattingADestructive
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).
Inputs: file_path (required), clear_bold, clear_font, clear_color, +4 more.
close_fileADestructive
Close an open file session, or close all sessions with explicit confirmation. Supports DOCX, ODT, and Google Docs.
Inputs: confirm, clear_all, file_path, google_doc_id.
compare_documentsARead-only
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 output always uses the revised archive as its package base and publishes tagged revisions; engine, strategy, reconstruction, premerge, and refinement selectors are not exposed. DOCX stats count insertions/deletions as contiguous ranges, expose tagged-token-v1 totals as insertedAtoms/deletedAtoms with atomMetricVersion, report formatChanges separately from modifiedParagraphs, and report detected moves as moves/movedParagraphs with moveFromRanges/moveToRanges (moved content is not also counted as insertions or deletions, so a pure move reports moves > 0 with zero insertions/deletions). When a DOCX input difference is preserved in the output without tracked-change markup (for example a removed section's header or footer, or an unsupported header/footer topology), the response includes unrepresented_changes (objects with scope, kind, sectionIndex, for header/footer scopes role, and for the contentControl scope a contentControl identity: a changed w:sdtPr/w:sdtEndPr is published as the revised properties without markup, because CT_SdtPr admits no revision elements) plus one warnings string per entry, and the message carries a WARNING. Both fields are absent when no reportable unrepresented change was detected; the detector covers section properties, selected header/footer stories and content-control properties, so absence is not a guarantee about differences outside that scope. ODF compares at inline granularity (a modified paragraph is marked up in place — only the changed spans are struck or inserted).
Inputs: save_to_local_path (required), author, file_path, compare_moves, +4 more.
convert_to_odtA
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.
Inputs: file_path, output_path, allow_overwrite.
delete_commentADestructive
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.
Inputs: file_path (required), comment_id (required).
delete_footnoteADestructive
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).
Inputs: note_id (required), file_path (required).
exportA
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.
Inputs: format, file_path, output_path, allow_overwrite, +1 more.
extract_revisionsARead-only
Extract tracked changes as structured JSON with before/after text per paragraph, revision details, and comments. Table rows inserted or deleted as a whole, and row property changes (w:trPr > w:ins / w:del / w:trPrChange), are reported as records with scope "row", keyed by the row's first paragraph, whose revisions are ROW_INSERTION / ROW_DELETION / FORMAT_CHANGE entries carrying the revision id, author and date. Supports pagination via offset and limit. Read-only - does not modify the document.
Inputs: file_path (required), limit, offset.
format_layoutADestructive
Apply layout controls (paragraph spacing, paragraph alignment and pagination flags, table row height, cell padding). paragraph_properties sets alignment (w:jc) and sets (true) or removes (false) direct pageBreakBefore/keepNext/keepLines; requests that change nothing are no-ops. Google Docs supports paragraph spacing only. Surface: revisionable — DOCX geometry edits emit native property-change revisions (w:pPrChange/w:trPrChange/w:tcPrChange).
Inputs: strict, file_path, row_height, cell_padding, +3 more.
format_numberingADestructive
Change one DOCX body paragraph’s direct numbering reference. Use remove=true to drop direct w:numPr, match_paragraph_id to adopt another paragraph’s explicit numbering, or num_id with ilvl to reference an existing numbering definition. This tool does not create numbering definitions or change style-inherited numbering. Effective edits emit a native w:pPrChange; identical requests are no-ops.
Inputs: target_paragraph_id (required), ilvl, num_id, remove, +3 more.
format_sectionADestructive
Partially update one DOCX section’s page-number restart, page dimensions/orientation, or margins using a zero-based section_index from get_sections. Effective calls emit one native w:sectPrChange and preserve section topology, page-number format, columns, break type, and header/footer references. Orientation is literal and does not automatically swap dimensions. This tool does not create sections or edit header/footer content.
Inputs: section_index (required), margins, file_path, page_size, +2 more.
get_commentsARead-only
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.
Inputs: file_path (required).
get_document_outlineARead-only
Get a compact structural map of a document's headings (DOCX only). Each entry is {paragraph_id, text, level, source}, plus list_label (e.g. "Section 1.01") when the heading is numbered; Markdown puts the label before the text. 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.
Inputs: format, file_path, include_heuristic_headings.
get_file_statusARead-only
Get file/session metadata including edit count, normalization stats, and cache info. Supports DOCX, ODT, and Google Docs.
Inputs: file_path, google_doc_id.
get_footnotesARead-only
Get all footnotes from the document with IDs, display numbers, text, and anchored paragraph IDs. Read-only.
Inputs: file_path (required).
get_sectionsARead-only
Read DOCX main-document sections in document order. Returns zero-based session-relative section_index values, paragraph/body boundary metadata, page numbering, page size, margins, and header/footer relationship references. Call again after any operation that changes section topology. Read-only.
Inputs: file_path, google_doc_id.
grepARead-only
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.
Inputs: pattern, patterns, file_path, file_paths, +8 more.
has_tracked_changesARead-only
Check whether the document body contains tracked-change markers (insertions, deletions, moves, and property-change records). Read-only.
Inputs: file_path (required).
insert_paragraphADestructive
Insert a paragraph before/after an anchor paragraph by paragraph id. DOCX responses include structural_warnings when the placement may slice a hierarchy, mismatch list levels, or renumber a list. Supports DOCX, ODT, and Google Docs. ODT paragraph ids remain stable within the session; new paragraphs receive monotonically allocated ids, and reopening renumbers stored document order. Surface: revisionable — DOCX insertions emit native OOXML tracked changes.
Inputs: new_string (required), instruction (required), positional_anchor_node_id (required), position, +3 more.
insert_section_breakADestructive
Insert a tracked DOCX section break after a stable direct-body paragraph. The new boundary preserves the containing section’s page setup and header/footer relationship references. The following section inherits current properties by default; set inherit_properties=false to reset non-relationship properties, and optionally provide page-number/page-size/margin overrides in new_section. Call get_sections again after success because section indexes change.
Inputs: break_type (required), paragraph_id (required), file_path, new_section, +1 more.
read_fileARead-only
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.
Inputs: limit, format, offset, node_ids, +7 more.
reject_ai_editsADestructive
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.
Inputs: file_path (required), author, revision_ids, normalize_first.
replace_textADestructive
Replace text in a paragraph by provider paragraph id, preserving formatting where supported. Supports DOCX, ODT, and Google Docs. To delete an ordinary DOCX body paragraph, pass its complete visible text as old_string and an empty new_string; a clean save removes the paragraph and a tracked save keeps the deletion for review. Do not use this shortcut for paragraphs that carry section properties, are structurally required by a table cell, or own bookmark/comment anchors without inspecting the structure first. Surface: revisionable — DOCX edits emit native OOXML tracked changes (w:ins/w:del/w:rPrChange).
Inputs: new_string (required), old_string (required), instruction (required), target_paragraph_id (required), +3 more.
saveADestructive
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.
Inputs: save_to_local_path (required), file_path, save_format, google_doc_id, +7 more.
update_footnoteADestructive
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.
Inputs: note_id (required), new_text (required), file_path (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 30 tools
Most tools target a distinct resource+action (comments, footnotes, sections, formatting, revisions), and descriptions clarify the boundaries. The main overlap is accept_changes vs accept_ai_edits/reject_ai_edits and batch_edit vs insert_paragraph/replace_text, where an agent must read carefully to pick the right one.
Names are uniformly snake_case and overwhelmingly verb-first (add_comment, get_sections, format_section, delete_footnote), with clear resource suffixes. Minor deviations are bare verbs (save, grep, export) and a get_/read_ split for retrieval tools (read_file vs get_file_status/get_comments).
At 30 tools this is heavy, though the domain (DOCX/ODT/Google Docs editing with tracked changes, comments, footnotes, sections, conversion) genuinely justifies breadth. Some consolidation is plausible — four format_* tools and three accept/reject revision tools could be grouped — so it sits at the borderline.
Coverage is broad: read/search/outline, edit (batch and single-step), save/export/convert, comments and footnotes CRUD, section and formatting edits, plus accept/reject and revision extraction. Gaps are modest: no reject-all counterpart to accept_changes, no comment text update, and no table or header/footer content editing.
Maintenance
Related MCP Connectors
Document editing, AI writing, saved documents, DOCX downloads, PDF, STT, TTS and watermarking
Convert DOCX documents to and from PDF, TXT, HTML, ODT, JPG and RTF.
Convert, create and edit Word, PowerPoint, Excel and PDF documents from any AI agent.
PDF to Word that keeps the layout, merge, split, compress, OCR, PDF/A and more
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA powerful Word document processing service based on FastMCP, enabling AI assistants to create, edit, and manage docx files with full formatting support. Preserves original styles when editing content.193-
- AlicenseBqualityDmaintenanceEnables comprehensive management of Microsoft Word documents with 30+ tools for reading, writing, formatting, template merging, image extraction, equation extraction, and style application.241MIT
- AlicenseAqualityBmaintenanceFill standard legal agreement templates (NDAs, SAFEs, NVCA docs, employment, cloud terms) and produce DOCX files.35,330 npm66Apache 2.0
- AlicenseAqualityDmaintenanceProvides comprehensive read/write access to Word documents, including comments, track changes, and reply threads.91MIT