mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-21 20:39:42 +00:00
* #7124: mcp refuses to start without both automation roots, and refuses --connect Co-Authored-By: Claude Opus 5.5 <[email protected]> * #7124: control protocol says --connect is refused; test folder comment matches Co-Authored-By: Claude Opus 5.5 <[email protected]> * #7124: refuse --connect without a value; test folders removed by Drop guards Co-Authored-By: Claude Opus 5.5 <[email protected]> * #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 <[email protected]> * #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 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: FredApps <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
FredApps
parent
60ac6f5e6d
commit
70ecef86df
@@ -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`.
|
||||
|
||||
@@ -206,14 +206,15 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?s
|
||||
WordCraft was designed to be driven by people *and* by AI agents.
|
||||
|
||||
```sh
|
||||
claude mcp add wordcraft -- wordcraft-cli mcp # headless documents
|
||||
# confine the agent to folders: wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
|
||||
wordcraft --control 7981 & # or drive the running app…
|
||||
claude mcp add wordcraft-app -- wordcraft-cli mcp --connect 127.0.0.1:7981
|
||||
# headless documents; the agent reads only inside the first folder and writes only inside the second
|
||||
claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
|
||||
```
|
||||
|
||||
Both roots are required. Bridging an agent to the running app (`mcp --connect`) is refused until
|
||||
the app confines its control channel to the same roots (#3695).
|
||||
|
||||
Tools include `list_commands`, `execute`, `batch`, `type_text`, `select_text`, `inspect_document`,
|
||||
`render_page`, `save_document`, and, with a running app, `screenshot`, `click` and `key`. Agents
|
||||
`render_page` and `save_document`. Agents
|
||||
can check their work through `inspect_document` without screenshots. See [docs/mcp.md](docs/mcp.md)
|
||||
and the [control protocol](docs/control-protocol.md). Macros record any sequence of commands and
|
||||
play it back (`tools.recordMacro`, `tools.macros`).
|
||||
|
||||
+3
-1
File diff suppressed because one or more lines are too long
@@ -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 <command> <file> [--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<wordcraft_engine::file_access::AutomationRoots>,
|
||||
author: Option<&str>,
|
||||
) -> Result<wordcraft_mcp::Headless, String> {
|
||||
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<String> {
|
||||
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<S: AsRef<OsStr>>(raw: &[S]) -> Option<PathBuf> {
|
||||
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::<u16>().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<S: AsRef<OsStr>>(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<dyn wordcraft_mcp::Backend> = 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<dyn wordcraft_mcp::Backend> = 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.
|
||||
|
||||
@@ -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::<Vec<_>>(), 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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 <args>`, 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<Value> = 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<Value> =
|
||||
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<String> = 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());
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
+20
-11
@@ -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 <dir>` or `--flag=<dir>`).
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user