From 2bc442f795c61a89f8951b2e527bae21175da0a1 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:31:21 -0700 Subject: [PATCH] feat(app): the Connect page's Claude desktop app row writes a one-click extension (P15 C1) Claude's desktop extension format is the MCP Bundle: a .mcpb zip with a manifest.json (manifest 0.3, github.com/anthropics/mcpb). The row's button makes the company's agent key if there is none and writes Documents/Wanderbooks/Extensions/wanderbooks-.mcpb: a manifest whose server is a binary running this program's own stable path as mcp --book , the 512 px icon and a short README as the entry point. The package carries no program (the one executable is the installed one), no key and no path of the data root. The page then says in plain words where in Claude to pick the file and to keep Wanderbooks open, and offers to show the file. The manifest is checked against Anthropic's published schema (a test fixture) and its required fields. The blessed Connect page pictures change by exactly the new row. The program's version is now one value set by main for every platform, not only Unix. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 1 + crates/ledger-cli/src/main.rs | 15 +- crates/ledger-cli/tests/extension.rs | 142 +++++++ .../ledger-cli/tests/fixtures/mcpb/SOURCE.txt | 10 + .../mcpb/mcpb-manifest-v0.3.schema.json | 376 ++++++++++++++++++ crates/ledger-gui/src/connect.rs | 81 ++++ crates/ledger-gui/src/owner.rs | 19 + crates/ledger-gui/tests/assistants.rs | 55 +++ .../snapshots/assist_connect_page_dark.shapes | 2 +- .../assist_connect_page_light.shapes | 2 +- crates/ledger-host/Cargo.toml | 2 + crates/ledger-host/src/commands.rs | 2 +- crates/ledger-host/src/extension.rs | 317 +++++++++++++++ crates/ledger-host/src/lib.rs | 19 + crates/ledger-host/src/update.rs | 17 +- 15 files changed, 1039 insertions(+), 21 deletions(-) create mode 100644 crates/ledger-cli/tests/extension.rs create mode 100644 crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt create mode 100644 crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json create mode 100644 crates/ledger-host/src/extension.rs diff --git a/Cargo.lock b/Cargo.lock index 9d337a8d..7e52588d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4133,6 +4133,7 @@ dependencies = [ "tokio", "tokio-util", "zeroize", + "zip", ] [[package]] diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 406c17f6..a4940241 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -282,6 +282,18 @@ impl ledger_gui::owner::Owner for ViewerOwner { ) } + fn claude_desktop_extension( + &self, + book: &str, + company: &str, + ) -> Result { + let made = ledger_host::extension::claude_desktop_extension(&self.common, book, company)?; + Ok(ledger_gui::owner::ExtensionMade { + file: made.path.display().to_string(), + folder: made.folder.display().to_string(), + }) + } + fn new_books(&self, id: &str, currency: &str) -> Result { ledger_host::commands::new_books_and_home(&self.common, id, currency) } @@ -690,8 +702,7 @@ fn is_bare_launch(words: &[String], stdin_is_terminal: bool) -> bool { } fn main() { - #[cfg(unix)] - ledger_host::update::set_program_version(env!("CARGO_PKG_VERSION")); + ledger_host::set_program_version(env!("CARGO_PKG_VERSION")); // A file's path may be any name the system takes: the file commands // get the words as given. Everything else is text. let given: Vec = env::args_os().skip(1).collect(); diff --git a/crates/ledger-cli/tests/extension.rs b/crates/ledger-cli/tests/extension.rs new file mode 100644 index 00000000..da9a213a --- /dev/null +++ b/crates/ledger-cli/tests/extension.rs @@ -0,0 +1,142 @@ +//! The Claude desktop extension the Connect page writes (plan P15 unit C1, +//! WB-pkg-5): its package is Anthropic's MCP Bundle, and its manifest is +//! checked against Anthropic's published schema for manifest version 0.3 +//! (`tests/fixtures/mcpb/`, with where it came from). +//! +//! ```text +//! GOAL: a package the Claude desktop app can install, naming this +//! program's bridge for one company, with nothing secret in it. +//! SOURCE: WB-pkg-5; github.com/anthropics/mcpb (MANIFEST.md, the 0.3 +//! schema); ledger-host extension.rs. +//! INVARIANTS: +//! 1. The package is a zip whose root holds `manifest.json`; every file +//! the manifest names (`icon`, `server.entry_point`) is in the zip. +//! 2. The manifest validates against the 0.3 schema, which refuses any +//! field the specification does not define. +//! 3. The server is a `binary` whose command is the program's path and +//! whose arguments are `mcp --book `. +//! SCENARIOS: +//! 1. A package made for a company with an awkward name validates. +//! 2. Every required field of the schema is present. +//! ``` + +use serde_json::Value; +use std::io::Read; + +fn schema() -> jsonschema::Validator { + let text = include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json"); + jsonschema::validator_for(&serde_json::from_str::(text).unwrap()).unwrap() +} + +fn made(company: &str) -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let bridge: Vec = [ + "/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks", + "mcp", + "--book", + "acme", + ] + .map(Into::into) + .to_vec(); + let made = ledger_host::extension::write_in(dir.path(), "acme", company, "0.1.0", &bridge) + .expect("the package is written"); + (dir, made.path) +} + +fn read(path: &std::path::Path) -> (Value, Vec) { + let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap(); + let names: Vec = (0..zip.len()) + .map(|i| zip.by_index(i).unwrap().name().unwrap().to_string()) + .collect(); + let mut text = String::new(); + zip.by_name("manifest.json") + .expect("manifest.json is at the root of the package") + .read_to_string(&mut text) + .unwrap(); + (serde_json::from_str(&text).unwrap(), names) +} + +#[test] +fn the_manifest_is_one_the_published_schema_accepts() { + for company in [ + "Wanderland Labs LLC", + "Quote \" and & \u{e9}\u{4e2d}", + &"long ".repeat(100), + "", + ] { + let (_dir, path) = made(company); + let (manifest, _) = read(&path); + let errors: Vec = schema() + .iter_errors(&manifest) + .map(|e| format!("{e} at {}", e.instance_path())) + .collect(); + assert!(errors.is_empty(), "{company:?}: {errors:?}\n{manifest:#}"); + // The check is not vacuous: a field the specification lacks, or a + // missing required one, is refused. + let mut extra = manifest.clone(); + extra["no_such_field"] = Value::Bool(true); + assert!(!schema().is_valid(&extra)); + let mut short = manifest.clone(); + short.as_object_mut().unwrap().remove("author"); + assert!(!schema().is_valid(&short)); + } +} + +#[test] +fn every_file_the_manifest_names_is_in_the_package() { + let (_dir, path) = made("Acme"); + let (manifest, names) = read(&path); + assert_eq!(manifest["manifest_version"], "0.3"); + for named in [ + manifest["icon"].as_str().unwrap(), + manifest["server"]["entry_point"].as_str().unwrap(), + ] { + assert!(names.iter().any(|n| n == named), "{named} in {names:?}"); + } + // The schema's required fields, by the schema's own list. + let schema: Value = + serde_json::from_str(include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json")).unwrap(); + for field in schema["required"].as_array().unwrap() { + assert!(manifest.get(field.as_str().unwrap()).is_some(), "{field}"); + } + for field in schema["properties"]["server"]["required"] + .as_array() + .unwrap() + { + assert!(manifest["server"].get(field.as_str().unwrap()).is_some()); + } +} + +#[test] +fn the_server_runs_this_programs_bridge_for_the_company() { + let (_dir, path) = made("Acme"); + let (manifest, _) = read(&path); + let server = &manifest["server"]; + assert_eq!(server["type"], "binary"); + assert_eq!( + server["mcp_config"]["command"], + "/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks" + ); + assert_eq!( + server["mcp_config"]["args"], + serde_json::json!(["mcp", "--book", "acme"]) + ); + // The package carries no program (the one executable is the installed + // one) and no key. + let (_, names) = read(&path); + assert_eq!(names.len(), 3, "{names:?}"); + assert_eq!(manifest["name"], "wanderbooks-acme"); +} + +/// The 512 px icon is a PNG (the manifest's `icon` is "a png icon file"). +#[test] +fn the_icon_is_a_png() { + let (_dir, path) = made("Acme"); + let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap(); + let mut head = [0u8; 8]; + zip.by_name("icon.png") + .unwrap() + .read_exact(&mut head) + .unwrap(); + assert_eq!(&head, b"\x89PNG\r\n\x1a\n"); +} diff --git a/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt b/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt new file mode 100644 index 00000000..e87a8ce4 --- /dev/null +++ b/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt @@ -0,0 +1,10 @@ +mcpb-manifest-v0.3.schema.json is Anthropic's published JSON Schema for the +manifest.json of an MCP Bundle (.mcpb, formerly the Desktop Extension .dxt), +manifest_version 0.3, copied verbatim on 2026-11-21 from +https://github.com/anthropics/mcpb (schemas/mcpb-manifest-v0.3.schema.json, +main branch). The specification's prose is MANIFEST.md in the same +repository; the install steps are Claude's help article "Getting started +with Local MCP servers on Claude Desktop" (support.claude.com). +The repository's licence: Apache-2.0 for new contributions, MIT for older +ones (its LICENSE file); both fit this project's MIT OR Apache-2.0. It is +a test fixture only and is not shipped. diff --git a/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json b/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json new file mode 100644 index 00000000..64471c54 --- /dev/null +++ b/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json @@ -0,0 +1,376 @@ +{ + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "dxt_version": { + "type": "string", + "const": "0.3", + "description": "@deprecated Use manifest_version instead" + }, + "manifest_version": { + "type": "string", + "const": "0.3" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "description": { + "type": "string" + }, + "long_description": { + "type": "string" + }, + "author": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "email": { + "type": "string", + "format": "email" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "repository": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "type", + "url" + ], + "additionalProperties": false + }, + "homepage": { + "type": "string", + "format": "uri" + }, + "documentation": { + "type": "string", + "format": "uri" + }, + "support": { + "type": "string", + "format": "uri" + }, + "icon": { + "type": "string" + }, + "icons": { + "type": "array", + "items": { + "type": "object", + "properties": { + "src": { + "type": "string" + }, + "size": { + "type": "string", + "pattern": "^\\d+x\\d+$" + }, + "theme": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "src", + "size" + ], + "additionalProperties": false + } + }, + "screenshots": { + "type": "array", + "items": { + "type": "string" + } + }, + "localization": { + "type": "object", + "properties": { + "resources": { + "type": "string", + "pattern": "\\$\\{locale\\}" + }, + "default_locale": { + "type": "string", + "pattern": "^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$" + } + }, + "required": [ + "resources", + "default_locale" + ], + "additionalProperties": false + }, + "server": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "python", + "node", + "binary" + ] + }, + "entry_point": { + "type": "string" + }, + "mcp_config": { + "type": "object", + "properties": { + "command": { + "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "platform_overrides": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "command": { + "$ref": "#/properties/server/properties/mcp_config/properties/command" + }, + "args": { + "$ref": "#/properties/server/properties/mcp_config/properties/args" + }, + "env": { + "$ref": "#/properties/server/properties/mcp_config/properties/env" + } + }, + "additionalProperties": false + } + } + }, + "required": [ + "command" + ], + "additionalProperties": false + } + }, + "required": [ + "type", + "entry_point", + "mcp_config" + ], + "additionalProperties": false + }, + "tools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + } + }, + "tools_generated": { + "type": "boolean" + }, + "prompts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "arguments": { + "type": "array", + "items": { + "type": "string" + } + }, + "text": { + "type": "string" + } + }, + "required": [ + "name", + "text" + ], + "additionalProperties": false + } + }, + "prompts_generated": { + "type": "boolean" + }, + "keywords": { + "type": "array", + "items": { + "type": "string" + } + }, + "license": { + "type": "string" + }, + "privacy_policies": { + "type": "array", + "items": { + "type": "string", + "format": "uri" + } + }, + "compatibility": { + "type": "object", + "properties": { + "claude_desktop": { + "type": "string" + }, + "platforms": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "darwin", + "win32", + "linux" + ] + } + }, + "runtimes": { + "type": "object", + "properties": { + "python": { + "type": "string" + }, + "node": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "user_config": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "directory", + "file" + ] + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "default": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "multiple": { + "type": "boolean" + }, + "sensitive": { + "type": "boolean" + }, + "min": { + "type": "number" + }, + "max": { + "type": "number" + } + }, + "required": [ + "type", + "title", + "description" + ], + "additionalProperties": false + } + }, + "_meta": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": {} + } + } + }, + "required": [ + "name", + "version", + "description", + "author", + "server" + ], + "additionalProperties": false, + "$schema": "http://json-schema.org/draft-07/schema#" +} \ No newline at end of file diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index 7ae8d23e..75f8fb38 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -424,6 +424,9 @@ pub struct State { new_address_asked: bool, /// The address was just copied (the time, for the word "Copied"). copied_at: Option, + /// The folder the Claude desktop extension was written in, once it + /// was (set by the job that made it). + extension_folder: Arc>>, } /// The two lines an assistant set up by hand needs. @@ -807,6 +810,7 @@ impl State { want = Some(w); } } + self.desktop_row(ui, status, book, &owner, busy, &mut want); another_row(ui, status, book, &owner, &commands, busy, &mut want); if let Some((what, keep, work)) = want { self.start(ui, jobs, what, &keep, work); @@ -842,6 +846,83 @@ impl State { }); } + /// The "Claude desktop app" row (WB-pkg-5): one button that writes the + /// one-click extension, and the steps that follow, in plain words. + fn desktop_row( + &mut self, + ui: &mut Ui, + status: &Status, + book: &str, + owner: &Option>, + busy: bool, + want: &mut Want, + ) { + let p = pal(ui.ctx()); + let made = self + .extension_folder + .lock() + .map(|f| f.clone()) + .unwrap_or_default(); + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(12, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label(RichText::new("Claude desktop app").font(theme::semibold(14.5))); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if let Some(owner) = owner + && ui + .add_enabled(!busy, egui::Button::new("Make the Claude extension")) + .on_hover_text( + "Writes one file you open in the Claude desktop app to add these books", + ) + .clicked() + { + let (o, b, company) = + (owner.clone(), book.to_string(), status.company.clone()); + let folder = self.extension_folder.clone(); + *want = Some(( + "Claude desktop extension".to_string(), + "Making the Claude desktop extension".to_string(), + Box::new(move || { + o.claude_desktop_extension(&b, &company).map(|made| { + if let Ok(mut f) = folder.lock() { + *f = Some(made.folder.clone()); + } + format!( + "made {}. Next: open the Claude desktop app, go to Settings, then Extensions, then Advanced settings, choose Install Extension, and pick that file (or just open the file). Keep Wanderbooks open while you use Claude.", + made.file + ) + }) + }), + )); + } + }); + }); + ui.add_space(4.0); + ui.label( + RichText::new( + "Adds these books to the Claude app on this computer with one file, so you type nothing.", + ) + .font(theme::regular(13.0)) + .color(p.muted), + ); + if let Some(folder) = made { + ui.add_space(4.0); + if ui + .button(format!("{} Show the file", icon::FOLDER_OPEN)) + .clicked() + { + crate::export::open(std::path::Path::new(&folder)); + } + } + }); + ui.add_space(6.0); + } + /// "Connections": every key to these books, who is connected on it, /// what it may do, when it last did anything, and Revoke. fn connections( diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index a10aaa4f..c9289be6 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -412,6 +412,16 @@ pub trait Owner: Send + Sync { fn command_line(&self, _words: &[&str]) -> Result { Err("not here".into()) } + /// The Claude desktop extension for the company `book` (shown as + /// `company`): the one-click package written where a person can open it, + /// the key made first if there was none. Blocks. + fn claude_desktop_extension( + &self, + _book: &str, + _company: &str, + ) -> Result { + Err("not here".into()) + } /// The key an assistant needs to reach the company `book` exists (made /// now if it did not), able to read, draft and post but not to see the /// access record: `Ok(true)` when it was made now. It never replaces a @@ -476,6 +486,15 @@ pub trait Owner: Send + Sync { } } +/// The Claude desktop extension the Connect page made (WB-pkg-5). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionMade { + /// The package file, in full. + pub file: String, + /// The folder it is in. + pub folder: String, +} + /// The owner the program gave the viewer, for every company's view that /// isn't given one of its own. It is the program's (one per process, as /// the program is one), not a company's: each view takes a handle to it diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs index 0e14ef99..3d14f3ca 100644 --- a/crates/ledger-gui/tests/assistants.rs +++ b/crates/ledger-gui/tests/assistants.rs @@ -247,6 +247,17 @@ impl Owner for Fake { self.note(format!("connect {} {book}", agent.key())); Ok(vec![format!("{} reaches the books.", agent.label())]) } + fn claude_desktop_extension( + &self, + book: &str, + company: &str, + ) -> Result { + self.note(format!("extension {book} {company}")); + Ok(ledger_gui::owner::ExtensionMade { + file: "/docs/Wanderbooks/Extensions/wanderbooks-alpha.mcpb".into(), + folder: "/docs/Wanderbooks/Extensions".into(), + }) + } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } @@ -731,6 +742,50 @@ fn the_connect_buttons_do_what_connect_does() { drop(h); } +/// WB-pkg-5: the "Claude desktop app" row makes the extension for this +/// company through the owner, then says in words what to do with the file. +#[test] +fn the_claude_desktop_row_makes_the_extension_and_says_what_to_do_next() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.answer(roster(vec![], vec![])); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + h.state_mut().goto(Route::Connect); + h.run_steps(3); + assert!(h.query_by_label_contains("Claude desktop app").is_some()); + assert!( + h.query_by_label_contains("Show the file").is_none(), + "nothing is made yet" + ); + h.get_by_role_and_label(Role::Button, "Make the Claude extension") + .click(); + h.run_steps(2); + wait_for("the extension was made", || { + owner + .said() + .contains(&"extension alpha Wanderland Labs".to_string()) + }); + until(&mut h, "it said what came of it", |a| { + a.views()[0].connect_state().said().is_some() + }); + h.run_steps(2); + for words in [ + "wanderbooks-alpha.mcpb", + "Settings", + "Extensions", + "Install Extension", + "Keep Wanderbooks open", + ] { + assert!( + h.query_by_label_contains(words).is_some(), + "{words} is said on the page" + ); + } + assert!(h.query_by_label_contains("Show the file").is_some()); + drop(h); +} + // ---- 5: the warning before a close --------------------------------------------- fn connected_alpha(owner: &Fake) { diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes index e58c6ce9..6a892c47 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes @@ -1 +1 @@ -2abd53e6457106f8 +de92373f318d6a38 diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes index 26abeaee..e95e67d0 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes @@ -1 +1 @@ -b990ac9586df492a +d163fd8e3925b936 diff --git a/crates/ledger-host/Cargo.toml b/crates/ledger-host/Cargo.toml index b3eedc39..c507be73 100644 --- a/crates/ledger-host/Cargo.toml +++ b/crates/ledger-host/Cargo.toml @@ -25,6 +25,8 @@ rpassword = "7" # Token texts and passphrases are wiped from memory when dropped. zeroize = "1" minisign-verify = "0.3.0" +# The Claude desktop extension is a zip file (extension.rs). +zip = { version = "9.0.1", default-features = false, features = ["deflate"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 6564ef85..73797754 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1893,7 +1893,7 @@ pub fn ensure_key( /// What `connect` does first: the default key's copy is in the token file, /// or the key is made again with every scope (replacing a live key whose /// copy is missing: the owner asked to connect an agent here). -fn ensure_agent_key(common: &Common, book: &str) -> Result { +pub(crate) fn ensure_agent_key(common: &Common, book: &str) -> Result { let book = ledger_store::root::BookId::parse(book) .map_err(|e| e.to_string())? .to_string(); diff --git a/crates/ledger-host/src/extension.rs b/crates/ledger-host/src/extension.rs new file mode 100644 index 00000000..546142be --- /dev/null +++ b/crates/ledger-host/src/extension.rs @@ -0,0 +1,317 @@ +//! The Claude desktop extension for a company (plan P15 unit C1, 3.3). +//! +//! The Connect page's "Claude desktop app" row writes a one-click +//! extension package that makes the Claude desktop app run this program's +//! bridge (`wanderbooks mcp --book X`) for one company. The format is +//! Anthropic's MCP Bundle ("MCPB"): a zip archive, extension `.mcpb`, +//! holding a `manifest.json`. (The format was called "Desktop Extension", +//! `.dxt`, until it was renamed; the manifest spec's page says so.) +//! +//! ```text +//! GOAL: a person double-clicks one file, or picks it under Claude +//! desktop's Settings > Extensions > Advanced settings > Install +//! Extension, and Claude can keep that company's books, with no +//! command typed and no file edited. +//! SOURCE: WB-pkg-5; Anthropic's MCPB manifest specification, version +//! 0.3 (github.com/anthropics/mcpb, MANIFEST.md and +//! schemas/mcpb-manifest-v0.3.schema.json, read 2026-11-21) and +//! Claude's help article "Getting started with Local MCP servers +//! on Claude Desktop" (the install steps). +//! INVARIANTS: +//! 1. The manifest holds only fields the specification defines, with +//! `manifest_version` "0.3", a `server` of type `binary` whose +//! `mcp_config.command` is this program's own stable path (the one a +//! terminal agent is registered with: `commands::bridge_serve_args`, +//! which refuses a translocated app) and whose arguments are `mcp +//! --book ` (and `--root` when the root was named). The package +//! carries no program: the one executable is the installed one, so +//! an update of the app is an update of the extension. +//! 2. No key, token, passphrase or path of the data root is in the +//! package: the bridge reads its key from the token file the app +//! keeps, as it does for a terminal agent (`ensure_agent_key` makes +//! it, once). +//! 3. The package is written under `/Wanderbooks/Extensions/` +//! (a folder a person can open; not a book's home, which holds four +//! files and nothing else), by a temporary file and a rename. +//! 4. The package is for the system it was made on (`platforms`). +//! SCENARIOS: +//! 1. IF the program is installed at a stable path: SHOULD write +//! `wanderbooks-.mcpb` that validates against the 0.3 schema. +//! 2. IF the program runs from a translocated macOS copy: SHOULD write +//! nothing and say to move it first. +//! 3. IF the company's name holds quotes, markup or a very long text: +//! SHOULD appear as text in the manifest, bounded. +//! ``` +//! +//! Not run against a real Claude desktop app by the author (written on +//! Linux, with no Claude desktop at hand): the manifest is checked +//! against the published schema in `crates/ledger-cli/tests/extension.rs`; +//! that Claude accepts a `binary` extension whose command is an absolute +//! path to a program outside the package is the part to try first on a +//! real install. + +use crate::commands::Common; +use serde_json::{Value, json}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// The manifest specification this package follows. +pub const MANIFEST_VERSION: &str = "0.3"; + +/// The icon the package carries (the app's own, 512 px). +const ICON: &[u8] = include_bytes!("../../../deploy/packaging/icons/512x512.png"); + +/// The longest company name or description put in a manifest, in +/// characters. +const LONGEST: usize = 120; + +/// What was written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Made { + /// The package. + pub path: PathBuf, + /// The folder it is in, for the person to open. + pub folder: PathBuf, +} + +/// `/Wanderbooks/Extensions`: where the packages go. A book's id +/// is lower case, so no company's books home can have this name. +pub fn extensions_dir_in(documents: &Path) -> PathBuf { + documents.join("Wanderbooks").join("Extensions") +} + +/// The file's name for a book: `wanderbooks-.mcpb`. +pub fn file_name(book: &str) -> String { + format!("wanderbooks-{book}.mcpb") +} + +/// `process.platform`'s name for this system, as the manifest's +/// `compatibility.platforms` spells it. +pub fn platform_name() -> &'static str { + match std::env::consts::OS { + "macos" => "darwin", + "windows" => "win32", + other => other, + } +} + +/// `text` cut to [`LONGEST`] characters, with control characters turned +/// into spaces: a name is text in the manifest and nothing else. +fn tidy(text: &str) -> String { + text.chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .take(LONGEST) + .collect::() + .trim() + .to_string() +} + +/// The manifest (INVARIANT 1) for `book`, kept by `company`, run by +/// `command` with `args`, made for `platform`. +pub fn manifest( + book: &str, + company: &str, + version: &str, + command: &str, + args: &[String], + platform: &str, +) -> Value { + let company = match tidy(company) { + name if name.is_empty() => book.to_string(), + name => name, + }; + json!({ + "manifest_version": MANIFEST_VERSION, + "name": format!("wanderbooks-{book}"), + "display_name": format!("Wanderbooks: {company}"), + "version": version, + "description": format!("Lets Claude keep the books of {company} in Wanderbooks."), + "long_description": format!( + "Connects the Claude desktop app to the books of {company}, which Wanderbooks keeps on this computer. Claude reads them, drafts entries and, when you let it, posts them. Wanderbooks must be open, with these books open in a tab, for Claude to reach them." + ), + "author": { "name": "Wanderbooks", "url": "https://wanderbooks.ai" }, + "homepage": "https://wanderbooks.ai", + "icon": "icon.png", + "license": "MIT OR Apache-2.0", + "keywords": ["bookkeeping", "accounting", "wanderbooks"], + "server": { + "type": "binary", + "entry_point": "server/README.txt", + "mcp_config": { "command": command, "args": args } + }, + "tools_generated": true, + "compatibility": { "platforms": [platform] } + }) +} + +/// What `server/README.txt` says (the manifest's entry point is a file in +/// the package; the program it names is the installed one). +const README: &str = "This extension carries no program of its own.\n\ +It runs the Wanderbooks app you installed, as `wanderbooks mcp --book `,\n\ +so Claude can keep one company's books. Open Wanderbooks first, with those\n\ +books open in a tab. If you move or reinstall Wanderbooks somewhere else,\n\ +make this extension again from the app's Assistants page.\n"; + +/// The package's bytes: a zip of `manifest.json`, `icon.png` and +/// `server/README.txt` (INVARIANT 1). +pub fn package_bytes(manifest: &Value) -> Result, String> { + use zip::write::SimpleFileOptions; + let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let text = serde_json::to_vec_pretty(manifest).map_err(|e| e.to_string())?; + let mut out = std::io::Cursor::new(Vec::new()); + let mut zip = zip::ZipWriter::new(&mut out); + let mut add = |name: &str, bytes: &[u8]| -> Result<(), String> { + zip.start_file(name, options) + .map_err(|e| format!("can't make the package: {e}"))?; + zip.write_all(bytes) + .map_err(|e| format!("can't make the package: {e}")) + }; + add("manifest.json", &text)?; + add("icon.png", ICON)?; + add("server/README.txt", README.as_bytes())?; + zip.finish() + .map_err(|e| format!("can't make the package: {e}"))?; + Ok(out.into_inner()) +} + +/// Write the extension for `book` (company `company`) under `documents`, +/// for the program and arguments `bridge` (`program, args…`). The key is +/// the caller's to have made (INVARIANT 2). +pub fn write_in( + documents: &Path, + book: &str, + company: &str, + version: &str, + bridge: &[std::ffi::OsString], +) -> Result { + let book = ledger_store::root::BookId::parse(book) + .map_err(|e| e.to_string())? + .to_string(); + if !documents.is_absolute() { + return Err("there is no documents folder to put the extension in".into()); + } + let (command, args) = bridge + .split_first() + .ok_or("the bridge's command could not be worked out")?; + let as_text = |part: &std::ffi::OsStr| { + part.to_str() + .map(str::to_string) + .ok_or_else(|| "the program's path is not text Claude can be given".to_string()) + }; + let command = as_text(command)?; + let args = args + .iter() + .map(|a| as_text(a)) + .collect::, _>>()?; + let bytes = package_bytes(&manifest( + &book, + company, + version, + &command, + &args, + platform_name(), + ))?; + let folder = extensions_dir_in(documents); + std::fs::create_dir_all(&folder) + .map_err(|e| format!("can't make {}: {}", folder.display(), e.kind()))?; + let path = folder.join(file_name(&book)); + let tmp = folder.join(format!(".{}.tmp{}", file_name(&book), std::process::id())); + std::fs::write(&tmp, &bytes).map_err(|e| format!("can't write the package: {}", e.kind()))?; + std::fs::rename(&tmp, &path).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + format!("can't write the package: {}", e.kind()) + })?; + Ok(Made { path, folder }) +} + +/// The Claude desktop extension for `book`, in the person's Documents: +/// the agent key made if there is none, then the package (the words +/// above). What was made. +pub fn claude_desktop_extension( + common: &Common, + book: &str, + company: &str, +) -> Result { + let documents = crate::commands::documents_dir() + .ok_or("there is no documents folder to put the extension in")?; + // The stable path first: a translocated copy refuses here, before a + // key is made or a file written. + let bridge = crate::commands::bridge_serve_args(common, book)?; + crate::commands::ensure_agent_key(common, book)?; + write_in(&documents, book, company, crate::program_version(), &bridge) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bridge() -> Vec { + ["/opt/Wanderbooks/wanderbooks", "mcp", "--book", "acme"] + .map(Into::into) + .to_vec() + } + + #[test] + fn the_package_is_written_where_a_person_can_open_it() { + let dir = tempfile::tempdir().unwrap(); + let made = write_in(dir.path(), "acme", "Acme LLC", "0.1.0", &bridge()).unwrap(); + assert_eq!( + made.path, + dir.path() + .join("Wanderbooks/Extensions/wanderbooks-acme.mcpb") + ); + assert_eq!(made.folder, dir.path().join("Wanderbooks/Extensions")); + let file = std::fs::File::open(&made.path).unwrap(); + let mut zip = zip::ZipArchive::new(file).unwrap(); + let mut names: Vec = (0..zip.len()) + .map(|i| zip.by_index(i).unwrap().name().unwrap().to_string()) + .collect(); + names.sort(); + assert_eq!(names, ["icon.png", "manifest.json", "server/README.txt"]); + // Written again, it replaces itself; nothing is left beside it. + write_in(dir.path(), "acme", "Acme LLC", "0.1.0", &bridge()).unwrap(); + let left: Vec<_> = std::fs::read_dir(&made.folder).unwrap().collect(); + assert_eq!(left.len(), 1); + } + + #[test] + fn a_name_is_text_and_bounded() { + let long = "x".repeat(500); + let m = manifest( + "acme", + &format!("A\"\n{long}"), + "1.0.0", + "/p", + &[], + "linux", + ); + let shown = m["display_name"].as_str().unwrap(); + assert!( + shown.chars().count() <= "Wanderbooks: ".len() + LONGEST, + "{shown}" + ); + assert!(!shown.contains('\n')); + let none = manifest("acme", " ", "1.0.0", "/p", &[], "linux"); + assert_eq!(none["display_name"], "Wanderbooks: acme"); + } + + #[test] + fn no_secret_and_no_data_root_is_in_the_package() { + let dir = tempfile::tempdir().unwrap(); + let made = write_in(dir.path(), "acme", "Acme", "0.1.0", &bridge()).unwrap(); + let mut zip = zip::ZipArchive::new(std::fs::File::open(&made.path).unwrap()).unwrap(); + let mut text = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("manifest.json").unwrap(), &mut text) + .unwrap(); + for word in ["token", "passphrase", "secret", "password", "bearer"] { + assert!(!text.to_lowercase().contains(word), "{word} in {text}"); + } + assert!(text.contains("\"mcp\""), "{text}"); + } + + #[test] + fn a_relative_documents_folder_is_refused() { + let err = write_in(Path::new("Documents"), "acme", "Acme", "0.1.0", &bridge()).unwrap_err(); + assert!(err.contains("documents folder"), "{err}"); + } +} diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index 43d4cad2..119e700d 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -20,6 +20,7 @@ pub mod app_server; pub mod bridge; pub mod channel; pub mod commands; +pub mod extension; pub mod host; pub mod knobs; pub mod lease; @@ -30,6 +31,24 @@ pub mod tokens; pub mod update; pub mod web; +/// The version of the program being run, set by its `main` (this crate's +/// own is the fallback: the packages rewrite only the program's, whose +/// `Cargo.toml` is the one source of the version, WB-pkg-6). +static PROGRAM_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); + +/// Say which version this program is. +pub fn set_program_version(version: &'static str) { + let _ = PROGRAM_VERSION.set(version); +} + +/// This program's version. +pub fn program_version() -> &'static str { + PROGRAM_VERSION + .get() + .copied() + .unwrap_or(env!("CARGO_PKG_VERSION")) +} + /// How a mode stops when it can't go on: the reason is already printed, /// and the number is the process's exit code. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ledger-host/src/update.rs b/crates/ledger-host/src/update.rs index 4c519f40..dea7e848 100644 --- a/crates/ledger-host/src/update.rs +++ b/crates/ledger-host/src/update.rs @@ -90,22 +90,7 @@ const STAGED: &str = "staged"; const FEED_FILE: &str = "feed"; const CHECKED: &str = "checked"; -/// The version of the program being run, set by its `main` (this crate's -/// own is the fallback: the packages rewrite only the program's). -static PROGRAM_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); - -/// Say which version this program is. -pub fn set_program_version(version: &'static str) { - let _ = PROGRAM_VERSION.set(version); -} - -/// This program's version. -pub fn program_version() -> &'static str { - PROGRAM_VERSION - .get() - .copied() - .unwrap_or(env!("CARGO_PKG_VERSION")) -} +pub use crate::{program_version, set_program_version}; const MAX_MANIFEST: usize = 1 << 20; const MAX_PROGRAM: u64 = 1 << 30;