Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ fn extensions_command(command: &str, rest: &[String]) -> ExitCode {
println!("{}", serde_json::Value::Array(extensions::take()));
ExitCode::SUCCESS
}
Some("beat") => {
extensions::beat();
ExitCode::SUCCESS
}
Some("finish") => {
let mut text = String::new();
if std::io::Read::read_to_string(&mut std::io::stdin(), &mut text).is_err() {
Expand All @@ -123,7 +127,7 @@ fn extensions_command(command: &str, rest: &[String]) -> ExitCode {
Err(e) => fail(format!("the outcome is not JSON ({e})")),
}
}
Some(other) => fail(format!("extensions {other:?}: use list, window [BASE], stamp, file ADDRESS, take or finish RID")),
Some(other) => fail(format!("extensions {other:?}: use list, window [BASE], stamp, file ADDRESS, take, beat or finish RID")),
}
}

Expand Down Expand Up @@ -181,9 +185,9 @@ fn main() -> ExitCode {
};
}
if command == "settings" {
let saved = Settings::saved();
let read = Settings::read();
let port = Settings::load().port();
print(&json!({ "file": settings::path(), "settings": saved, "http": { "address": http::address(port), "token_file": settings::token_path() } }));
print(&json!({ "file": settings::path(), "error": read.as_ref().err(), "settings": read.clone().unwrap_or_default(), "http": { "address": http::address(port), "token_file": settings::token_path() } }));
return ExitCode::SUCCESS;
}
if command == "extensions" || command == "extension" {
Expand Down
18 changes: 18 additions & 0 deletions cli/tests/family_and_reach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,21 @@ fn make_executable(path: &std::path::Path) {

#[cfg(not(unix))]
fn make_executable(_: &std::path::Path) {}

#[test]
fn a_checkout_script_on_windows_runs_without_a_cmd_line_and_odd_paths_are_refused() {
use formmcp_core::reach::Route;
use std::path::PathBuf;
let dev = |path: &str| Route::Dev { checkout: PathBuf::from("C:\\dev\\formvis"), command: PathBuf::from(path) };

let (program, args, dir) = dev("C:\\dev\\R&D tools\\formvis\\formvis.bat").command_on(true).expect("a plain path is run");
assert_eq!(program, PathBuf::from("C:\\dev\\R&D tools\\formvis\\formvis.bat"));
assert_eq!(args, vec!["mcp".to_string()]);
assert_eq!(dir, Some(PathBuf::from("C:\\dev\\formvis")));

for odd in ["C:\\dev\\100%\\formvis\\formvis.bat", "C:\\dev\\a\nb\\formvis.bat", "C:\\dev\\a\u{7f}\\formvis.bat", "C:\\dev\\a\tb\\formvis.bat"] {
let refused = dev(odd).command_on(true);
assert!(refused.is_err(), "{odd:?} was run: {refused:?}");
}
assert!(dev("/home/me/dev/100%/formvis").command_on(false).is_ok());
}
63 changes: 63 additions & 0 deletions cli/tests/mcp_stdio_and_http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,3 +344,66 @@ fn a_session_whose_name_holds_antigravity_has_its_own_switches() {
assert_eq!(listed, offered, "{name}: {answer}");
}
}

#[test]
fn a_settings_file_that_cannot_be_read_stops_app_calls_and_is_never_replaced() {
let s = Sandbox::new("broken-settings");
s.json(&["for", "other", "formvis", "off"], &[]);
let file = s.path("formmcp/settings.json");

let mut m = Stdio2::start(&s, &[]);
m.initialize();
let listed = m.call(2, "tools/call", json!({ "name": "family_apps", "arguments": {} }));
assert!(!text(&listed).contains("\"formvis\""), "{listed}");
let good = std::fs::read_to_string(&file).unwrap();
let broken = good.trim_end().trim_end_matches('}').to_string() + ",}\n";
std::fs::write(&file, &broken).unwrap();
let during = m.call(3, "tools/call", json!({ "name": "call_app", "arguments": { "app": "formvis", "tool": "get_document" } }));
assert!(during["result"]["isError"] == json!(true) && !text(&during).contains("cannot be reached"), "{during}");
drop(m);

let mut m = Stdio2::start(&s, &[]);
m.initialize();
let fresh = m.call(2, "tools/call", json!({ "name": "call_app", "arguments": { "app": "formpdf", "tool": "status" } }));
assert!(text(&fresh).contains("could not be read") && !text(&fresh).contains("cannot be reached"), "{fresh}");
drop(m);

let out = s.command().args(["structured", "on"]).output().unwrap();
assert!(!out.status.success(), "{}", String::from_utf8_lossy(&out.stdout));
assert!(String::from_utf8_lossy(&out.stderr).contains("could not be read"), "{}", String::from_utf8_lossy(&out.stderr));
let out = s.command().args(["for", "codex", "formcut", "off"]).output().unwrap();
assert!(!out.status.success(), "{}", String::from_utf8_lossy(&out.stdout));
assert_eq!(std::fs::read_to_string(&file).unwrap(), broken);
}

#[test]
fn a_window_that_keeps_beating_while_it_works_is_not_taken_for_closed() {
use std::io::Write;
let s = Sandbox::new("window-beat");
s.json(&["extensions", "take"], &[]);
let mut m = Stdio2::start(&s, &[]);
m.initialize();
m.send(json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "demo_open", "arguments": { "id": "window" } } }));

