mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-30 18:24:11 +01:00
- Live mode keeps every --automation-write-root, not only the first. - --attach sends this machine's token file only to a loopback address; another host gets only FIGCRAFT_CONTROL_TOKEN. - Stopping a listener (the launcher's switch off) cancels its requests still queued, so none runs after the stop. - A screenshot write is checked against the request's roots again when it happens. - The frame that applies an agent's queued ui.input batch runs confined to that agent's roots, so a queued Save shortcut can't write outside them. - The headless confinement test uses the registered file.saveAs; docs say both roots are required only without the switch or with --headless.
453 lines
21 KiB
Rust
453 lines
21 KiB
Rust
//! `figcraft-cli`: FigCraft without a window. Inspect, export, convert and render documents, run
|
|
//! command scripts, list commands, serve MCP on stdio, publish plugins to a server's plugin
|
|
//! directory, publish code connect mappings to a design file and measure performance. `run` is the
|
|
//! whole program, so it can be tested in-process as well as through the binary. The conventions are
|
|
//! RFC-0018's: exit 0, 1 (a command failed) or 2 (a usage error), results on stdout,
|
|
//! `error: <message>` on stderr.
|
|
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
|
|
|
/// Writes a line to `$io.out`. A closed pipe (`figcraft-cli commands | head`) is not worth an error:
|
|
/// the rest of the output is dropped.
|
|
macro_rules! outln {
|
|
($io:expr) => {
|
|
drop(writeln!($io.out))
|
|
};
|
|
($io:expr, $($arg:tt)*) => {
|
|
drop(writeln!($io.out, $($arg)*))
|
|
};
|
|
}
|
|
|
|
/// Writes a line to `$io.err`.
|
|
macro_rules! errln {
|
|
($io:expr, $($arg:tt)*) => {
|
|
drop(writeln!($io.err, $($arg)*))
|
|
};
|
|
}
|
|
|
|
mod args;
|
|
mod files;
|
|
mod live;
|
|
mod perf;
|
|
|
|
use std::ffi::OsString;
|
|
use std::io::Write;
|
|
|
|
use args::{Cli, Command, ConnectCommand, McpArgs, PluginCommand, RootArgs};
|
|
use serde_json::{Value, json};
|
|
|
|
/// The automation roots a file subcommand was given, if any. Omitting both leaves the run
|
|
/// unconfined, as before; giving either confines every file the subcommand touches (#833).
|
|
fn roots_of(r: &RootArgs) -> CliResult<Option<figcraft_engine::file_access::Roots>> {
|
|
if r.automation_read_root.is_empty() && r.automation_write_root.is_empty() {
|
|
return Ok(None);
|
|
}
|
|
Ok(Some(figcraft_engine::file_access::Roots::new(&r.automation_read_root, &r.automation_write_root).map_err(CliError::Failed)?))
|
|
}
|
|
|
|
/// Runs `f` confined to the roots `r` carries.
|
|
fn confined<R>(r: &RootArgs, f: impl FnOnce() -> CliResult<R>) -> CliResult<R> {
|
|
let roots = roots_of(r)?.map(std::sync::Arc::new);
|
|
figcraft_engine::file_access::confined(roots.as_ref(), f)
|
|
}
|
|
|
|
/// Why a command did not succeed. The variant is the exit code: a usage error is 2, a failure 1.
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum CliError {
|
|
/// Bad arguments found after parsing (an output extension no format writes): exit code 2.
|
|
#[error("{0}")]
|
|
Usage(String),
|
|
/// The operation failed: exit code 1.
|
|
#[error("{0}")]
|
|
Failed(String),
|
|
}
|
|
|
|
/// The two output streams a command writes to: results to `out`, diagnostics to `err`.
|
|
pub(crate) struct Io<'a> {
|
|
pub(crate) out: &'a mut dyn Write,
|
|
pub(crate) err: &'a mut dyn Write,
|
|
}
|
|
|
|
impl From<String> for CliError {
|
|
fn from(s: String) -> Self {
|
|
CliError::Failed(s)
|
|
}
|
|
}
|
|
|
|
pub type CliResult<T> = Result<T, CliError>;
|
|
|
|
fn dispatch(cli: Cli, io: &mut Io) -> CliResult<i32> {
|
|
check(&cli.command)?;
|
|
// Headless MCP is always confined (AGENTS.md: agent entry points refuse to start without both
|
|
// roots, unless the ArtCraft Launcher's switch lets agents in, which gives them the agent
|
|
// folders); checked before the fonts are scanned, so a usage error comes back at once.
|
|
let mcp_plan = match &cli.command {
|
|
Command::Mcp(a) => Some(mcp_plan(a, &live::launcher_allows)?),
|
|
_ => None,
|
|
};
|
|
if !cli.no_system_fonts {
|
|
// Text lays out with the installed fonts, like the desktop app, so headless renders and
|
|
// auto layout sizes match what users see.
|
|
figcraft_text::scan_system_fonts_on_demand();
|
|
} else {
|
|
// Nothing scans them then, not even a `.sketch` import matching its fonts.
|
|
figcraft_text::opt_out_of_system_fonts();
|
|
}
|
|
match cli.command {
|
|
Command::Info(a) => confined(&a.roots, || files::info(&a.file, a.json, io)),
|
|
Command::Export(a) => {
|
|
let target = files::Target {
|
|
print: a.print(),
|
|
vd_compat: a.vd_compat,
|
|
scale: a.scale.scale,
|
|
format: a.format,
|
|
page: a.page,
|
|
node: a.node,
|
|
strict: a.strict,
|
|
};
|
|
confined(&a.roots, || files::export(&a.file, &a.out, &target, io))
|
|
}
|
|
Command::Convert(a) => confined(&a.roots, || files::convert(&a.input, &a.output, a.strict, io)),
|
|
Command::Render(a) => confined(&a.roots, || files::render(&a.file, &a.out, a.scale.scale, a.page.as_deref(), io)),
|
|
Command::Run(a) => confined(&a.roots, || files::run_script(&a.script, a.input.as_deref(), a.out.as_deref(), a.strict, io)),
|
|
Command::Commands(a) => {
|
|
commands(a.json, a.filter.as_deref(), io);
|
|
Ok(0)
|
|
}
|
|
// `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them.
|
|
Command::Mcp(_) => mcp(mcp_plan.ok_or_else(|| CliError::Failed("no MCP plan".into()))?, io),
|
|
Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server, a.key.as_deref(), io),
|
|
Command::Connect { command: ConnectCommand::Publish(a) } => {
|
|
confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run, io))
|
|
}
|
|
Command::Perf(a) => {
|
|
let sizes: Vec<usize> = a.layers.into_iter().map(|n| n.clamp(10, 2_000_000)).collect();
|
|
let instances: Vec<usize> = a.instances.into_iter().filter(|n| *n > 0).map(|n| n.min(100_000)).collect();
|
|
perf::run(&sizes, &instances, !cli.no_system_fonts, io)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn commands(as_json: bool, filter: Option<&str>, io: &mut Io) {
|
|
let f = filter.map(str::to_lowercase).unwrap_or_default();
|
|
let list: Vec<&figcraft_engine::CommandSpec> = figcraft_engine::all_commands()
|
|
.iter()
|
|
.filter(|c| f.is_empty() || c.id.to_lowercase().contains(&f) || c.label.to_lowercase().contains(&f) || c.params.to_lowercase().contains(&f))
|
|
.collect();
|
|
if as_json {
|
|
let v: Vec<Value> = list
|
|
.iter()
|
|
.map(|c| json!({"id": c.id, "label": c.label, "params": c.params, "menu": c.menu(), "shortcut": c.shortcut(), "undoable": c.history}))
|
|
.collect();
|
|
outln!(io, "{}", serde_json::to_string_pretty(&v).unwrap_or_default());
|
|
return;
|
|
}
|
|
for c in list {
|
|
let sc = c.shortcut().map(|s| format!(" ({s})")).unwrap_or_default();
|
|
let undo = if c.history { "*" } else { "" };
|
|
outln!(io, "{}{undo} {}{sc}\n {}", c.id, c.label, c.params);
|
|
}
|
|
}
|
|
|
|
/// Publish the plugin folder `folder` to the plugin directory at `server` (the key from the address
|
|
/// or `FIGCRAFT_SERVER_KEY`); never prints the key.
|
|
fn publish_plugin(folder: &str, server: &str, key: Option<&str>, io: &mut Io) -> CliResult<i32> {
|
|
let address = server.split('?').next().unwrap_or_default().to_string();
|
|
let server = match key.map(str::trim) {
|
|
Some(key) if !server.contains("key=") && !key.is_empty() => format!("{address}?key={key}"),
|
|
_ => server.to_string(),
|
|
};
|
|
let mut h = figcraft_mcp::Headless::new();
|
|
use figcraft_mcp::Backend as _;
|
|
let r = h.call("engine.execute", json!({"command": "plugin.directory.publish", "params": {"path": folder, "server": server}}))?;
|
|
let e = &r["published"];
|
|
outln!(
|
|
io,
|
|
"Published {} {} ({}) to {address}: {} bytes, SHA-256 {}",
|
|
e["name"].as_str().unwrap_or_default(),
|
|
e["version"].as_str().unwrap_or_default(),
|
|
e["id"].as_str().unwrap_or_default(),
|
|
e["bytes"],
|
|
e["sha256"].as_str().unwrap_or_default()
|
|
);
|
|
Ok(0)
|
|
}
|
|
|
|
/// How `figcraft-cli mcp` serves.
|
|
enum McpPlan {
|
|
/// `--attach ADDR`: the app started with `--control`, its token read from the file it wrote.
|
|
Attach { addr: String, timeout: Option<std::time::Duration> },
|
|
/// No window: `--headless`, or the ArtCraft Launcher's switch doesn't let agents use FigCraft.
|
|
Headless(figcraft_engine::file_access::Roots),
|
|
/// The open window while the launcher's switch lets agents in, otherwise headless (#2740).
|
|
Live(live::Options),
|
|
}
|
|
|
|
/// What `a` asks for. `allowed` reads the launcher's switch; it is asked only when it decides
|
|
/// (no `--attach`, no `--headless`).
|
|
fn mcp_plan(a: &McpArgs, allowed: &dyn Fn() -> bool) -> CliResult<McpPlan> {
|
|
let timeout = a.timeout.map(std::time::Duration::from_secs);
|
|
if let Some(addr) = &a.attach {
|
|
return Ok(McpPlan::Attach { addr: addr.clone(), timeout });
|
|
}
|
|
let config_dir = live::settings_dir();
|
|
match config_dir {
|
|
Some(config_dir) if !a.headless && allowed() => {
|
|
let servers = allowed_servers(&a.automation_allow_servers)?;
|
|
let path = |d: &String| std::path::PathBuf::from(d);
|
|
let launch = std::env::current_exe().ok().and_then(|cli| craft_control::agents::launcher(&cli, "figcraft"));
|
|
Ok(McpPlan::Live(live::Options {
|
|
config_dir,
|
|
read_roots: a.roots.automation_read_root.iter().map(path).collect(),
|
|
write_roots: a.roots.automation_write_root.iter().map(path).collect(),
|
|
servers,
|
|
timeout,
|
|
launch,
|
|
consent: Box::new(live::launcher_allows),
|
|
}))
|
|
}
|
|
_ => Ok(McpPlan::Headless(mcp_roots(&a.roots, &a.automation_allow_servers)?)),
|
|
}
|
|
}
|
|
|
|
fn mcp(plan: McpPlan, io: &mut Io) -> CliResult<i32> {
|
|
let (backend, roots): (Box<dyn figcraft_mcp::Backend>, _) = match plan {
|
|
McpPlan::Attach { addr, timeout } => {
|
|
let no_app = |e: std::io::Error| format!("can't reach the FigCraft app at {addr}: {e} (start it with `figcraft --control PORT`)");
|
|
let mut b = figcraft_mcp::Attached::connect(&addr).map_err(no_app)?;
|
|
if let Some(token) = attach_token(&addr, &live::control_app()) {
|
|
b = b.with_token(token);
|
|
}
|
|
let b = match timeout {
|
|
Some(t) => b.with_timeout(t).map_err(no_app)?,
|
|
None => b,
|
|
};
|
|
(Box::new(b), None)
|
|
}
|
|
McpPlan::Headless(roots) => (Box::new(figcraft_mcp::Headless::new()), Some(roots)),
|
|
// Each route confines itself: the window by the app's own roots, a headless session by its folders.
|
|
McpPlan::Live(options) => (Box::new(live::LiveBackend::new(options)), None),
|
|
};
|
|
errln!(io, "figcraft MCP server ({}) on stdio", backend.describe());
|
|
if let Some(r) = &roots {
|
|
errln!(io, "file access confined to {}", r.to_json());
|
|
}
|
|
let mut server = figcraft_mcp::Server::new(backend).with_roots(roots);
|
|
let stdin = std::io::stdin();
|
|
let stdout = std::io::stdout();
|
|
server.serve(stdin.lock(), stdout.lock()).map_err(|e| format!("stdio: {e}"))?;
|
|
Ok(0)
|
|
}
|
|
|
|
/// The token `--attach ADDR` sends: for a loopback address the token file the app on this machine
|
|
/// wrote for that port (or `FIGCRAFT_CONTROL_TOKEN`); for any other host only
|
|
/// `FIGCRAFT_CONTROL_TOKEN`, since this machine's token file belongs to this machine's app.
|
|
fn attach_token(addr: &str, app: &craft_control::auth::App) -> Option<String> {
|
|
let (host, port) = addr.rsplit_once(':')?;
|
|
let port = port.parse::<u16>().ok()?;
|
|
let host = host.trim_start_matches('[').trim_end_matches(']');
|
|
let loopback = host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
|
if loopback { app.client_token(port, None).map(|t| t.token) } else { app.env_token() }
|
|
}
|
|
|
|
/// The roots a headless MCP session is confined to: both kinds are required, and the servers in
|
|
/// `allowed_servers` (ws:// or wss:// addresses without a query or key) are the only ones
|
|
/// `collab.join` may reach.
|
|
fn mcp_roots(roots: &RootArgs, allowed_servers: &[String]) -> CliResult<figcraft_engine::file_access::Roots> {
|
|
if roots.automation_read_root.is_empty() || roots.automation_write_root.is_empty() {
|
|
return Err(CliError::Usage("headless mcp requires both --automation-read-root and --automation-write-root".into()));
|
|
}
|
|
let roots = figcraft_engine::file_access::Roots::new(&roots.automation_read_root, &roots.automation_write_root).map_err(CliError::Failed)?;
|
|
Ok(roots.with_allowed_servers(self::allowed_servers(allowed_servers)?))
|
|
}
|
|
|
|
/// `--automation-allow-server`: ws:// or wss:// server URLs without a query or key.
|
|
fn allowed_servers(allowed_servers: &[String]) -> CliResult<Vec<String>> {
|
|
let mut servers = Vec::with_capacity(allowed_servers.len());
|
|
for server in allowed_servers {
|
|
if server.contains('?') {
|
|
return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into()));
|
|
}
|
|
let (endpoint, query) = figcraft_collab_net::Endpoint::parse(server)
|
|
.map_err(|_| CliError::Usage("--automation-allow-server must be a ws:// or wss:// server URL".into()))?;
|
|
if !query.is_empty() {
|
|
return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into()));
|
|
}
|
|
servers.push(endpoint.url());
|
|
}
|
|
Ok(servers)
|
|
}
|
|
|
|
/// What the arguments can't say alone: an output that would replace its input needs `--in-place`.
|
|
fn check(command: &Command) -> CliResult<()> {
|
|
let refuse = |flag: &str, path: &str, input: &str, allowed: bool| -> CliResult<()> {
|
|
if !same_file(path, input) {
|
|
return Ok(());
|
|
}
|
|
if allowed {
|
|
return Ok(());
|
|
}
|
|
Err(CliError::Usage(format!("{flag} {path} is the input, which it would replace: choose another file, or pass --in-place")))
|
|
};
|
|
// `--strict` holds a writer to what it reports, so it is refused where nothing would be checked.
|
|
let unchecked = |what: &str, formats: &str| {
|
|
Err(CliError::Usage(format!("--strict checks {formats}, the formats that report what they leave out; {what} isn't one of them")))
|
|
};
|
|
match command {
|
|
Command::Export(a) if a.strict && !files::export_reports_losses(a.format.as_deref(), &a.out) => {
|
|
return unchecked(&format!("--out {}", a.out), "fig, penpot and xml exports");
|
|
}
|
|
Command::Export(a) if a.strict && a.vd_compat == figcraft_doc::VdCompat::Ignore && files::export_writes_xml(a.format.as_deref(), &a.out) => {
|
|
return Err(CliError::Usage("--strict can't check --vd-compat ignore, which drops what it can't draw without saying so".into()));
|
|
}
|
|
Command::Convert(a) if a.strict && !files::save_reports_losses(&a.output) => {
|
|
return unchecked(&format!("OUT {}", a.output), ".fig, .penpot and .figcraft output");
|
|
}
|
|
Command::Run(a) if a.strict && !a.out.as_deref().is_some_and(files::save_reports_losses) => {
|
|
return unchecked(&format!("--out {}", a.out.as_deref().unwrap_or("")), ".fig, .penpot and .figcraft output");
|
|
}
|
|
_ => {}
|
|
}
|
|
match command {
|
|
Command::Convert(a) => refuse("OUT", &a.output, &a.input, a.in_place)?,
|
|
Command::Run(a) => {
|
|
if let (Some(out), Some(input)) = (&a.out, &a.input) {
|
|
refuse("--out", out, input, a.in_place)?;
|
|
}
|
|
}
|
|
Command::Export(a) => refuse("--out", &a.out, &a.file, false)?,
|
|
Command::Render(a) => refuse("--out", &a.out, &a.file, false)?,
|
|
_ => {}
|
|
}
|
|
if let Command::Convert(a) = command
|
|
&& a.in_place
|
|
&& !same_file(&a.output, &a.input)
|
|
{
|
|
return Err(CliError::Usage("--in-place is for an OUT that is the IN, and this is another file".into()));
|
|
}
|
|
if let Command::Run(a) = command
|
|
&& a.in_place
|
|
&& !matches!((&a.out, &a.input), (Some(out), Some(input)) if same_file(out, input))
|
|
{
|
|
return Err(CliError::Usage("--in-place is for an --out that is the --in file, and this is another file".into()));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Whether two paths name the same existing file, through links and `.` and `..`.
|
|
fn same_file(a: &str, b: &str) -> bool {
|
|
matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b)
|
|
}
|
|
|
|
/// Run the CLI on its arguments (without the program name), writing results to `out` and
|
|
/// diagnostics to `err`. Returns the process exit code: 0 on success, 1 on failure, 2 for a usage
|
|
/// error. Help and the version go to `out`, exit 0. `mcp` speaks MCP on the process's own stdin
|
|
/// and stdout.
|
|
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
|
where
|
|
I: IntoIterator<Item = T>,
|
|
T: Into<OsString>,
|
|
{
|
|
let argv: Vec<OsString> = std::iter::once(OsString::from("figcraft-cli")).chain(args.into_iter().map(Into::into)).collect();
|
|
let cli = match args::parse(argv) {
|
|
Ok(cli) => cli,
|
|
Err(e) => {
|
|
// Help and `--version` on stdout with 0, usage errors on stderr with 2.
|
|
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
|
let _ = write!(to, "{}", e.render());
|
|
return e.exit_code();
|
|
}
|
|
};
|
|
let mut io = Io { out, err };
|
|
// Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable.
|
|
match dispatch(cli, &mut io) {
|
|
Ok(code) => code,
|
|
Err(e @ CliError::Usage(_)) => {
|
|
errln!(io, "error: {}\n\nFor more information, try '--help'.", files::plain(&e.to_string()));
|
|
2
|
|
}
|
|
Err(e @ CliError::Failed(_)) => {
|
|
errln!(io, "error: {}", files::plain(&e.to_string()));
|
|
1
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod mcp_roots_tests {
|
|
use super::{CliError, McpPlan, attach_token, mcp_plan, mcp_roots};
|
|
use crate::args::{McpArgs, RootArgs};
|
|
|
|
fn args(attach: Option<&str>, headless: bool, read: &[&str], write: &[&str]) -> McpArgs {
|
|
let own = |d: &[&str]| d.iter().map(|s| s.to_string()).collect();
|
|
McpArgs {
|
|
attach: attach.map(str::to_string),
|
|
headless,
|
|
timeout: None,
|
|
automation_allow_servers: Vec::new(),
|
|
roots: RootArgs { automation_read_root: own(read), automation_write_root: own(write) },
|
|
}
|
|
}
|
|
|
|
// #2740: plain `mcp` with the ArtCraft Launcher's switch on needs no roots (the agent folders
|
|
// stand in); with it off, or with --headless, both roots are still required (rule 18).
|
|
#[test]
|
|
fn plain_mcp_without_roots_runs_only_while_the_launcher_lets_agents_in() {
|
|
let on = || true;
|
|
let off = || false;
|
|
let never = || -> bool { panic!("the switch decides nothing here") };
|
|
assert!(matches!(mcp_plan(&args(None, false, &[], &[]), &off), Err(CliError::Usage(_))));
|
|
assert!(matches!(mcp_plan(&args(None, true, &[], &[]), &never), Err(CliError::Usage(_))), "--headless needs both roots");
|
|
assert!(matches!(mcp_plan(&args(Some("127.0.0.1:7979"), false, &[], &[]), &never), Ok(McpPlan::Attach { .. })));
|
|
// Needs a settings folder to find the app in; every test machine has a platform folder.
|
|
let Ok(McpPlan::Live(live)) = mcp_plan(&args(None, false, &["in"], &["out", "more"]), &on) else { panic!("live") };
|
|
assert_eq!(live.read_roots, [std::path::PathBuf::from("in")]);
|
|
assert_eq!(live.write_roots, [std::path::PathBuf::from("out"), std::path::PathBuf::from("more")], "every write root is kept");
|
|
assert!(matches!(mcp_plan(&args(None, false, &[], &[]), &on), Ok(McpPlan::Live(_))));
|
|
}
|
|
|
|
fn token_folder() -> Option<std::path::PathBuf> {
|
|
Some(std::env::temp_dir().join(format!("figcraft-cli-attach-token-{}", std::process::id())))
|
|
}
|
|
|
|
// This machine's token file goes only to this machine's app, never to another host on the same
|
|
// port.
|
|
#[test]
|
|
fn attach_sends_the_local_token_only_to_loopback() {
|
|
let app = craft_control::auth::App { name: "FigCraft", data_dir: token_folder, env: |_| None, utc: |s| s.to_string(), default_port: 7979 };
|
|
let file = app.token_path(7979).unwrap();
|
|
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
|
std::fs::write(&file, "local-token\n").unwrap();
|
|
for local in ["127.0.0.1:7979", "localhost:7979", "[::1]:7979"] {
|
|
assert_eq!(attach_token(local, &app).as_deref(), Some("local-token"), "{local}");
|
|
}
|
|
for remote in ["192.168.0.2:7979", "example.com:7979", "[2001:db8::1]:7979"] {
|
|
assert_eq!(attach_token(remote, &app), None, "{remote}");
|
|
}
|
|
let _ = std::fs::remove_dir_all(token_folder().unwrap());
|
|
}
|
|
|
|
#[test]
|
|
fn headless_mcp_requires_both_roots_and_allowlist_cannot_carry_a_key() {
|
|
let server = "wss://figcraft.example.com/".to_string();
|
|
let no_roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: Vec::new() };
|
|
assert!(matches!(mcp_roots(&no_roots, &[]), Err(CliError::Usage(_))));
|
|
assert!(matches!(mcp_roots(&no_roots, std::slice::from_ref(&server)), Err(CliError::Usage(_))));
|
|
|
|
let path = std::env::temp_dir().join(format!("figcraft-cli-roots-{}", std::process::id()));
|
|
std::fs::create_dir_all(&path).unwrap();
|
|
let root = path.to_string_lossy().into_owned();
|
|
let read_only = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: Vec::new() };
|
|
assert!(matches!(mcp_roots(&read_only, &[]), Err(CliError::Usage(_))));
|
|
let roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: vec![path.to_string_lossy().into_owned()] };
|
|
assert!(matches!(mcp_roots(&roots, &[]), Err(CliError::Usage(_))));
|
|
|
|
let roots = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: vec![root] };
|
|
let allowed = mcp_roots(&roots, &[server]).unwrap();
|
|
assert_eq!(allowed.allowed_servers(), ["wss://figcraft.example.com:443/"]);
|
|
|
|
let with_key = "wss://figcraft.example.com/?key=secret".to_string();
|
|
assert!(matches!(mcp_roots(&roots, &[with_key]), Err(CliError::Usage(message)) if !message.contains("secret")));
|
|
let _ = std::fs::remove_dir_all(path);
|
|
}
|
|
}
|