From 70ecef86df6d37b7efe8df84c686e2081e382656 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:08:42 +0000 Subject: [PATCH] #7124: mcp refuses to start without both automation roots, and refuses --connect (#7157) * #7124: mcp refuses to start without both automation roots, and refuses --connect Co-Authored-By: Claude Opus 5.5 * #7124: control protocol says --connect is refused; test folder comment matches Co-Authored-By: Claude Opus 5.5 * #7124: refuse --connect without a value; test folders removed by Drop guards Co-Authored-By: Claude Opus 5.5 * #7124: scratch folders retry only a name that exists Scratch::new and Folders::new retried every create_dir failure, so a missing or read-only temp folder looped forever instead of failing the test (CodeRabbit). Retry only AlreadyExists; any other error panics with the path. Co-Authored-By: Claude Opus 5.5 * #7124: mcp's headless session is built by a function the unit tests reach SonarCloud's new-code coverage was 57%: the session set-up after the root checks ran only in the subprocess integration tests, which coverage does not see. headless_mcp builds the confined session and applies --author; mcp_headless_session_takes_the_author_flag covers it without confining the test process. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- AGENTS.md | 2 +- README.md | 11 +- ROADMAP.md | 4 +- apps/wordcraft-cli/src/main.rs | 109 +++++------ apps/wordcraft-cli/src/tests.rs | 113 +++++++++++- apps/wordcraft-cli/tests/it/closed_stdout.rs | 14 +- apps/wordcraft-cli/tests/it/main.rs | 1 + apps/wordcraft-cli/tests/it/mcp_roots.rs | 179 +++++++++++++++++++ crates/mcp/src/lib.rs | 3 +- docs/control-protocol.md | 6 +- docs/mcp.md | 31 ++-- 11 files changed, 378 insertions(+), 95 deletions(-) create mode 100644 apps/wordcraft-cli/tests/it/mcp_roots.rs diff --git a/AGENTS.md b/AGENTS.md index 5f53cf29ef..3ec9719e4c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W - `unsafe`: none; the workspace forbids it. Typing behaviour is pinned by `crates/engine/src/tests/typing.rs` and described in `docs/typing-parity.md`. - Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`. - Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)). -- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp` (add `--connect 127.0.0.1:7981` to drive the app), see `docs/mcp.md`. +- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`. - Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists. - Contributor credits: `docs/contributors.md`. diff --git a/README.md b/README.md index ee41a08d2d..04e64218dc 100644 --- a/README.md +++ b/README.md @@ -206,14 +206,15 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** trivial (progress log: File › Print’s preview pages as the print job prints and marks tracked changes with Track Changes Options, #5232, #6267); previously trivial (formatting shortcuts say what they did to screen readers); previously trivial (dialogs are dialogs to screen readers, their tabs are tabs, and colour fields and swatches say their colour); previously trivial (the Paste button is named "Paste" for screen readers, without macOS's key on other platforms; the status bar's Go To hint shows the platform's key); previously trivial (progress log: border boxes close their corners; previously trivial: progress log: file formats, codecs and protocols from craft-libs, #778); previously trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** trivial (progress log: `wordcraft-cli mcp` needs both automation roots and refuses `--connect`, #7124); previously trivial (progress log: File › Print’s preview pages as the print job prints and marks tracked changes with Track Changes Options, #5232, #6267); previously trivial (formatting shortcuts say what they did to screen readers); previously trivial (dialogs are dialogs to screen readers, their tabs are tabs, and colour fields and swatches say their colour); previously trivial (the Paste button is named "Paste" for screen readers, without macOS's key on other platforms; the status bar's Go To hint shows the platform's key); previously trivial (progress log: border boxes close their corners; previously trivial: progress log: file formats, codecs and protocols from craft-libs, #778); previously trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > > **Recipient CSV update:** 2026-10-27 · Complete quoted header records choose the delimiter (#4249); detection and regressions follow the current mailings module split. Recipient limits and readiness estimates are unchanged. @@ -151,6 +151,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-11-20: `wordcraft-cli mcp` starts only with both `--automation-read-root` and `--automation-write-root` (shared rule 18, #7124); without them it stops with an error naming the two flags, where it used to serve with access to every file the user can reach. `mcp --connect` is refused until the desktop app confines its control channel to the same roots (#3695, #5819). The help, `docs/mcp.md`, the README and `AGENTS.md` pass both roots in every example. - 2026-11-15: Native, built-in and web Insert/Change Picture choosers offer both TIFF extensions (`.tif`, `.tiff`) alongside other supported pictures; native drops, picked-file inbox dispatch and pasted picture paths recognize the same suffixes (#6704). TIFF decoding remains limited to supported compression. - 2026-10-31: Screen readers hear what the dialogs and their drawn controls are: a dialog is a dialog, where it was only a window, so NVDA says so and reads the text in it (Word Count's figures); a dialog's tabs (Paragraph, Find and Replace, About) are tabs, the one shown selected, as in Word, where they were buttons read as pressed toggles; a colour field says its label and colour ("Font color: #104861"), where its text alone was the colour's hex digits; and each swatch of the colour grid says its colour, where it had no name. Readiness estimates unchanged. @@ -413,6 +414,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-11-20 | trivial | Progress log: `wordcraft-cli mcp` needs both automation roots; `--connect` refused (#7124) | | 2026-11-17 | trivial | Progress log: file formats, codecs and protocols come from craft-libs (#778) | | 2026-11-15 | trivial | Progress log: Get the Missing Fonts (download pages for missing fonts their publisher gives away) | | 2026-11-07 | Narrow windows (#5886): the window can be made 600 pt wide (was 760 pt), enabling split-window layout and edge tiling on Wayland/GNOME and 1280 pt screens; the title bar's search box and Discord button condense, and status-bar texts (page, word count, language, Track Changes, Overtype) stop before the right controls or shorten ("…" for language) instead of overlapping Focus, views and zoom | diff --git a/apps/wordcraft-cli/src/main.rs b/apps/wordcraft-cli/src/main.rs index 63d4abf3c2..7a12dd3c32 100644 --- a/apps/wordcraft-cli/src/main.rs +++ b/apps/wordcraft-cli/src/main.rs @@ -51,14 +51,16 @@ USAGE: documents and with {\"id\": N} makes one active wordcraft-cli commands [--json] list every command wordcraft-cli parity [--markdown] feature-catalog parity - wordcraft-cli mcp [--connect HOST:PORT | --author NAME] [--automation-read-root DIR] [--automation-write-root DIR] - MCP server on stdio (headless, or bridged to the app). - --automation-read-root / --automation-write-root confine - the files the agent's commands read (open, insert text - or picture, mail-merge data, templates…) and write (save, - export, merge output…) to DIR, links followed; a root left - out grants none of its access. They apply to the headless - server and are an error with --connect. + wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME] + MCP server on stdio, with a headless session. + Both roots are required: the agent's commands read + files (open, insert text or picture, mail-merge data, + templates…) only inside the read root and write them + (save, export, merge output…) only inside the write + root, links followed; the same folder may be both. + --connect HOST:PORT (bridge to the running app) is + refused until the app confines its control channel + (#3695, #5819). wordcraft-cli zotero [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P] run a Zotero command on a document (Zotero must be running): addEditCitation, addEditBibliography, @@ -217,6 +219,19 @@ fn set_author(s: &mut Session, name: &str) -> Result<(), String> { s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false)) } +/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the +/// process to the same roots first (`confine_process`), which a test must not do. +fn headless_mcp( + roots: std::sync::Arc, + author: Option<&str>, +) -> Result { + let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots)); + if let Some(name) = author { + set_author(&mut headless.session, name)?; + } + Ok(headless) +} + fn arg_value(args: &[String], name: &str) -> Option { args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned() } @@ -352,6 +367,16 @@ const RUN_OPTIONS: &[OptionSpec] = &[ ]; const COMMANDS_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_value: false }]; const PARITY_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--markdown", takes_value: false }]; +/// Why `mcp` won't start unconfined (shared rule 18, #7124). +const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \ + commands may read only inside the read root and write only inside the write root (the same folder may be both)"; + +/// Why `mcp --connect` is refused: the running app would not confine the agent's file access. +// lean: refused outright; allow it once the app confines its control channel and reports both roots. +const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \ + channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \ + --automation-read-root DIR --automation-write-root DIR"; + const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--connect", takes_value: true }, OptionSpec { name: "--author", takes_value: true }]; const ZOTERO_OPTIONS: &[OptionSpec] = &[ OptionSpec { name: "--cmd", takes_value: true }, @@ -416,14 +441,6 @@ fn script_operand>(raw: &[S]) -> Option { raw.get(at + 1).map(|a| PathBuf::from(a.as_ref())) } -/// Whether `addr` (`HOST:PORT`, as `--connect` gives it) is at least shaped like an address: a -/// host of some kind and a numeric port. Malformed addresses fail at startup — a lazy remote -/// would otherwise retry one on every call and never say why nothing connects. -fn valid_connect_addr(addr: &str) -> bool { - let Some((host, port)) = addr.rsplit_once(':') else { return false }; - !host.is_empty() && port.parse::().is_ok() -} - /// A failed `--strict` export: a strict refusal becomes [`Failure::Strict`] carrying what stderr /// shows (each line of the report as `wordcraft-cli: …`, then its JSON on one line, from /// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary @@ -717,57 +734,19 @@ fn run>(args: &[S]) -> Result<(), Failure> { "mcp" => { let (roots, rest) = automation_roots("mcp", &rest)?; validate_options("mcp", &rest, MCP_OPTIONS)?; - let author = arg_value(&rest, "--author"); - let connect = arg_value(&rest, "--connect"); - if roots.is_some() && connect.is_some() { - return Err( - "mcp: --automation-read-root and --automation-write-root confine the headless server; a running app is not confined by them" - .into(), - ); + // Refused with or without a value: a bare trailing `--connect` must not slip past. + if rest.iter().any(|a| a == "--connect" || a.starts_with("--connect=")) { + return Err(MCP_CONNECT_REFUSED.into()); } - let backend: Box = match connect { - // The app's user name is the person's own setting; don't rewrite it from a flag. - Some(_) if author.is_some() => { - return Err("mcp: --author applies to the headless server; with --connect, run file.setAuthor".into()); - } - Some(addr) => { - // A malformed address must fail at startup, not on every tool call the lazy - // remote would retry it with. - if !valid_connect_addr(&addr) { - return Err(format!("mcp: --connect needs HOST:PORT with a numeric port, got `{addr}`").into()); - } - match wordcraft_mcp::Remote::connect(&addr) { - Ok(remote) => { - eprintln!("wordcraft-cli mcp: connected to WordCraft at {addr}"); - if let Some(w) = remote.key_warning() { - eprintln!("wordcraft-cli: {w}"); - } - Box::new(remote) - } - // The app may start after the client does: serve anyway and connect on the - // first call, or the client marks the server failed for its whole session - // (#4078). - Err(e) => { - eprintln!("wordcraft-cli mcp: WordCraft is not reachable at {addr} yet ({e}); will retry on each call"); - Box::new(wordcraft_mcp::Remote::lazy(&addr)) - } - } - } - None => { - let mut headless = wordcraft_mcp::Headless::default(); - if let Some(roots) = roots { - // Every thread of this process, not only the server's: nothing reaches past the roots. - wordcraft_engine::file_access::confine_process(roots.clone()); - let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string()); - eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root())); - headless = headless.with_automation_roots(Some(roots)); - } - if let Some(name) = author { - set_author(&mut headless.session, &name)?; - } - Box::new(headless) - } + // Shared rule 18 (#7124): an agent entry point never runs unconfined. + let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else { + return Err(MCP_NEEDS_ROOTS.into()); }; + // Every thread of this process, not only the server's: nothing reaches past the roots. + wordcraft_engine::file_access::confine_process(roots.clone()); + let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string()); + eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root())); + let backend: Box = Box::new(headless_mcp(roots, arg_value(&rest, "--author").as_deref())?); let mut server = wordcraft_mcp::Server::new(backend); let stdin = std::io::stdin(); // A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly. diff --git a/apps/wordcraft-cli/src/tests.rs b/apps/wordcraft-cli/src/tests.rs index e22d4791fb..8466ef8d9c 100644 --- a/apps/wordcraft-cli/src/tests.rs +++ b/apps/wordcraft-cli/src/tests.rs @@ -126,11 +126,6 @@ fn author_flag_names_the_headless_session() { assert_eq!(s.author, "Claude (copyedit)"); assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:"))); assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok()); - // The app's user name is the person's own; a bridge flag must not rewrite it. - assert!(run(&args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"])).is_err_and(|e| e.to_string().contains("--author"))); - // A malformed address fails at startup, not on every retried call. - assert!(run(&args(&["mcp", "--connect", "127.0.0.1:notaport"])).is_err_and(|e| e.to_string().contains("numeric port"))); - assert!(run(&args(&["mcp", "--connect", "notaport"])).is_err_and(|e| e.to_string().contains("numeric port"))); // The flag goes through the same protection check as the command. let mut s = Session::new(wordcraft_doc::Document::new()); s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap(); @@ -240,11 +235,113 @@ fn only_the_opened_file_may_be_other_than_unicode() { } } +/// An exclusively created scratch folder, removed on drop even when an assertion fails. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + loop { + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("wc-cli-{tag}-{}-{n}", std::process::id())); + // `create_dir` fails when the path exists, so a leftover or a planted folder is never reused. Any + // other failure (no temp folder, no permission) fails every name: report it instead of looping. + match std::fs::create_dir(&dir) { + Ok(()) => return Self(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => panic!("scratch folder {}: {e}", dir.display()), + } + } + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Shared rule 18 (#7124): every agent entry point, a subcommand that serves a client's requests +/// rather than running what the person typed and exiting, refuses to start without both +/// automation roots. Each subcommand has a row, so a new one fails here until it is classified, +/// and a new agent entry point fails until it refuses. #[test] -fn automation_roots_are_an_error_with_connect() { +fn every_agent_entry_point_refuses_to_start_without_both_roots() { + enum Kind { + Agent, + NotAgent(&'static str), + } + use Kind::{Agent, NotAgent}; + let table = [ + ("convert", NotAgent("converts the files named on its command line, then exits")), + ("info", NotAgent("reads the one file named on its command line, then exits")), + ("text", NotAgent("reads the one file named on its command line, then exits")), + ("inspect", NotAgent("reads the one file named on its command line, then exits")), + ("render", NotAgent("renders the file named on its command line, then exits")), + ("run", NotAgent("runs the commands and script named on its command line, then exits")), + ("commands", NotAgent("lists the commands; touches no file")), + ("parity", NotAgent("prints the feature catalog; touches no file")), + ("mcp", Agent), + ("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")), + ]; + assert_eq!(table.iter().map(|(name, _)| *name).collect::>(), SUBCOMMANDS); + + let scratch = Scratch::new("entry"); + let base = scratch.0.clone(); + std::fs::create_dir_all(base.join("in")).unwrap(); + std::fs::create_dir_all(base.join("out")).unwrap(); + let read = format!("--automation-read-root={}", base.join("in").display()); + let write = format!("--automation-write-root={}", base.join("out").display()); + for (name, kind) in table { + if let NotAgent(why) = kind { + assert!(!why.is_empty(), "{name}: say why it is not an agent entry point"); + continue; + } + for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] { + let line = [vec![name.to_string()], given].concat(); + let e = run(&line).unwrap_err().to_string(); + assert!(e.contains("--automation-read-root") && e.contains("--automation-write-root"), "{line:?}: {e}"); + } + } +} + +/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge +/// to it is refused, with roots or without, before anything connects. +#[test] +fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() { let dir = std::env::temp_dir().to_string_lossy().into_owned(); - let e = run(&args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir])).unwrap_err().to_string(); - assert!(e.contains("--automation-read-root") && e.contains("headless"), "{e}"); + for line in [ + args(&["mcp", "--connect", "127.0.0.1:9"]), + args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]), + args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]), + ] { + let e = run(&line).unwrap_err().to_string(); + assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}"); + } +} + +/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does. +#[test] +fn mcp_headless_session_takes_the_author_flag() { + let scratch = Scratch::new("mcp-author"); + let roots = wordcraft_engine::file_access::AutomationRoots::new(Some(&scratch.0), Some(&scratch.0)).unwrap().unwrap(); + assert_eq!(headless_mcp(roots.clone(), Some("Claude (copyedit)")).unwrap().session.author, "Claude (copyedit)"); + assert!(headless_mcp(roots.clone(), Some(" ")).is_err_and(|e| e.starts_with("--author:"))); + let unnamed = headless_mcp(roots, None).unwrap(); + assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author"); +} + +/// `--connect` is refused whether or not it has a value, even with both roots valid. +#[test] +fn mcp_connect_is_refused_without_a_value_too() { + let scratch = Scratch::new("connect-bare"); + let dir = scratch.0.to_string_lossy().into_owned(); + let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir]; + for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"]] { + let line = args(&[&["mcp"][..], &roots, &tail].concat()); + let e = run(&line).unwrap_err().to_string(); + assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}"); + } } #[test] diff --git a/apps/wordcraft-cli/tests/it/closed_stdout.rs b/apps/wordcraft-cli/tests/it/closed_stdout.rs index 307c071000..55c939456d 100644 --- a/apps/wordcraft-cli/tests/it/closed_stdout.rs +++ b/apps/wordcraft-cli/tests/it/closed_stdout.rs @@ -24,7 +24,19 @@ fn commands_json_into_a_closed_pipe_exits_quietly() { #[test] fn mcp_server_ends_cleanly_when_its_client_closes_stdout() { - let mut child = cli().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + // The server starts only with both roots (#7124); the temporary folder serves as both. + let root = std::env::temp_dir(); + let mut child = cli() + .arg("mcp") + .arg("--automation-read-root") + .arg(&root) + .arg("--automation-write-root") + .arg(&root) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); drop(child.stdout.take()); let mut stdin = child.stdin.take().unwrap(); // The reply to this request has nowhere to go. diff --git a/apps/wordcraft-cli/tests/it/main.rs b/apps/wordcraft-cli/tests/it/main.rs index 5aaf93cca5..15e6a68665 100644 --- a/apps/wordcraft-cli/tests/it/main.rs +++ b/apps/wordcraft-cli/tests/it/main.rs @@ -3,6 +3,7 @@ mod closed_stdout; mod convert_fields; mod convert_region; mod help; +mod mcp_roots; #[cfg(all(unix, not(target_os = "macos")))] mod non_utf8_args; mod picture_then_typing; diff --git a/apps/wordcraft-cli/tests/it/mcp_roots.rs b/apps/wordcraft-cli/tests/it/mcp_roots.rs new file mode 100644 index 0000000000..c413630130 --- /dev/null +++ b/apps/wordcraft-cli/tests/it/mcp_roots.rs @@ -0,0 +1,179 @@ +//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both +//! `--automation-read-root` and `--automation-write-root`, refuses `--connect` while the desktop +//! app doesn't confine its control channel (#3695, #5819), and with both roots refuses files +//! outside them, through the real binary. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::{Value, json}; + +/// An exclusively created folder holding `in` (the read root, with `a.txt`), `out` (the write +/// root) and `outside` (with `secret.txt`). Removed on drop, even when an assertion fails. +struct Folders(PathBuf); + +impl Folders { + fn new(tag: &str) -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let base = loop { + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("wc-cli-mcp-roots-{tag}-{}-{n}", std::process::id())); + // `create_dir` fails when the path exists, so a leftover or a planted folder is never reused. Any + // other failure (no temp folder, no permission) fails every name: report it instead of looping. + match std::fs::create_dir(&dir) { + Ok(()) => break dir, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => panic!("scratch folder {}: {e}", dir.display()), + } + }; + let folders = Self(base); + for d in ["in", "out", "outside"] { + std::fs::create_dir_all(folders.0.join(d)).unwrap(); + } + std::fs::write(folders.0.join("in/a.txt"), "Inside text").unwrap(); + std::fs::write(folders.0.join("outside/secret.txt"), "TOP SECRET").unwrap(); + folders + } +} + +impl Drop for Folders { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn s(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +/// Run `wordcraft-cli mcp `, send `lines` on stdin, then hang up. +fn mcp(args: &[String], lines: &[Value]) -> Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")) + .arg("mcp") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + for line in lines { + // A server that refused to start has closed its end: that is the expected outcome. + let _ = writeln!(stdin, "{line}"); + } + drop(stdin); + child.wait_with_output().unwrap() +} + +const PING: &str = r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#; + +fn refused_at_start(args: &[String], why: &[&str]) { + let out = mcp(args, &[serde_json::from_str(PING).unwrap()]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{args:?} started: stderr {stderr}"); + assert!(out.stdout.is_empty(), "{args:?} served: {}", String::from_utf8_lossy(&out.stdout)); + for w in why { + assert!(stderr.contains(w), "{args:?}: `{w}` missing from {stderr}"); + } + assert!(!stderr.contains("panicked"), "{stderr}"); +} + +#[test] +fn mcp_refuses_to_start_without_both_roots() { + let folders = Folders::new("start"); + let base = folders.0.clone(); + let (read, write) = (s(&base.join("in")), s(&base.join("out"))); + let both = ["--automation-read-root", "--automation-write-root"]; + refused_at_start(&[], &both); + refused_at_start(&["--author".into(), "Claude".into()], &both); + refused_at_start(&["--automation-read-root".into(), read.clone()], &both); + refused_at_start(&[format!("--automation-write-root={write}")], &both); + // Both: it serves. + let out = mcp(&["--automation-read-root".into(), read, "--automation-write-root".into(), write], &[serde_json::from_str(PING).unwrap()]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "stderr: {stderr}"); + let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap(); + assert_eq!(reply["id"], 1, "{reply}"); + assert!(reply.get("error").is_none(), "{reply}"); +} + +#[test] +fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() { + let folders = Folders::new("connect"); + let base = folders.0.clone(); + let (read, write) = (s(&base.join("in")), s(&base.join("out"))); + let why = ["--connect", "#3695", "#5819"]; + refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &why); + refused_at_start( + &["--connect".into(), "127.0.0.1:9".into(), "--automation-read-root".into(), read, "--automation-write-root".into(), write], + &why, + ); +} + +/// `tools/call` request `id` for `name` with `arguments`. +fn tool(id: u64, name: &str, arguments: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": arguments}}) +} + +fn execute(id: u64, command: &str, params: Value) -> Value { + tool(id, "execute", json!({"command": command, "params": params})) +} + +#[test] +fn mcp_with_both_roots_refuses_files_outside_them() { + let folders = Folders::new("files"); + let base = folders.0.clone(); + let sep = std::path::MAIN_SEPARATOR; + let (inside, outside) = (base.join("in"), base.join("outside")); + let secret = s(&outside.join("secret.txt")); + let up = |root: &str, rest: &str| format!("{}{sep}..{sep}{rest}", s(&base.join(root))); + #[cfg(unix)] + let linked = std::os::unix::fs::symlink(&outside, base.join("out/away")).is_ok() + && std::os::unix::fs::symlink(outside.join("secret.txt"), inside.join("leak.txt")).is_ok(); + #[cfg(not(unix))] + let linked = false; + + // (id, request, refused with). Reads first, then writes, then the allowed ones. + let mut cases = vec![ + (2, tool(2, "open_document", json!({"path": secret})), Some("outside the read root")), + (3, execute(3, "file.open", json!({"path": secret})), Some("outside the read root")), + (4, execute(4, "file.open", json!({"path": up("in", "outside/secret.txt")})), Some("outside the read root")), + (5, execute(5, "insert.picture", json!({"path": s(&outside.join("pic.png"))})), Some("outside the read root")), + (6, execute(6, "insert.textFromFile", json!({"path": secret})), Some("outside the read root")), + (7, tool(7, "save_document", json!({"path": s(&outside.join("a.docx"))})), Some("outside the write root")), + (8, execute(8, "file.saveAs", json!({"path": s(&outside.join("b.docx"))})), Some("outside the write root")), + (9, execute(9, "file.exportPdf", json!({"path": s(&outside.join("c.pdf"))})), Some("outside the write root")), + (10, execute(10, "file.exportPng", json!({"path": s(&outside.join("d.png"))})), Some("outside the write root")), + (11, execute(11, "file.saveAs", json!({"path": up("out", "outside/e.docx")})), Some("outside the write root")), + // The write root isn't readable, nor the read root writable. + (12, execute(12, "file.saveAs", json!({"path": s(&inside.join("f.docx"))})), Some("outside the write root")), + (13, tool(13, "open_document", json!({"path": s(&inside.join("a.txt"))})), None), + (14, execute(14, "file.saveAs", json!({"path": s(&base.join("out/g.docx"))})), None), + ]; + if linked { + cases.push((15, tool(15, "open_document", json!({"path": s(&inside.join("leak.txt"))})), Some("outside the read root"))); + cases.push((16, execute(16, "file.saveAs", json!({"path": s(&base.join("out/away/h.docx"))})), Some("outside the write root"))); + } + let requests: Vec = cases.iter().map(|(_, r, _)| r.clone()).collect(); + let out = mcp(&["--automation-read-root".into(), s(&inside), "--automation-write-root".into(), s(&base.join("out"))], &requests); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "stderr: {stderr}"); + let replies: Vec = + String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect(); + for (id, request, why) in &cases { + let reply = replies.iter().find(|r| r["id"] == *id).unwrap_or_else(|| panic!("no reply to {request}")); + let result = &reply["result"]; + let text: String = result["content"].as_array().into_iter().flatten().filter_map(|c| c["text"].as_str()).collect(); + match why { + Some(why) => assert!(result["isError"] == true && text.contains(why), "{request} should be refused ({why}): {reply}"), + None => assert!(result["isError"] != true, "{request}: {reply}"), + } + } + let mut written: Vec = std::fs::read_dir(&outside).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + written.sort(); + assert_eq!(written, ["secret.txt"], "nothing was written outside the roots"); + assert!(!inside.join("f.docx").exists()); + assert!(base.join("out/g.docx").is_file()); +} diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 11a39e7a6a..bd862201de 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -21,7 +21,8 @@ use wordcraft_engine::Session; use wordcraft_engine::file_access::{self, AutomationRoots}; /// Methods that need the desktop app. -pub const NEEDS_APP: &str = "needs the desktop app: start `wordcraft --control 7981` and run `wordcraft-cli mcp --connect 127.0.0.1:7981`"; +pub const NEEDS_APP: &str = + "needs the desktop app; `wordcraft-cli mcp --connect` is refused until the app confines its control channel to automation roots (#3695)"; /// An in-process session. pub struct Headless { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index fc849ed23a..eaba10ef85 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol -> **Last updated:** 2026-11-18 · The control channel authenticates once per connection with a token (`auth`), replacing the per-request key. Earlier: Correct the force-close request envelope and document the optional command search parameter; command behavior unchanged. #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows. +> **Last updated:** 2026-11-20 · `wordcraft-cli mcp --connect` is refused for now (#7124); the token section describes the bridge for when it returns. Earlier: The control channel authenticates once per connection with a token (`auth`), replacing the per-request key. Earlier: Correct the force-close request envelope and document the optional command search parameter; command behavior unchanged. #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows. Start the app with a control port: `wordcraft --control 7981` (or `WORDCRAFT_CONTROL_PORT=7981`). A missing or invalid port after `--control` (not 1–65535) prints an error and exits with status 2. @@ -52,7 +52,9 @@ exit. sends. After that the connection may stay idle. - At most 16 connections are served at once; the next one gets `connection limit reached`. -`wordcraft-cli mcp --connect` takes the token from `WORDCRAFT_CONTROL_TOKEN`, or else from the +`wordcraft-cli mcp --connect` is refused for now, until the app confines this channel to automation +roots (#3695, #5819; see [docs/mcp.md](mcp.md)). When it returns, it takes the token from +`WORDCRAFT_CONTROL_TOKEN`, or else from the token file for the port it connects to, and reads it again on every new connection (the app may have restarted). It sends the token only to the app's own address, `127.0.0.1` (`localhost` connects there too, never to `::1`): another loopback address such as `::1` or `127.0.0.2` is not diff --git a/docs/mcp.md b/docs/mcp.md index 3ab1edf4fa..a2b1dcb44d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,17 +1,26 @@ # MCP server -> **Last updated:** 2026-11-18 · The bridge authenticates once per connection with the control token (`WORDCRAFT_CONTROL_TOKEN` or the app's token file). Earlier: The protocol core is the shared `craft-mcp-server` crate (#778); `click` and `key` list every argument they accept. Earlier: Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests. +> **Last updated:** 2026-11-20 · `wordcraft-cli mcp` starts only with both `--automation-read-root` and `--automation-write-root`, and `--connect` is refused until the desktop app confines its control channel (#7124, shared rule 18). Earlier: The bridge authenticates once per connection with the control token (`WORDCRAFT_CONTROL_TOKEN` or the app's token file). Earlier: The protocol core is the shared `craft-mcp-server` crate (#778); `click` and `key` list every argument they accept. Earlier: Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests. WordCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio, so Claude and other agents can write and edit documents. ```sh -wordcraft-cli mcp # headless session (no window) -wordcraft --control 7981 & # or: drive the running app… -wordcraft-cli mcp --connect 127.0.0.1:7981 # …including clicks, keys and screenshots +wordcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out ``` -Claude Code: `claude mcp add wordcraft -- wordcraft-cli mcp`. +Claude Code: `claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out`. + +The server runs a headless session (no window) and starts only with both roots: see +[Confining file access](#confining-file-access). Without them it stops with an error naming the +two flags (shared rule 18, #7124). + +**`--connect` is refused for now.** `wordcraft-cli mcp --connect HOST:PORT` bridged an agent to the +running app (`wordcraft --control 7981`), with clicks, keys and screenshots. The app doesn't +confine its control channel to automation roots yet, so the bridge would give the agent every file +the user can reach; it stops with an error pointing to #3695 and #5819. Once the app confines the +channel, connected mode will be allowed when the app has both roots set. The rest of this page +describes the connected mode as it will work then. With `--connect`, the bridge authenticates once per connection with the app's control token, which it reads from `WORDCRAFT_CONTROL_TOKEN` or from the token file the app writes at start. It sends @@ -75,7 +84,7 @@ status 1, and nothing is saved. Every output is checked (known extension, folder Tracked changes and comments are recorded under the session's user name ("WordCraft User" by default). Name the agent so reviewers can tell its edits from people's: start the headless server -with `wordcraft-cli mcp --author "Claude (copyedit)"`, or run +with `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR --author "Claude (copyedit)"`, or run `file.setAuthor {"name": "Claude (copyedit)"}`. Turn tracking on explicitly with `review.trackChanges {"value": true}`; without `value` it toggles, which turns tracking *off* in a document that was saved with it on. `wordcraft-cli run` takes `--author` too. @@ -111,8 +120,8 @@ config works across the suite) keep the agent to the folders you give it: the name it is given, so that name must be inside the write root as well as what it leads to: a link outside the root pointing in is refused (#3735). - Read and write access are separate. Give the same folder twice for both; a root left out grants - none of its access (with only `--automation-read-root`, nothing can be written to disk). Without - either flag nothing changes. + none of its access at the engine level. `wordcraft-cli mcp` needs both flags and refuses to start + with one or neither. - A path is made absolute against the server's working directory, then its links are followed: a file (or folder) link that leads out of a root is outside it. For a file that doesn't exist yet, its nearest existing folder's links are followed and the rest must be plain names, so `..` below a @@ -126,9 +135,9 @@ config works across the suite) keep the agent to the folders you give it: - The roots must be existing folders; a missing one stops the server with an error. Each flag is given once (`--flag ` or `--flag=`). -The flags confine the headless server; `--connect` with them is an error, since the server would -otherwise talk to an app that isn't confined. WordCraft's desktop app has no equivalent flags yet, -so a running app (`wordcraft --control`) is not confined. +The flags confine the headless server. WordCraft's desktop app has no equivalent flags yet, so a +running app (`wordcraft --control`) is not confined, and `--connect` is refused, with the flags or +without (#3695, #5819). What the roots do not cover: commands that take no path (`text.insert`, `execute` of anything that works on the open document) can still read and change that document, and `get_text` and