let deadline = Instant::now() + Duration::from_secs(10);
let rid = loop {
let taken = s.json(&["extensions", "take"], &[]);
if let Some(rid) = taken.as_array().and_then(|l| l.first()).and_then(|r| r["rid"].as_str()) {
break rid.to_string();
}
assert!(Instant::now() < deadline, "the request never reached the window");
std::thread::sleep(Duration::from_millis(100));
};
let working = Instant::now();
while working.elapsed() < Duration::from_secs(12) {
let out = s.command().args(["extensions", "beat"]).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
std::thread::sleep(Duration::from_millis(900));
}
let mut finish = s.command().args(["extensions", "finish", &rid]).stdin(std::process::Stdio::piped()).spawn().unwrap();
finish.stdin.take().unwrap().write_all(br#"{"result":{"shown":true}}"#).unwrap();
assert!(finish.wait().unwrap().success());

let reply = m.reply(2, Duration::from_secs(10));
assert!(reply["result"]["isError"] != json!(true) && text(&reply).contains("shown"), "{reply}");
}
26 changes: 21 additions & 5 deletions core/src/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::path::{Path, PathBuf};
use serde::Serialize;
use serde_json::{json, Value};

use crate::extensions::APP_NAME;
use crate::{host_json, programs};

pub const SERVER_NAME: &str = "formmcp";
Expand Down Expand Up @@ -65,11 +66,26 @@ pub struct Launcher {

impl Launcher {
pub fn current() -> Result<Launcher, String> {
let program = match std::env::var_os("FORMMCP_LAUNCHER") {
Some(p) => PathBuf::from(p),
None => std::env::current_exe().map_err(|e| e.to_string())?,
};
Ok(Launcher { program, args: vec!["mcp".to_string()] })
if let Some(p) = std::env::var_os("FORMMCP_LAUNCHER") {
return Ok(Launcher { program: PathBuf::from(p), args: vec!["mcp".to_string()] });
}
let image = std::env::var_os("APPIMAGE").filter(|_| cfg!(target_os = "linux")).map(PathBuf::from).filter(|p| p.is_file());
Launcher::for_exe(std::env::current_exe().map_err(|e| e.to_string())?, image)
}

pub fn for_exe(exe: PathBuf, image: Option<PathBuf>) -> Result<Launcher, String> {
let parts: Vec<String> = exe.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
let part = |test: fn(&str) -> bool| parts.iter().any(|c| test(c));
if part(|c| c == "AppTranslocation") {
return Err(format!("{APP_NAME} is running from a temporary copy macOS made; move {APP_NAME} to Applications, open it from there and connect again"));
}
if part(|c| c.starts_with(".mount_")) {
return match image {
Some(program) => Ok(Launcher { program, args: vec!["mcp".to_string()] }),
None => Err(format!("{APP_NAME} is running from a temporary AppImage folder, {}; open the AppImage file itself and connect again", exe.display())),
};
}
Ok(Launcher { program: exe, args: vec!["mcp".to_string()] })
}
}

Expand Down
11 changes: 8 additions & 3 deletions core/src/extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,8 +487,8 @@ pub fn open_portal() -> Result<(), String> {
command.spawn().map(|_| ()).map_err(|e| format!("FormPortal could not be opened ({e}); install it from formai.studio"))
}

pub fn settings_mark() -> String {
serde_json::to_string(&settings::Settings::saved()).unwrap_or_default()
pub fn settings_mark() -> Result<String, String> {
serde_json::to_string(&settings::Settings::read()?).map_err(|e| e.to_string())
}

pub fn settings_restore(text: &str) -> Result<(), String> {
Expand Down Expand Up @@ -530,10 +530,15 @@ pub fn window_open() -> bool {
std::fs::metadata(mailbox().join(ALIVE)).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age < ALIVE_FOR)
}

pub fn beat() {
let _ = std::fs::create_dir_all(mailbox());
let _ = std::fs::write(mailbox().join(ALIVE), CORE_VERSION);
}

pub fn take() -> Vec<Value> {
let dir = mailbox().join("requests");
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(mailbox().join(ALIVE), CORE_VERSION);
beat();
let mut names: Vec<PathBuf> = std::fs::read_dir(&dir).map(|r| r.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|x| x == "json")).collect()).unwrap_or_default();
names.sort();
names
Expand Down
33 changes: 27 additions & 6 deletions core/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub struct Gateway {
pool: Arc<Mutex<Pool>>,
catalog_read: bool,
list_changed: bool,
settings_problem: Option<String>,
}

type Shared = Arc<Mutex<AppServer>>;
Expand All @@ -46,13 +47,19 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {

impl Gateway {
pub fn new(family: Family, places: Places) -> Gateway {
let settings = Settings::load();
let (settings, settings_problem) = match Settings::try_load() {
Ok(settings) => (settings, None),
Err(problem) => {
log::record("settings", json!({ "error": problem }));
(Settings::load(), Some(problem))
}
};
secrets::remember_all(&settings);
Gateway { family, places, settings, client: "other".into(), transport: "stdio", forced_client: false, pool: Arc::default(), catalog_read: false, list_changed: false }
Gateway { family, places, settings, client: "other".into(), transport: "stdio", forced_client: false, pool: Arc::default(), catalog_read: false, list_changed: false, settings_problem }
}

pub fn session(&self) -> Gateway {
Gateway { family: self.family.clone(), places: self.places.clone(), settings: self.settings.clone(), client: self.client.clone(), transport: self.transport, forced_client: self.forced_client, pool: Arc::clone(&self.pool), catalog_read: self.catalog_read, list_changed: false }
Gateway { family: self.family.clone(), places: self.places.clone(), settings: self.settings.clone(), client: self.client.clone(), transport: self.transport, forced_client: self.forced_client, pool: Arc::clone(&self.pool), catalog_read: self.catalog_read, list_changed: false, settings_problem: self.settings_problem.clone() }
}

pub fn absorb(&mut self, used: Gateway) {
Expand All @@ -61,6 +68,7 @@ impl Gateway {
self.family = used.family;
}
self.settings = used.settings;
self.settings_problem = used.settings_problem;
}

pub fn force_client(&mut self, name: &str) {
Expand All @@ -74,7 +82,17 @@ impl Gateway {
}

pub fn reload_settings(&mut self) {
let fresh = Settings::load();
let fresh = match Settings::try_load() {
Ok(fresh) => fresh,
Err(problem) => {
if self.settings_problem.as_ref() != Some(&problem) {
log::record("settings", json!({ "error": problem }));
}
self.settings_problem = Some(problem);
return;
}
};
self.settings_problem = None;
if fresh.secrets != self.settings.secrets {
secrets::remember_all(&fresh);
}
Expand Down Expand Up @@ -155,6 +173,9 @@ impl Gateway {
}

fn server(&mut self, app: &App) -> Result<(String, Shared), String> {
if let Some(problem) = &self.settings_problem {
return Err(format!("formMCP does not use {} while its settings cannot be read: {problem}", app.name));
}
let early = {
let mut pool = lock(&self.pool);
let stale = pool.running.get(&app.id).is_some_and(|(_, s)| s.try_lock().is_ok_and(|mut s| !s.alive()));
Expand Down Expand Up @@ -203,7 +224,7 @@ impl Gateway {

pub fn start_early(&mut self) {
let wanted = |m: &std::collections::BTreeMap<String, String>| m.values().any(|p| p == "session");
if !wanted(&self.settings.start) && !self.settings.profile_of(&self.client).is_some_and(|(_, p)| wanted(&p.start)) {
if self.settings_problem.is_some() || !wanted(&self.settings.start) && !self.settings.profile_of(&self.client).is_some_and(|(_, p)| wanted(&p.start)) {
return;
}
self.ensure_catalog();
Expand Down Expand Up @@ -274,7 +295,7 @@ fn start_app_server(app: &App, places: &Places, policy: &str, settings: &Setting
};
return Err((format!("{} cannot be reached: {how}", app.name), false));
};
let (program, args, dir) = route.command();
let (program, args, dir) = route.command().map_err(|e| (format!("{} was not started: {e}", app.name), false))?;
let started = Instant::now();
let wall = std::time::SystemTime::now();
let span = |ok: bool, error: Option<&str>| {
Expand Down
16 changes: 10 additions & 6 deletions core/src/reach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,20 @@ impl Route {
}
}

pub fn command(&self) -> (PathBuf, Vec<String>, Option<PathBuf>) {
pub fn command(&self) -> Result<(PathBuf, Vec<String>, Option<PathBuf>), String> {
self.command_on(cfg!(windows))
}

pub fn command_on(&self, windows: bool) -> Result<(PathBuf, Vec<String>, Option<PathBuf>), String> {
match self {
Route::Dev { checkout, command } => {
if cfg!(windows) {
(PathBuf::from("cmd"), vec!["/c".into(), command.to_string_lossy().into_owned(), "mcp".into()], Some(checkout.clone()))
} else {
(command.clone(), vec!["mcp".into()], Some(checkout.clone()))
let shown = command.to_string_lossy();
if windows && shown.chars().any(|c| c.is_ascii_control() || c == '%') {
return Err(format!("the checkout script {shown:?} has a control character or % in its path, which a Windows script cannot be started from; move the checkout to a plain folder"));
}
Ok((command.clone(), vec!["mcp".into()], Some(checkout.clone())))
}
Route::Formportal { program, product } => (program.clone(), vec!["app-mcp".into(), product.clone()], None),
Route::Formportal { program, product } => Ok((program.clone(), vec!["app-mcp".into(), product.clone()], None)),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions core/src/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ pub fn set(app: &str, name: &str, value: &str) -> Result<(), String> {
if value.is_empty() || value.len() > LONGEST {
return Err(format!("a secret is 1 to {LONGEST} bytes"));
}
let mut settings = Settings::read()?;
entry(app, name)?.set_password(value).map_err(store_error)?;
let mut settings = Settings::saved();
let names = settings.secrets.entry(app.to_string()).or_default();
if !names.iter().any(|n| n == name) {
names.push(name.to_string());
Expand All @@ -63,7 +63,7 @@ pub fn set(app: &str, name: &str, value: &str) -> Result<(), String> {
}

pub fn remove(app: &str, name: &str) -> Result<(), String> {
let mut settings = Settings::saved();
let mut settings = Settings::read()?;
let listed = settings.secrets.get(app).is_some_and(|l| l.iter().any(|n| n == name));
match entry(app, name)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => {}
Expand Down
27 changes: 22 additions & 5 deletions core/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,19 +196,36 @@ pub fn path() -> PathBuf {
}

impl Settings {
pub fn read() -> Result<Settings, String> {
let file = path();
match std::fs::read_to_string(&file) {
Ok(text) => serde_json::from_str(&text).map_err(|e| format!("{} could not be read as formMCP settings ({e}); fix or remove the file, formMCP changes nothing in it until then", file.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Settings::default()),
Err(e) => Err(format!("{} could not be read ({e}); formMCP changes nothing in it until it can be", file.display())),
}
}

pub fn saved() -> Settings {
std::fs::read_to_string(path()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
Settings::read().unwrap_or_default()
}

pub fn try_load() -> Result<Settings, String> {
Settings::read().map(Settings::with_env)
}

pub fn load() -> Settings {
let mut settings = Settings::saved();
if let Ok(list) = std::env::var("FORMMCP_EXPOSE") {
settings.expose = list.split(',').map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()).collect();
Settings::saved().with_env()
}

fn with_env(self) -> Settings {
match std::env::var("FORMMCP_EXPOSE") {
Ok(list) => Settings { expose: list.split(',').map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()).collect(), ..self },
Err(_) => self,
}
settings
}

pub fn save(&self) -> Result<PathBuf, String> {
Settings::read()?;
let file = path();
if let Some(parent) = file.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
Expand Down
16 changes: 16 additions & 0 deletions core/tests/host_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,19 @@ fn antigravity_older_file_is_reported_and_left_alone() {
assert_eq!(fs::read_to_string(&older).unwrap(), original);
assert_eq!(clients::state(Client::Antigravity).note, None);
}

#[test]
fn the_launcher_never_names_a_temporary_copy_of_the_app() {
let moved = Launcher::for_exe(PathBuf::from("/private/var/folders/ab/T/AppTranslocation/0A1B/d/FormMCP.app/Contents/MacOS/formmcp"), None);
assert!(moved.as_ref().is_err_and(|e| e.contains("Applications")), "{:?}", moved.map(|l| l.program));

let inside = PathBuf::from("/tmp/.mount_FormMCa1b2/usr/bin/formmcp");
let image = PathBuf::from("/opt/apps/FormMCP.AppImage");
let from_image = Launcher::for_exe(inside.clone(), Some(image.clone())).expect("the AppImage itself is named");
assert_eq!(from_image.program, image);
assert_eq!(from_image.args, vec!["mcp".to_string()]);
assert!(Launcher::for_exe(inside, None).is_err());

let installed = PathBuf::from("/Applications/FormMCP.app/Contents/MacOS/formmcp");
assert_eq!(Launcher::for_exe(installed.clone(), None).map(|l| l.program), Ok(installed));
}
Loading
Loading