* MCP: compact inspect_design and tool JSON, off by default (--compact / SOLIDCRAFT_MCP_COMPACT) Split out of #2901 per review: the smaller inspect_design changed the default for everyone, so it is now an MCP server option that is off unless asked for. - solidcraft-cli mcp --compact, or SOLIDCRAFT_MCP_COMPACT=1 (true/yes/on; 0/false/no/off/empty leave it off; anything else is an error at start-up). solidcraft_mcp::Options::resolve is the one place that decides, so an app Preferences setting can feed it later. - With it on, inspect_design summarises sketches (id, name, plane, counts of points, curves, constraints and profiles, dof, status), returns full contents only for the sketches named in `sketches` (names/ids, true, false or "summary"), takes a `bodies` filter and measures only those; unknown names list the existing ones. Tool JSON is compact rather than pretty-printed. - Off, tools/list, argument checks, inspect_design and tool JSON are exactly as before. - document.inspect gains an opt-in `sketch_counts` (plane, points, constraints); without it its reply is unchanged. Tests: both modes in the MCP suite, Options parsing, and the CLI flag and variable end to end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * MCP compact output: a Preferences setting too (AI › Agents through MCP) The desktop app's Preferences › AI gets "Compact output" under a new "Agents through MCP" section, off by default and shown with the chat off too. The app reports it on the control channel as `mcp.options` ({"compact": bool}); the agent chat lets its own MCP server read it. A bridged MCP server (`solidcraft-cli mcp --connect`) asks the app when an agent first lists or calls a tool and keeps the answer for the session, so the tools it listed keep their shape. An app not running yet, or busy past 2 s, is asked again on the next call; an app from before the setting counts as off. `--compact` and SOLIDCRAFT_MCP_COMPACT=1 still turn it on whatever the app says. Tests: the server follows the app's answer (waits for it, keeps it, the flag still wins); the checkbox reaches `mcp.options` and Restore Defaults clears it; the chat gate allows `mcp.options`. docs/mcp.md and docs/control-protocol.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * MCP compact output: review fixes (mcp.options never blocks, headless test, locales, prefs doc) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * MCP compact output: the setting is a section of the AI page; the bridged test answers mcp.options Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * MCP compact output: the preference test sets it through ui.prefs; rustfmt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * MCP compact output: look for a newly started app before asking its options; counts from sketch.inspect for an older app Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -18,7 +18,7 @@
|
||||
//! solidcraft-cli oracle <case-dir>... replay recipes and compare with expected.json
|
||||
//! solidcraft-cli kernel-cases [--json] [--dumps=DIR] [--validation=MODE] <case-dir>... the kernel regression rig (tests/kernel-cases)
|
||||
//! solidcraft-cli mcp [--headless] [--in design|script] [--connect HOST:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]
|
||||
//! [--param-check off|warn|strict]
|
||||
//! [--param-check off|warn|strict] [--compact]
|
||||
//! MCP server on stdio (docs/mcp.md)
|
||||
//! solidcraft-cli mcp setup [--dry-run] [--client NAME] [--live] (alias: mcp install) add it to OpenCode, Claude Desktop, Claude Code, Cursor
|
||||
//! solidcraft-cli licences SolidCraft's licence and the third-party licences
|
||||
@@ -91,7 +91,7 @@ const USAGE_KERNEL_CASES: &str = " solidcraft-cli kernel-cases <case-dir>... [-
|
||||
const USAGE_FUZZ: &str =
|
||||
" solidcraft-cli fuzz [--from N] [--count N] [--jobs J] [--timeout S] [--steps N] [--minimise] [--out DIR] [--report FILE]\n";
|
||||
/// `mcp`'s lines in the usage.
|
||||
const USAGE_MCP: &str = " solidcraft-cli mcp [--headless] [--in design.sc|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]\n [--param-check off|warn|strict] [--render-gpu]\n solidcraft-cli mcp setup [--dry-run] [--client opencode|claude-desktop|claude-code|cursor] [--live]\n (adds a `solidcraft` server, with this program's path, to each installed AI client; --live adds `solidcraft-live` for the running app; alias: mcp install)\n";
|
||||
const USAGE_MCP: &str = " solidcraft-cli mcp [--headless] [--in design.sc|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]\n [--param-check off|warn|strict] [--render-gpu] [--compact]\n (--compact, SOLIDCRAFT_MCP_COMPACT=1 or the app's Preferences › AI (with --connect): compact tool output for\n agents: inspect_design summarises sketches and takes `sketches` by name and a `bodies` filter, and tool JSON\n is not pretty-printed; off by default)\n solidcraft-cli mcp setup [--dry-run] [--client opencode|claude-desktop|claude-code|cursor] [--live]\n (adds a `solidcraft` server, with this program's path, to each installed AI client; --live adds `solidcraft-live` for the running app; alias: mcp install)\n";
|
||||
/// `crashes`'s lines in the usage.
|
||||
const USAGE_CRASHES: &str = " solidcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]\n";
|
||||
/// `licences`'s lines in the usage.
|
||||
@@ -792,6 +792,10 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
|
||||
return Err("mcp: --render-gpu installs a headless image host; a connected application owns its own device".into());
|
||||
}
|
||||
install_renderer();
|
||||
let options = solidcraft_mcp::Options::from_args_and_env(args).map_err(|e| format!("mcp: {e}"))?;
|
||||
if options.compact {
|
||||
eprintln!("solidcraft mcp: compact output (inspect_design summarises sketches; tool JSON is not pretty-printed)");
|
||||
}
|
||||
let scope = (!args.iter().any(|a| a == "--allow-any-path"))
|
||||
.then(|| solidcraft_mcp::agent_scope(flags(args, "--allow-path").into_iter().map(std::path::PathBuf::from)));
|
||||
if let Some(s) = &scope {
|
||||
@@ -837,7 +841,7 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
|
||||
if auto && let Some(port) = discover_app() {
|
||||
solidcraft_engine::note!("solidcraft mcp: bridged to the running app at 127.0.0.1:{port} (--headless starts a session of its own)");
|
||||
let remote = solidcraft_mcp::Remote::new(&format!("127.0.0.1:{port}"), flag(args, "--token")).with_param_check(param_check);
|
||||
return serve_mcp(Box::new(remote), scope);
|
||||
return serve_mcp(Box::new(remote), scope, options);
|
||||
}
|
||||
let mut headless = solidcraft_mcp::Headless::default();
|
||||
headless.session.param_check = param_check;
|
||||
@@ -852,13 +856,17 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
};
|
||||
serve_mcp(backend, scope)
|
||||
serve_mcp(backend, scope, options)
|
||||
}
|
||||
|
||||
fn serve_mcp(backend: Box<dyn solidcraft_mcp::Backend>, scope: Option<solidcraft_engine::io::vfs::PathScope>) -> Result<(), String> {
|
||||
fn serve_mcp(
|
||||
backend: Box<dyn solidcraft_mcp::Backend>,
|
||||
scope: Option<solidcraft_engine::io::vfs::PathScope>,
|
||||
options: solidcraft_mcp::Options,
|
||||
) -> Result<(), String> {
|
||||
let stdin = std::io::stdin();
|
||||
let stdout = std::io::stdout();
|
||||
solidcraft_mcp::Server::new(backend).with_path_scope(scope).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
|
||||
solidcraft_mcp::Server::new(backend).with_path_scope(scope).with_options(options).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The port of the running desktop app: the one its discovery file names, if something listens
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//! `mcp --compact` and `SOLIDCRAFT_MCP_COMPACT` turn on compact tool output; without them the
|
||||
//! server's tools are as they always were.
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// `inspect_design`'s input schema as `solidcraft-cli mcp` with `args` and `env` lists it, or
|
||||
/// the server's stderr when it does not start.
|
||||
fn inspect_schema(args: &[&str], env: Option<&str>) -> Result<Value, String> {
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli"));
|
||||
// --headless: never bridge to (and read the preference of) an app the developer has running.
|
||||
cmd.args(["mcp", "--headless", "--allow-any-path"]).args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
match env {
|
||||
Some(v) => cmd.env("SOLIDCRAFT_MCP_COMPACT", v),
|
||||
None => cmd.env_remove("SOLIDCRAFT_MCP_COMPACT"),
|
||||
};
|
||||
let mut child = cmd.spawn().unwrap();
|
||||
{
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
// The server may refuse to start and close stdin first.
|
||||
let _ = writeln!(stdin, "{}", json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}));
|
||||
}
|
||||
let out = child.wait_with_output().unwrap();
|
||||
if !out.status.success() {
|
||||
return Err(String::from_utf8_lossy(&out.stderr).into_owned());
|
||||
}
|
||||
let reply: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
let tools = reply["result"]["tools"].as_array().cloned().unwrap_or_default();
|
||||
Ok(tools.into_iter().find(|t| t["name"] == "inspect_design").map(|t| t["inputSchema"].clone()).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_output_is_off_unless_asked() {
|
||||
let plain = inspect_schema(&[], None).unwrap();
|
||||
assert_eq!(plain["properties"]["sketches"]["type"], "boolean", "{plain}");
|
||||
assert!(plain["properties"].get("bodies").is_none(), "{plain}");
|
||||
assert_eq!(inspect_schema(&[], Some("0")).unwrap(), plain);
|
||||
|
||||
for (args, env) in [(&["--compact"][..], None), (&[][..], Some("1")), (&[][..], Some("true"))] {
|
||||
let compact = inspect_schema(args, env).unwrap();
|
||||
assert!(compact["properties"]["bodies"].is_object(), "{args:?} {env:?}: {compact}");
|
||||
}
|
||||
|
||||
let e = inspect_schema(&[], Some("maybe")).unwrap_err();
|
||||
assert!(e.contains("SOLIDCRAFT_MCP_COMPACT"), "{e}");
|
||||
}
|
||||
@@ -60,15 +60,25 @@ fn mcp_connect_serves_before_the_app_runs_and_reaches_it_once_it_does() {
|
||||
let listener = TcpListener::bind(&addr).unwrap();
|
||||
let app = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(stream.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
let reply = if req["token"] == json!(token) {
|
||||
json!({"id": req["id"], "ok": true, "result": {"bodies": [], "method": req["method"]}})
|
||||
} else {
|
||||
json!({"id": req["id"], "ok": false, "error": format!("unauthorized: token {}", req["token"])})
|
||||
};
|
||||
writeln!(&stream, "{reply}").unwrap();
|
||||
let mut lines = BufReader::new(stream.try_clone().unwrap());
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
lines.read_line(&mut line).unwrap();
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
// The server first asks for the agents' output options (the compact preference: off).
|
||||
let options = req["method"] == "mcp.options";
|
||||
let reply = if req["token"] != json!(token) {
|
||||
json!({"id": req["id"], "ok": false, "error": format!("unauthorized: token {}", req["token"])})
|
||||
} else if options {
|
||||
json!({"id": req["id"], "ok": true, "result": {"compact": false}})
|
||||
} else {
|
||||
json!({"id": req["id"], "ok": true, "result": {"bodies": [], "method": req["method"]}})
|
||||
};
|
||||
writeln!(&stream, "{reply}").unwrap();
|
||||
if !options {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = ask(4, "tools/call", measure);
|
||||
assert_ne!(r["result"]["isError"], true, "{r}");
|
||||
@@ -111,10 +121,21 @@ fn mcp_without_arguments_finds_the_running_app() {
|
||||
break (stream, line);
|
||||
}
|
||||
};
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
let ok = req["token"] == json!(token);
|
||||
let reply = json!({"id": req["id"], "ok": ok, "result": {"bodies": [], "method": req["method"]}, "error": "unauthorized"});
|
||||
writeln!(&stream, "{reply}").unwrap();
|
||||
let mut lines = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut line = line;
|
||||
// The server first asks for the agents' output options (the compact preference: off).
|
||||
loop {
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
let ok = req["token"] == json!(token);
|
||||
let options = req["method"] == "mcp.options";
|
||||
let result = if options { json!({"compact": false}) } else { json!({"bodies": [], "method": req["method"]}) };
|
||||
writeln!(&stream, "{}", json!({"id": req["id"], "ok": ok, "result": result, "error": "unauthorized"})).unwrap();
|
||||
if !options {
|
||||
break;
|
||||
}
|
||||
line.clear();
|
||||
lines.read_line(&mut line).unwrap();
|
||||
}
|
||||
});
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli"))
|
||||
.args(["mcp", "--allow-any-path"])
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"ar": {
|
||||
"ui.mcp_agents": "الوكلاء عبر MCP",
|
||||
"ui.mcp_compact": "مخرجات مضغوطة",
|
||||
"ui.mcp_compact_note": "للوكلاء المتصلين عبر خادم MCP (solidcraft-cli mcp): يلخّص inspect_design الرسومات، ولا تُنسَّق نتائج الأدوات، فتستهلك رموزًا أقل. يسري على جلسات الوكلاء التي تبدأ بعد التغيير؛ ويفعّله أيضًا --compact أو SOLIDCRAFT_MCP_COMPACT=1."
|
||||
},
|
||||
"de": {
|
||||
"ui.mcp_agents": "Agenten über MCP",
|
||||
"ui.mcp_compact": "Kompakte Ausgabe",
|
||||
"ui.mcp_compact_note": "Für Agenten, die über den MCP-Server (solidcraft-cli mcp) verbunden sind: inspect_design fasst Skizzen zusammen und Werkzeugergebnisse werden nicht formatiert, sodass sie weniger Tokens verbrauchen. Gilt für Agentensitzungen, die nach der Änderung beginnen; --compact oder SOLIDCRAFT_MCP_COMPACT=1 schalten es ebenfalls ein."
|
||||
},
|
||||
"en": {
|
||||
"ui.mcp_agents": "Agents through MCP",
|
||||
"ui.mcp_compact": "Compact output",
|
||||
"ui.mcp_compact_note": "For agents connected through the MCP server (solidcraft-cli mcp): inspect_design summarises sketches and tool results are not pretty-printed, so they use fewer tokens. Applies to agent sessions started after the change; --compact or SOLIDCRAFT_MCP_COMPACT=1 also turn it on."
|
||||
},
|
||||
"he": {
|
||||
"ui.mcp_agents": "סוכנים דרך MCP",
|
||||
"ui.mcp_compact": "פלט מקוצר",
|
||||
"ui.mcp_compact_note": "לסוכנים שמחוברים דרך שרת ה-MCP (solidcraft-cli mcp): inspect_design מסכם סקיצות ותוצאות הכלים אינן מעוצבות, כך שהן צורכות פחות טוקנים. חל על הפעלות סוכן שמתחילות אחרי השינוי; גם --compact או SOLIDCRAFT_MCP_COMPACT=1 מפעילים אותו."
|
||||
},
|
||||
"ja": {
|
||||
"ui.mcp_agents": "MCP 経由のエージェント",
|
||||
"ui.mcp_compact": "コンパクトな出力",
|
||||
"ui.mcp_compact_note": "MCP サーバー (solidcraft-cli mcp) 経由で接続したエージェント向け: inspect_design はスケッチを要約し、ツールの結果は整形されないため、トークンが少なくて済みます。変更後に開始したエージェントのセッションから適用されます。--compact または SOLIDCRAFT_MCP_COMPACT=1 でも有効になります。"
|
||||
},
|
||||
"ko": {
|
||||
"ui.mcp_agents": "MCP를 통한 에이전트",
|
||||
"ui.mcp_compact": "간결한 출력",
|
||||
"ui.mcp_compact_note": "MCP 서버(solidcraft-cli mcp)로 연결된 에이전트용: inspect_design이 스케치를 요약하고 도구 결과를 보기 좋게 정렬하지 않아 토큰을 덜 사용합니다. 변경 후 시작한 에이전트 세션부터 적용됩니다. --compact 또는 SOLIDCRAFT_MCP_COMPACT=1로도 켤 수 있습니다."
|
||||
},
|
||||
"vi": {
|
||||
"ui.mcp_agents": "Tác tử qua MCP",
|
||||
"ui.mcp_compact": "Đầu ra gọn",
|
||||
"ui.mcp_compact_note": "Dành cho các tác tử kết nối qua máy chủ MCP (solidcraft-cli mcp): inspect_design tóm tắt các bản phác thảo và kết quả công cụ không được định dạng đẹp, nên tốn ít token hơn. Áp dụng cho các phiên tác tử bắt đầu sau khi thay đổi; --compact hoặc SOLIDCRAFT_MCP_COMPACT=1 cũng bật nó."
|
||||
},
|
||||
"zh": {
|
||||
"ui.mcp_agents": "通过 MCP 连接的代理",
|
||||
"ui.mcp_compact": "紧凑输出",
|
||||
"ui.mcp_compact_note": "适用于通过 MCP 服务器 (solidcraft-cli mcp) 连接的代理:inspect_design 汇总草图,工具结果不做美化排版,从而占用更少的 token。更改后新开始的代理会话生效;--compact 或 SOLIDCRAFT_MCP_COMPACT=1 也会开启它。"
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.key("I")
|
||||
.noundo()
|
||||
.params("bodies?: [names] (default all); names_only?: bool (each world body's name and its definition's, nothing measured) → closed per body; volume_mm3, center_of_mass, density_g_cm3 and mass_g only for closed, consistently oriented bodies; area, bbox and counts for all; total.open_bodies_skipped counts bodies excluded from volume/mass totals; or items: [1-2 selections] (face/edge: type, body, point; index optional) → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"),
|
||||
CommandSpec::new("document.inspect", "Inspect Design", inspect).icon("inspect").noundo().params("measure?: bool (include body measurements)"),
|
||||
CommandSpec::new("document.inspect", "Inspect Design", inspect).icon("inspect").noundo().params("measure?: bool (include body measurements); sketch_counts?: bool (each sketch also gives its plane and its number of points and constraints)"),
|
||||
CommandSpec::new("document.revision", "Design Revision", revision).icon("inspect").noundo().params(
|
||||
"→ document_id (this open design's id: kept while it stays open, another for each design started or opened), \
|
||||
revision (moves whenever the design, what is hidden or a component's uncaptured position changes, \
|
||||
@@ -399,6 +399,7 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect();
|
||||
let definitions = s.model.state();
|
||||
let with_measure = bool_(p, "measure").unwrap_or(false);
|
||||
let with_counts = bool_(p, "sketch_counts").unwrap_or(false);
|
||||
// Each body is measured on its own: on all cores, in body order (as `inspect.measure`).
|
||||
let mut measured =
|
||||
if with_measure { solidcraft_kernel::map_on_threads(&st.bodies, 16, |b| measure_sheet_json(b, Some(&definitions))) } else { Vec::new() }
|
||||
@@ -424,7 +425,16 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sketches: Vec<Value> = st
|
||||
.sketches
|
||||
.iter()
|
||||
.map(|ss| json!({"id": ss.feature, "name": ss.name, "dof": ss.report.dof, "status": ss.report.status, "curves": ss.sketch.curves.len(), "profiles": ss.profiles.len(), "visible": crate::view::sketch_shown(s, ss.feature)}))
|
||||
.map(|ss| {
|
||||
let mut v = json!({"id": ss.feature, "name": ss.name, "dof": ss.report.dof, "status": ss.report.status, "curves": ss.sketch.curves.len(), "profiles": ss.profiles.len(), "visible": crate::view::sketch_shown(s, ss.feature)});
|
||||
// A summary that stands in for the sketch's contents (the compact MCP inspect_design).
|
||||
if with_counts && let Some(o) = v.as_object_mut() {
|
||||
o.insert("plane".into(), json!(ss.plane));
|
||||
o.insert("points".into(), json!(ss.sketch.points.len()));
|
||||
o.insert("constraints".into(), json!(ss.sketch.constraints.len()));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"name": s.doc.name, "units": s.doc.units, "metadata": s.doc.metadata, "path": s.path, "dirty": s.is_dirty(), "revision": s.revision,
|
||||
|
||||
@@ -41,6 +41,13 @@ pub trait Backend {
|
||||
fn param_check(&self) -> ParamCheck {
|
||||
ParamCheck::Off
|
||||
}
|
||||
/// The output options the app's Preferences ask for (its `mcp.options` reply), for a backend
|
||||
/// bridged to the app. `Ok(None)`: nothing to ask (no app, or one from before the setting), so
|
||||
/// the server's own options decide; `Err`: the app could not answer now (not running, busy),
|
||||
/// ask again on a later call.
|
||||
fn app_options(&mut self) -> Result<Option<Value>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest reply line accepted from the app.
|
||||
@@ -49,6 +56,10 @@ const MAX_REPLY: u64 = 64 << 20;
|
||||
/// How long a reply may take: kernel operations (booleans, fillets) on big parts can take a while.
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
/// How long the app may take to answer `mcp.options`: the window answers it within a frame, so a
|
||||
/// longer wait means the app is busy and the server asks again on a later call.
|
||||
const OPTIONS_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// How long the app may take to run an `engine.batch`: a little longer than its control server
|
||||
/// waits (3600 s), so its "still running" reply arrives first.
|
||||
const BATCH_TIMEOUT: Duration = Duration::from_secs(3720);
|
||||
@@ -633,6 +644,34 @@ impl Backend for Remote {
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn app_options(&mut self) -> Result<Option<Value>, String> {
|
||||
// This runs on the serve loop before a tool call, so it never waits: not behind a request
|
||||
// still running (ask again on a later call), and one try with no retry, because a retry
|
||||
// reconnects with READ_TIMEOUT and could block for minutes.
|
||||
if self.outstanding.is_some() {
|
||||
return Err("a request is still running in the app".into());
|
||||
}
|
||||
if self.conn.is_none() {
|
||||
self.reconnect().map_err(|e| self.explain(&e))?;
|
||||
}
|
||||
let line = self.request_line("mcp.options", json!({}));
|
||||
self.set_read_timeout(OPTIONS_TIMEOUT);
|
||||
let reply = self.roundtrip(&line);
|
||||
self.set_read_timeout(READ_TIMEOUT);
|
||||
let reply = reply.map_err(|e| self.explain(&e))?;
|
||||
let v: Value = serde_json::from_str(&reply).map_err(|e| format!("bad reply from the app: {e}"))?;
|
||||
let r = outcome(&v).map_err(|error| {
|
||||
solidcraft_engine::control_auth::client_token(self.port, self.explicit_token.as_deref())
|
||||
.map_or_else(|| error.clone(), |t| t.explain_error(&error))
|
||||
});
|
||||
match r {
|
||||
Ok(v) => Ok(Some(v)),
|
||||
// An app from before the setting (its agent chat refuses methods it doesn't know):
|
||||
// the server's own options decide.
|
||||
Err(e) if e.starts_with("unknown method") || e.contains("is not available in the agent chat") => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
if self.conn.is_some() {
|
||||
format!("connected to the SolidCraft app at {} (the user watches the viewport)", self.addr)
|
||||
@@ -911,6 +950,17 @@ impl Backend for Auto {
|
||||
(None, None) => ParamCheck::Off,
|
||||
}
|
||||
}
|
||||
fn app_options(&mut self) -> Result<Option<Value>, String> {
|
||||
// The app may have started since: bridge to it first, as a tool call would.
|
||||
if self.remote.is_none() {
|
||||
self.look_for_app();
|
||||
}
|
||||
match &mut self.remote {
|
||||
Some(r) => r.app_options(),
|
||||
// Headless for now: the app may yet start, so ask again on a later call.
|
||||
None => Err("no app yet".into()),
|
||||
}
|
||||
}
|
||||
fn notice(&self) -> Option<String> {
|
||||
self.headless.as_ref().map(|_| {
|
||||
"Note: this is a headless session because the SolidCraft app was not found; the user cannot see this work. \
|
||||
|
||||
@@ -10,13 +10,15 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod backend;
|
||||
mod options;
|
||||
mod server;
|
||||
mod skill_reference;
|
||||
mod tools;
|
||||
|
||||
pub use backend::{Auto, Backend, Headless, Remote};
|
||||
pub use options::{COMPACT_ENV, COMPACT_FLAG, Options};
|
||||
pub use server::{PROTOCOL_VERSION, SUPPORTED_VERSIONS, Server};
|
||||
pub use tools::{call_tool, tool_definitions};
|
||||
pub use tools::{call_tool, call_tool_with, tool_definitions, tool_definitions_with};
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! How the MCP server shapes what its tools return. Off by default: every option keeps the
|
||||
//! behaviour the server had before it. Two places turn an option on: the server's own command
|
||||
//! line and environment ([`Options::resolve`]), and, when the server is bridged to the app, the
|
||||
//! app's Preferences (AI › MCP agents), which it reports as `mcp.options` ([`Options::from_app`]).
|
||||
//! Either one is enough ([`Options::or`]).
|
||||
|
||||
/// The environment variable that turns on compact output: `1`, `true`, `yes` or `on`
|
||||
/// (`0`, `false`, `no`, `off` or empty: off). `solidcraft-cli mcp --compact` does the same.
|
||||
pub const COMPACT_ENV: &str = "SOLIDCRAFT_MCP_COMPACT";
|
||||
|
||||
/// The command-line flag that turns on compact output.
|
||||
pub const COMPACT_FLAG: &str = "--compact";
|
||||
|
||||
/// Output options of the MCP server.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Options {
|
||||
/// Compact output for agents that pay for every byte: `inspect_design` summarises sketches
|
||||
/// (full contents only for the sketches named in `sketches`) and takes a `bodies` filter, and
|
||||
/// tool results that are JSON are not pretty-printed. Off: `inspect_design` returns every
|
||||
/// sketch in full, and JSON is pretty-printed.
|
||||
pub compact: bool,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// The options from the command line's `--compact` and the value of [`COMPACT_ENV`]: either
|
||||
/// turns compact output on. An unrecognised value is an error, so a typo is not silently off.
|
||||
pub fn resolve(flag: bool, env: Option<&str>) -> Result<Self, String> {
|
||||
let from_env = match env.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
|
||||
None | Some("" | "0" | "false" | "no" | "off") => false,
|
||||
Some("1" | "true" | "yes" | "on") => true,
|
||||
Some(other) => return Err(format!("{COMPACT_ENV} must be 1 or 0 (true/false, yes/no, on/off), not `{other}`")),
|
||||
};
|
||||
Ok(Self { compact: flag || from_env })
|
||||
}
|
||||
|
||||
/// [`Options::resolve`] with this process's command-line arguments (`args`, after the
|
||||
/// subcommand) and environment.
|
||||
pub fn from_args_and_env(args: &[String]) -> Result<Self, String> {
|
||||
Self::resolve(args.iter().any(|a| a == COMPACT_FLAG), std::env::var(COMPACT_ENV).ok().as_deref())
|
||||
}
|
||||
|
||||
/// The options the app reports in its `mcp.options` reply (`{"compact": bool}`); a field
|
||||
/// missing or of another type is off.
|
||||
pub fn from_app(reply: &serde_json::Value) -> Self {
|
||||
Self { compact: reply.get("compact").and_then(serde_json::Value::as_bool).unwrap_or(false) }
|
||||
}
|
||||
|
||||
/// Each option on when it is on in `self` or in `other`.
|
||||
pub fn or(self, other: Self) -> Self {
|
||||
Self { compact: self.compact || other.compact }
|
||||
}
|
||||
|
||||
/// Tool JSON as text: compact, or pretty-printed (the default).
|
||||
pub(crate) fn json_text(self, v: &serde_json::Value) -> String {
|
||||
if self.compact { v.to_string() } else { serde_json::to_string_pretty(v).unwrap_or_default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn off_unless_asked() {
|
||||
assert_eq!(Options::default(), Options { compact: false });
|
||||
assert_eq!(Options::resolve(false, None), Ok(Options { compact: false }));
|
||||
for v in ["", "0", "false", "No", " off "] {
|
||||
assert_eq!(Options::resolve(false, Some(v)), Ok(Options { compact: false }), "{v:?}");
|
||||
}
|
||||
for v in ["1", "true", "YES", "on"] {
|
||||
assert_eq!(Options::resolve(false, Some(v)), Ok(Options { compact: true }), "{v:?}");
|
||||
}
|
||||
assert_eq!(Options::resolve(true, None), Ok(Options { compact: true }));
|
||||
assert_eq!(Options::resolve(true, Some("0")), Ok(Options { compact: true }), "the flag wins");
|
||||
assert!(Options::resolve(false, Some("maybe")).is_err_and(|e| e.contains(COMPACT_ENV)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_app_or_the_command_line_turns_it_on() {
|
||||
let off = Options::default();
|
||||
let on = Options { compact: true };
|
||||
assert_eq!(Options::from_app(&serde_json::json!({"compact": true})), on);
|
||||
for reply in [serde_json::json!({}), serde_json::json!({"compact": "yes"}), serde_json::json!(null), serde_json::json!({"compact": false})] {
|
||||
assert_eq!(Options::from_app(&reply), off, "{reply}");
|
||||
}
|
||||
assert_eq!(off.or(off), off);
|
||||
assert_eq!(off.or(on), on);
|
||||
assert_eq!(on.or(off), on);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ use solidcraft_engine::MAX_LINE;
|
||||
use solidcraft_engine::io::vfs::{self, PathScope};
|
||||
|
||||
use crate::backend::Backend;
|
||||
use crate::tools::{call_tool, check_arguments, tool_definitions};
|
||||
use crate::options::Options;
|
||||
use crate::tools::{call_tool_with, check_arguments_with, tool_definitions_with};
|
||||
|
||||
/// The newest protocol revision we speak; offered when the client asks for one we don't know.
|
||||
pub const PROTOCOL_VERSION: &str = "2025-06-18";
|
||||
@@ -61,6 +62,10 @@ pub struct Server {
|
||||
backend: Box<dyn Backend>,
|
||||
initialized: bool,
|
||||
scope: Option<PathScope>,
|
||||
/// The options from the command line and environment.
|
||||
options: Options,
|
||||
/// The options the app's Preferences ask for, once it has answered (`None`: not yet).
|
||||
app_options: Option<Options>,
|
||||
}
|
||||
|
||||
/// The design files a call opens or saves (#7181): `open` and `save`, and the commands they run
|
||||
@@ -95,7 +100,7 @@ fn error(id: Value, code: i64, message: impl Into<String>) -> Value {
|
||||
|
||||
impl Server {
|
||||
pub fn new(backend: Box<dyn Backend>) -> Self {
|
||||
Self { backend, initialized: false, scope: None }
|
||||
Self { backend, initialized: false, scope: None, options: Options::default(), app_options: None }
|
||||
}
|
||||
/// Confine the files tool calls may reach to `scope` (`None`: anywhere). `solidcraft-cli mcp`
|
||||
/// always sets one unless started with `--allow-any-path` (docs/mcp.md).
|
||||
@@ -103,6 +108,24 @@ impl Server {
|
||||
self.scope = scope;
|
||||
self
|
||||
}
|
||||
/// Shape tool output with `options` (default: as always; `solidcraft-cli mcp --compact` or
|
||||
/// `SOLIDCRAFT_MCP_COMPACT=1` turn on compact output, docs/mcp.md). The app's Preferences can
|
||||
/// turn an option on too ([`Server::options`]).
|
||||
pub fn with_options(mut self, options: Options) -> Self {
|
||||
self.options = options;
|
||||
self
|
||||
}
|
||||
/// The options tools use now: the server's own, with what the app's Preferences turn on. The
|
||||
/// app is asked until it answers once (it may start after the server, or be busy), and its
|
||||
/// answer then holds for this session, so the tools an agent listed keep their shape.
|
||||
pub fn options(&mut self) -> Options {
|
||||
if self.app_options.is_none()
|
||||
&& let Ok(reply) = self.backend.app_options()
|
||||
{
|
||||
self.app_options = Some(reply.as_ref().map(Options::from_app).unwrap_or_default());
|
||||
}
|
||||
self.options.or(self.app_options.unwrap_or_default())
|
||||
}
|
||||
pub fn backend(&mut self) -> &mut dyn Backend {
|
||||
self.backend.as_mut()
|
||||
}
|
||||
@@ -220,21 +243,22 @@ impl Server {
|
||||
}))
|
||||
}
|
||||
"ping" => Ok(json!({})),
|
||||
"tools/list" => Ok(json!({"tools": tool_definitions()})),
|
||||
"tools/list" => Ok(json!({"tools": tool_definitions_with(self.options())})),
|
||||
"tools/call" => {
|
||||
let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing tool `name`".to_string()))?;
|
||||
let args = match params.get("arguments") {
|
||||
None | Some(Value::Null) => json!({}),
|
||||
Some(a) => a.clone(),
|
||||
};
|
||||
check_arguments(name, &args).map_err(|e| (INVALID_PARAMS, e))?;
|
||||
let options = self.options();
|
||||
check_arguments_with(name, &args, options).map_err(|e| (INVALID_PARAMS, e))?;
|
||||
// The open design's folder counts, and goes on counting for the rest of this run
|
||||
// when a save-as or open moves the design elsewhere (#7181).
|
||||
let open = self.backend.design_path();
|
||||
self.scope = self.scope.take().map(|s| s.with_design(open.as_deref()));
|
||||
let scope = self.scope.clone();
|
||||
let backend = self.backend.as_mut();
|
||||
let mut result = vfs::scoped(scope, || call_tool(backend, name, &args));
|
||||
let mut result = vfs::scoped(scope, || call_tool_with(backend, name, &args, options));
|
||||
// So does the folder of each design file the call opened or saved: the call reached
|
||||
// it, so it was one of the agent's folders already. Only paths given in full: a
|
||||
// running app resolves a relative one against its own working folder.
|
||||
|
||||
@@ -3585,6 +3585,8 @@ fn a_bridged_server_leaves_the_check_to_an_app_that_makes_it() {
|
||||
let level = req["params"]["param_check"].clone();
|
||||
match req["method"].as_str() {
|
||||
Some("control.capabilities") => json!({"ok": true, "result": {"param_check": ["off", "warn", "strict"]}}),
|
||||
// The server's own question, not a tool call: it carries no level.
|
||||
Some("mcp.options") => json!({"ok": true, "result": {"compact": false}}),
|
||||
Some("engine.batch") => {
|
||||
log.lock().unwrap().push(level.clone());
|
||||
json!({"ok": true, "result": {"completed": 1, "results": [{"param_warnings": ["the app's own"]}], "undone": 0}, "param_check": level})
|
||||
@@ -3692,3 +3694,169 @@ fn plain_headless_adds_no_notice() {
|
||||
let r = raw_tool(&mut s, "list_commands", json!({}));
|
||||
assert_eq!(r["result"]["content"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
/// A design with one 720-point sketch extruded into Body1, on a server with these options.
|
||||
fn server_with_big_sketch(options: crate::Options) -> Server {
|
||||
let mut s = Server::new(Box::new(Headless::default())).with_options(options);
|
||||
let points: Vec<[f64; 2]> = (0..720)
|
||||
.map(|i| {
|
||||
let t = f64::from(i) / 720.0 * std::f64::consts::TAU;
|
||||
[30.0 * t.cos(), 30.0 * t.sin()]
|
||||
})
|
||||
.collect();
|
||||
tool(
|
||||
&mut s,
|
||||
"batch",
|
||||
json!({"commands": [
|
||||
{"command": "sketch.create", "params": {"plane": "XY"}},
|
||||
{"command": "sketch.line", "params": {"points": points, "closed": true}},
|
||||
{"command": "sketch.finish"},
|
||||
{"command": "solid.extrude", "params": {"distance": 5}},
|
||||
]}),
|
||||
);
|
||||
s
|
||||
}
|
||||
|
||||
/// `inspect_design`'s text and error flag.
|
||||
fn inspect_text(s: &mut Server, args: Value) -> (bool, String) {
|
||||
let r = raw_tool(s, "inspect_design", args);
|
||||
(r["result"]["isError"] == json!(true), r["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// Off by default: `inspect_design` has its old arguments and returns every sketch in full,
|
||||
/// pretty-printed; `document.inspect` adds no sketch counts unless asked.
|
||||
#[test]
|
||||
fn inspect_design_is_unchanged_without_compact_output() {
|
||||
let mut s = server_with_big_sketch(crate::Options::default());
|
||||
let defs = tool_definitions();
|
||||
let def = defs.iter().find(|d| d["name"] == "inspect_design").unwrap();
|
||||
assert_eq!(def["inputSchema"]["properties"]["sketches"]["type"], "boolean", "{def}");
|
||||
assert!(def["inputSchema"]["properties"].get("bodies").is_none(), "{def}");
|
||||
let listed = call(&mut s, 1, "tools/list", json!({}));
|
||||
assert!(listed["result"]["tools"].as_array().unwrap().iter().any(|t| t == def), "tools/list serves the default definition");
|
||||
|
||||
let (err, full) = inspect_text(&mut s, json!({"measure": false}));
|
||||
assert!(!err && full.contains("\n "), "pretty-printed");
|
||||
let d: Value = serde_json::from_str(&full).unwrap();
|
||||
assert_eq!(d["sketches"][0]["curves"].as_array().map(Vec::len), Some(720), "full sketch contents by default");
|
||||
let (_, summary) = inspect_text(&mut s, json!({"measure": false, "sketches": false}));
|
||||
let d: Value = serde_json::from_str(&summary).unwrap();
|
||||
assert_eq!(d["sketches"][0]["curves"], 720, "{d}");
|
||||
assert!(d["sketches"][0].get("points").is_none() && d["sketches"][0].get("plane").is_none(), "{d}");
|
||||
|
||||
// The compact arguments are not there.
|
||||
let r = raw_tool(&mut s, "inspect_design", json!({"bodies": ["Body1"]}));
|
||||
assert_eq!(r["error"]["code"], -32602, "{r}");
|
||||
let r = raw_tool(&mut s, "inspect_design", json!({"sketches": ["Sketch1"]}));
|
||||
assert_eq!(r["error"]["code"], -32602, "{r}");
|
||||
}
|
||||
|
||||
/// With compact output (#15): sketch summaries, compact JSON; full sketch contents only for the
|
||||
/// sketches asked for; `bodies` keeps only those bodies.
|
||||
#[test]
|
||||
fn compact_inspect_design_summarises_sketches_unless_asked() {
|
||||
let mut s = server_with_big_sketch(crate::Options { compact: true });
|
||||
let listed = call(&mut s, 1, "tools/list", json!({}));
|
||||
let def = listed["result"]["tools"].as_array().unwrap().iter().find(|d| d["name"] == "inspect_design").cloned().unwrap();
|
||||
assert!(def["inputSchema"]["properties"]["bodies"].is_object(), "{def}");
|
||||
assert_eq!(def, crate::tool_definitions_with(crate::Options { compact: true }).into_iter().find(|d| d["name"] == "inspect_design").unwrap());
|
||||
// Arguments are checked against the tools as listed: `bodies` only with compact output.
|
||||
let bodies = json!({"bodies": ["Body1"]});
|
||||
assert!(crate::tools::check_arguments_with("inspect_design", &bodies, crate::Options { compact: true }).is_ok());
|
||||
assert!(crate::tools::check_arguments("inspect_design", &bodies).is_err_and(|e| e.contains("bodies")));
|
||||
|
||||
let (_, summary) = inspect_text(&mut s, json!({"measure": false}));
|
||||
assert!(summary.len() < 4000, "{} bytes: {summary}", summary.len());
|
||||
assert!(!summary.contains("\n "), "compact JSON");
|
||||
let d: Value = serde_json::from_str(&summary).unwrap();
|
||||
let sk = &d["sketches"][0];
|
||||
assert!(sk["points"].as_u64().is_some_and(|n| n >= 720), "{sk}");
|
||||
assert_eq!((&sk["curves"], &sk["profiles"]), (&json!(720), &json!(1)), "{sk}");
|
||||
assert!(sk["constraints"].is_u64() && sk["dof"].is_number() && sk["plane"].is_object(), "{sk}");
|
||||
assert_eq!(inspect_text(&mut s, json!({"measure": false, "sketches": false})).1, summary);
|
||||
assert_eq!(inspect_text(&mut s, json!({"measure": false, "sketches": "summary"})).1, summary);
|
||||
let name = sk["name"].as_str().unwrap().to_string();
|
||||
let (_, full) = inspect_text(&mut s, json!({"measure": false, "sketches": [name]}));
|
||||
assert!(full.len() > 50_000 && full.len() > 20 * summary.len(), "{} vs {}", full.len(), summary.len());
|
||||
let f: Value = serde_json::from_str(&full).unwrap();
|
||||
assert_eq!(f["sketches"][0]["curves"].as_array().map(Vec::len), Some(720));
|
||||
assert_eq!(inspect_text(&mut s, json!({"measure": false, "sketches": true})).1.len(), full.len());
|
||||
let (err, e) = inspect_text(&mut s, json!({"sketches": ["Nope"]}));
|
||||
assert!(err && e.contains("no sketch") && e.contains(&name), "{e}");
|
||||
|
||||
let (_, one) = inspect_text(&mut s, json!({"bodies": ["Body1"]}));
|
||||
let one: Value = serde_json::from_str(&one).unwrap();
|
||||
assert_eq!(one["bodies"].as_array().map(Vec::len), Some(1), "{one}");
|
||||
assert!(one["bodies"][0]["volume_mm3"].as_f64().is_some_and(|v| v > 0.0) && one["bodies"][0]["visible"] == true, "{one}");
|
||||
let (err, e) = inspect_text(&mut s, json!({"bodies": ["Nope"]}));
|
||||
assert!(err && e.contains("no body `Nope`") && e.contains("Body1"), "{e}");
|
||||
|
||||
// Other tools' JSON is compact too.
|
||||
let r = raw_tool(&mut s, "measure", json!({}));
|
||||
let text = r["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(!text.contains('\n') && serde_json::from_str::<Value>(text).is_ok(), "{text}");
|
||||
}
|
||||
|
||||
/// A headless design behind an "app" whose `mcp.options` answers are `replies`, one per question
|
||||
/// (the last one repeats), counting the questions in `asked`.
|
||||
struct AppWithPrefs {
|
||||
inner: Headless,
|
||||
replies: Vec<Result<Option<Value>, String>>,
|
||||
asked: std::rc::Rc<std::cell::Cell<usize>>,
|
||||
}
|
||||
|
||||
impl crate::Backend for AppWithPrefs {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
self.inner.call(method, params)
|
||||
}
|
||||
fn has_ui(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
"test app".into()
|
||||
}
|
||||
fn app_options(&mut self) -> Result<Option<Value>, String> {
|
||||
let n = self.asked.get();
|
||||
self.asked.set(n + 1);
|
||||
self.replies.get(n).or(self.replies.last()).cloned().unwrap_or(Ok(None))
|
||||
}
|
||||
}
|
||||
|
||||
fn inspect_design_is_compact(s: &mut Server) -> bool {
|
||||
let listed = call(s, 1, "tools/list", json!({}));
|
||||
let def = listed["result"]["tools"].as_array().and_then(|t| t.iter().find(|d| d["name"] == "inspect_design")).cloned().unwrap_or_default();
|
||||
def["inputSchema"]["properties"]["bodies"].is_object()
|
||||
}
|
||||
|
||||
/// The app's Preferences turn compact output on for a bridged server; it asks until the app
|
||||
/// answers once (here: not running at first), then keeps that answer for the session.
|
||||
#[test]
|
||||
fn compact_output_follows_the_apps_preference() {
|
||||
let asked = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let app = |replies: Vec<Result<Option<Value>, String>>| {
|
||||
Box::new(AppWithPrefs { inner: Headless::default(), replies, asked: asked.clone() }) as Box<dyn crate::Backend>
|
||||
};
|
||||
let not_running = Err(format!("{} 127.0.0.1:7878 (refused)", crate::backend::NOT_RUNNING));
|
||||
|
||||
let mut s = Server::new(app(vec![not_running.clone(), Ok(Some(json!({"compact": true}))), Ok(Some(json!({"compact": false})))]));
|
||||
assert!(!inspect_design_is_compact(&mut s), "not known yet: the server's own options (off)");
|
||||
assert!(inspect_design_is_compact(&mut s), "the app answered: compact");
|
||||
assert!(inspect_design_is_compact(&mut s), "kept for the session");
|
||||
let r = raw_tool(&mut s, "measure", json!({}));
|
||||
assert!(!r["result"]["content"][0]["text"].as_str().unwrap_or("\n").contains('\n'), "tool calls follow it too: {r}");
|
||||
assert_eq!(asked.get(), 2, "not asked again once answered");
|
||||
|
||||
// An app from before the setting, or with it off: off.
|
||||
asked.set(0);
|
||||
let mut s = Server::new(app(vec![Ok(None)]));
|
||||
assert!(!inspect_design_is_compact(&mut s) && !inspect_design_is_compact(&mut s));
|
||||
assert_eq!(asked.get(), 1);
|
||||
let mut s = Server::new(app(vec![Ok(Some(json!({"compact": false})))]));
|
||||
assert!(!inspect_design_is_compact(&mut s));
|
||||
|
||||
// The command line turns it on whatever the app says.
|
||||
let mut s = Server::new(app(vec![Ok(Some(json!({"compact": false})))])).with_options(crate::Options { compact: true });
|
||||
assert!(inspect_design_is_compact(&mut s));
|
||||
let mut s = Server::new(app(vec![not_running])).with_options(crate::Options { compact: true });
|
||||
assert!(inspect_design_is_compact(&mut s));
|
||||
}
|
||||
|
||||
+220
-56
@@ -8,6 +8,7 @@ use solidcraft_engine::io::vfs;
|
||||
use solidcraft_engine::timing;
|
||||
|
||||
use crate::backend::{Backend, STILL_RUNNING};
|
||||
use crate::options::Options;
|
||||
|
||||
/// Most commands in one `batch` call.
|
||||
const MAX_BATCH: usize = 10_000;
|
||||
@@ -92,8 +93,15 @@ fn expect_schema() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// Every tool, with its JSON schema. The same list serves the headless and the bridged backend.
|
||||
/// Every tool, with its JSON schema, as the server has them by default. The same list serves the
|
||||
/// headless and the bridged backend.
|
||||
pub fn tool_definitions() -> Vec<Value> {
|
||||
tool_definitions_with(Options::default())
|
||||
}
|
||||
|
||||
/// Every tool, with its JSON schema, for these [`Options`] (`compact` changes `inspect_design`'s
|
||||
/// arguments).
|
||||
pub fn tool_definitions_with(opts: Options) -> Vec<Value> {
|
||||
vec![
|
||||
tool(
|
||||
"list_commands",
|
||||
@@ -192,25 +200,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
),
|
||||
Effect::Files,
|
||||
),
|
||||
tool(
|
||||
"inspect_design",
|
||||
"Inspect the design",
|
||||
"The whole design: user parameters (expression, value, errors), the timeline (features with type, suppressed, \
|
||||
rolled back, error, warning, timing), bodies (volume, area, centre of mass, bounding box, face/edge/vertex \
|
||||
counts), sketches (curves with ids and coordinates, points, constraints, profiles, degrees of freedom, solve \
|
||||
status), assembly joints (what each origin is attached to: occurrence, the feature, face, edge or sketch \
|
||||
curve its face names refer to, whether it resolves and why not; `execute` `joint.inspect {joint}` gives one), \
|
||||
the active sketch, selection and undo depth.",
|
||||
obj(
|
||||
json!({
|
||||
"measure": {"type": "boolean", "description": "Measure bodies (default true)"},
|
||||
"sketches": {"type": "boolean", "description": "Full sketch contents (default true; false = summary only)"},
|
||||
"joints": {"type": "boolean", "description": "Joint definitions as joint.inspect gives them, when the design has joints (default true)"},
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
Effect::ReadOnly,
|
||||
),
|
||||
inspect_design_tool(opts),
|
||||
tool(
|
||||
"measure",
|
||||
"Measure bodies",
|
||||
@@ -470,6 +460,57 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
]
|
||||
}
|
||||
|
||||
/// `inspect_design`'s definition: as it always was, or with compact output its sketch summaries,
|
||||
/// `sketches` by name and the `bodies` filter.
|
||||
fn inspect_design_tool(opts: Options) -> Value {
|
||||
if !opts.compact {
|
||||
return tool(
|
||||
"inspect_design",
|
||||
"Inspect the design",
|
||||
"The whole design: user parameters (expression, value, errors), the timeline (features with type, suppressed, \
|
||||
rolled back, error, warning, timing), bodies (volume, area, centre of mass, bounding box, face/edge/vertex \
|
||||
counts), sketches (curves with ids and coordinates, points, constraints, profiles, degrees of freedom, solve \
|
||||
status), assembly joints (what each origin is attached to: occurrence, the feature, face, edge or sketch \
|
||||
curve its face names refer to, whether it resolves and why not; `execute` `joint.inspect {joint}` gives one), \
|
||||
the active sketch, selection and undo depth.",
|
||||
obj(
|
||||
json!({
|
||||
"measure": {"type": "boolean", "description": "Measure bodies (default true)"},
|
||||
"sketches": {"type": "boolean", "description": "Full sketch contents (default true; false = summary only)"},
|
||||
"joints": {"type": "boolean", "description": "Joint definitions as joint.inspect gives them, when the design has joints (default true)"},
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
Effect::ReadOnly,
|
||||
);
|
||||
}
|
||||
tool(
|
||||
"inspect_design",
|
||||
"Inspect the design",
|
||||
"The whole design: user parameters (expression, value, errors), the timeline (features with type, suppressed, \
|
||||
rolled back, error, warning, timing), bodies (volume, area, centre of mass, bounding box, face/edge/vertex \
|
||||
counts), sketches, the active sketch, selection and undo depth. Sketches are summarised by default (id, name, \
|
||||
plane, counts of points, curves, constraints and profiles, degrees of freedom, solve status); their full contents \
|
||||
(curves with ids and coordinates, points, constraints, profiles) only for the sketches named in `sketches`, or \
|
||||
all with `sketches: true` (large: a 720-point sketch is some 200 KB). Assembly joints: what each origin is \
|
||||
attached to (`execute` `joint.inspect {joint}` gives one). Arguments: measure, sketches, bodies, joints.",
|
||||
obj(
|
||||
json!({
|
||||
"measure": {"type": "boolean", "description": "Measure bodies (default true)"},
|
||||
"sketches": {
|
||||
"type": ["boolean", "string", "array"],
|
||||
"items": {"type": ["string", "integer"]},
|
||||
"description": "Which sketches in full: a list of sketch names or ids, true (all of them), or false / \"summary\" (none: summaries only, the default)",
|
||||
},
|
||||
"bodies": {"type": "array", "items": {"type": "string"}, "description": "Only these bodies, by name (default: all)"},
|
||||
"joints": {"type": "boolean", "description": "Joint definitions as joint.inspect gives them, when the design has joints (default true)"},
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
Effect::ReadOnly,
|
||||
)
|
||||
}
|
||||
|
||||
fn type_matches(t: &str, v: &Value) -> bool {
|
||||
match t {
|
||||
"string" => v.is_string(),
|
||||
@@ -483,10 +524,16 @@ fn type_matches(t: &str, v: &Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates `args` against the tool's schema (top level): unknown tool, missing required
|
||||
/// arguments, unknown arguments, type and enum mismatches.
|
||||
/// [`check_arguments_with`] the default options.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn check_arguments(name: &str, args: &Value) -> Result<(), String> {
|
||||
let defs = tool_definitions();
|
||||
check_arguments_with(name, args, Options::default())
|
||||
}
|
||||
|
||||
/// Validates `args` against the tool's schema as listed with these [`Options`] (top level):
|
||||
/// unknown tool, missing required arguments, unknown arguments, type and enum mismatches.
|
||||
pub(crate) fn check_arguments_with(name: &str, args: &Value, opts: Options) -> Result<(), String> {
|
||||
let defs = tool_definitions_with(opts);
|
||||
let def = defs.iter().find(|d| d["name"] == name).ok_or_else(|| format!("unknown tool `{name}`"))?;
|
||||
let schema = &def["inputSchema"];
|
||||
let Some(a) = args.as_object() else { return Err(format!("{name}: arguments must be an object")) };
|
||||
@@ -523,11 +570,12 @@ pub(crate) fn check_arguments(name: &str, args: &Value) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A tool result: content blocks plus the error flag.
|
||||
fn text_result(v: &Value, is_error: bool) -> Value {
|
||||
/// A tool result: content blocks plus the error flag. JSON is pretty-printed, or compact with
|
||||
/// compact output.
|
||||
fn text_result(v: &Value, is_error: bool, opts: Options) -> Value {
|
||||
let text = match v {
|
||||
Value::String(s) => s.clone(),
|
||||
v => serde_json::to_string_pretty(v).unwrap_or_default(),
|
||||
v => opts.json_text(v),
|
||||
};
|
||||
let mut r = json!({"content": [{"type": "text", "text": text}]});
|
||||
if is_error {
|
||||
@@ -543,34 +591,40 @@ fn text_result(v: &Value, is_error: bool) -> Value {
|
||||
r
|
||||
}
|
||||
|
||||
/// Run a tool. Failures are tool results with `isError: true` (the model sees the message);
|
||||
/// nothing here panics on hostile arguments.
|
||||
/// Run a tool, as the server does by default. Failures are tool results with `isError: true`
|
||||
/// (the model sees the message); nothing here panics on hostile arguments.
|
||||
pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value {
|
||||
call_tool_with(b, name, args, Options::default())
|
||||
}
|
||||
|
||||
/// [`call_tool`] with these [`Options`].
|
||||
pub fn call_tool_with(b: &mut dyn Backend, name: &str, args: &Value, opts: Options) -> Value {
|
||||
let empty = Map::new();
|
||||
let a = args.as_object().unwrap_or(&empty);
|
||||
let r = match name {
|
||||
"screenshot" => return screenshot(b, a),
|
||||
"compare_picture" => return compare_picture(b, a),
|
||||
"batch" => return batch(b, a),
|
||||
"check_parameters" => return check_parameters(b, a),
|
||||
"execute" => return execute(b, a),
|
||||
"compare_picture" => return compare_picture(b, a, opts),
|
||||
"batch" => return batch(b, a, opts),
|
||||
"check_parameters" => return check_parameters(b, a, opts),
|
||||
"execute" => return execute(b, a, opts),
|
||||
"inspect_design" if opts.compact => inspect_design_compact(b, a),
|
||||
_ => dispatch(b, name, a),
|
||||
};
|
||||
match r {
|
||||
Ok(v) => text_result(&v, false),
|
||||
Err(e) => text_result(&Value::String(e), true),
|
||||
Ok(v) => text_result(&v, false, opts),
|
||||
Err(e) => text_result(&Value::String(e), true, opts),
|
||||
}
|
||||
}
|
||||
|
||||
/// `execute`: one command, then its `expect` checked against the design.
|
||||
fn execute(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
fn execute(b: &mut dyn Backend, a: &Map<String, Value>, opts: Options) -> Value {
|
||||
let expect = match Expect::parse(a) {
|
||||
Ok(e) => e,
|
||||
Err(e) => return text_result(&Value::String(e), true),
|
||||
Err(e) => return text_result(&Value::String(e), true, opts),
|
||||
};
|
||||
match dispatch(b, "execute", a) {
|
||||
Ok(v) => with_expectation(b, v, expect),
|
||||
Err(e) => text_result(&Value::String(e), true),
|
||||
Ok(v) => with_expectation(b, v, expect, opts),
|
||||
Err(e) => text_result(&Value::String(e), true, opts),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -744,8 +798,8 @@ fn xyz_text(c: [f64; 3]) -> String {
|
||||
|
||||
/// A reply that went through, with its `expectation` when `expect` was given. A mismatch is a
|
||||
/// tool error that names it first; the design stays as built (the agent decides what to do).
|
||||
fn with_expectation(b: &mut dyn Backend, mut reply: Value, expect: Option<Expect>) -> Value {
|
||||
let Some(expect) = expect else { return text_result(&reply, false) };
|
||||
fn with_expectation(b: &mut dyn Backend, mut reply: Value, expect: Option<Expect>, opts: Options) -> Value {
|
||||
let Some(expect) = expect else { return text_result(&reply, false, opts) };
|
||||
let expectation = match expect.check(b) {
|
||||
Ok(e) => e,
|
||||
Err(e) => json!({"ok": false, "expected": expect.expected(), "mismatch": [format!("the design could not be measured: {e}")]}),
|
||||
@@ -761,8 +815,8 @@ fn with_expectation(b: &mut dyn Backend, mut reply: Value, expect: Option<Expect
|
||||
reply = json!({"result": reply});
|
||||
}
|
||||
reply["expectation"] = expectation;
|
||||
let Some(note) = note else { return text_result(&reply, false) };
|
||||
let mut r = text_result(&reply, true);
|
||||
let Some(note) = note else { return text_result(&reply, false, opts) };
|
||||
let mut r = text_result(&reply, true, opts);
|
||||
if let Some(content) = r["content"].as_array_mut() {
|
||||
content.insert(0, json!({"type": "text", "text": note}));
|
||||
}
|
||||
@@ -1195,6 +1249,116 @@ const TOOL_STEPS: &[&str] = &[
|
||||
"undo",
|
||||
];
|
||||
|
||||
/// Names for an error message: at most 40 of them.
|
||||
fn name_list(names: &[String]) -> String {
|
||||
let mut out = names.iter().take(40).cloned().collect::<Vec<_>>().join(", ");
|
||||
if names.len() > 40 {
|
||||
out.push_str(&format!(", … ({} in all)", names.len()));
|
||||
}
|
||||
if out.is_empty() { "none".into() } else { out }
|
||||
}
|
||||
|
||||
/// `inspect_design` with compact output: `document.inspect`, with sketch summaries unless
|
||||
/// sketches are asked for in full (by name or id, or all), and only the bodies asked for.
|
||||
fn inspect_design_compact(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<Value, String> {
|
||||
let measure = a.get("measure").and_then(Value::as_bool).unwrap_or(true);
|
||||
let bodies: Option<Vec<String>> = match a.get("bodies").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => Some(
|
||||
v.as_array()
|
||||
.and_then(|l| l.iter().map(|n| n.as_str().map(str::to_string)).collect::<Option<Vec<_>>>())
|
||||
.ok_or("inspect_design: `bodies` must be a list of body names")?,
|
||||
),
|
||||
};
|
||||
// With `bodies`, only those are measured.
|
||||
let mut d = b.call("document.inspect", json!({"measure": measure && bodies.is_none(), "sketch_counts": true}))?;
|
||||
if let Some(want) = bodies {
|
||||
let all: Vec<Value> = d["bodies"].as_array().cloned().unwrap_or_default();
|
||||
let names: Vec<String> = all.iter().filter_map(|x| x["name"].as_str().map(str::to_string)).collect();
|
||||
if let Some(missing) = want.iter().find(|n| !names.contains(n)) {
|
||||
return Err(format!("inspect_design: no body `{missing}` (bodies: {})", name_list(&names)));
|
||||
}
|
||||
let mut kept: Vec<Value> = all.into_iter().filter(|x| x["name"].as_str().is_some_and(|n| want.iter().any(|w| w == n))).collect();
|
||||
if measure && !want.is_empty() {
|
||||
let m = exec(b, "inspect.measure", json!({"bodies": want}))?;
|
||||
for body in &mut kept {
|
||||
let measured = m["bodies"].as_array().and_then(|l| l.iter().find(|x| x["name"] == body["name"])).cloned();
|
||||
if let (Some(Value::Object(fields)), Some(o)) = (measured, body.as_object_mut()) {
|
||||
for (k, v) in fields {
|
||||
o.entry(k).or_insert(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
d["bodies"] = Value::Array(kept);
|
||||
}
|
||||
let mut sketches: Vec<Value> = d["sketches"].as_array().cloned().unwrap_or_default();
|
||||
// An app from before `sketch_counts` leaves out the counts: take them from each sketch.
|
||||
for x in sketches.iter_mut().filter(|x| x.get("points").is_none()) {
|
||||
if let Ok(full) = exec(b, "sketch.inspect", json!({"sketch": x["id"].clone()}))
|
||||
&& let Some(o) = x.as_object_mut()
|
||||
{
|
||||
for key in ["points", "constraints"] {
|
||||
if let Some(n) = full[key].as_array().map(Vec::len) {
|
||||
o.insert(key.into(), json!(n));
|
||||
}
|
||||
}
|
||||
if let Some(plane) = full.get("plane").or_else(|| full["sketch"].get("plane")) {
|
||||
o.insert("plane".into(), plane.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
d["sketches"] = Value::Array(sketches.clone());
|
||||
let full: Vec<Value> = match a.get("sketches") {
|
||||
None | Some(Value::Null) | Some(Value::Bool(false)) => Vec::new(),
|
||||
Some(Value::String(t)) if t == "summary" => Vec::new(),
|
||||
Some(Value::Bool(true)) => sketches.iter().map(|x| x["id"].clone()).collect(),
|
||||
Some(Value::String(t)) if t == "full" || t == "all" => sketches.iter().map(|x| x["id"].clone()).collect(),
|
||||
Some(Value::Array(list)) => {
|
||||
let mut ids = Vec::new();
|
||||
for want in list {
|
||||
let found = sketches.iter().find(|x| match want {
|
||||
Value::String(n) => x["name"].as_str() == Some(n.as_str()) || x["id"].as_u64().is_some_and(|id| n.parse::<u64>() == Ok(id)),
|
||||
Value::Number(_) => x["id"] == *want,
|
||||
_ => false,
|
||||
});
|
||||
match found {
|
||||
Some(x) => ids.push(x["id"].clone()),
|
||||
None => {
|
||||
let names: Vec<String> = sketches.iter().filter_map(|x| x["name"].as_str().map(str::to_string)).collect();
|
||||
return Err(format!("inspect_design: no sketch {want} (sketches: {})", name_list(&names)));
|
||||
}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
Some(other) => {
|
||||
return Err(format!("inspect_design: `sketches` must be true, false, \"summary\" or a list of sketch names (got {other})"));
|
||||
}
|
||||
};
|
||||
if !full.is_empty() {
|
||||
let out: Vec<Value> = sketches
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
if full.contains(&x["id"]) {
|
||||
exec(b, "sketch.inspect", json!({"sketch": x["id"].clone()})).unwrap_or_else(|e| json!({"id": x["id"], "error": e}))
|
||||
} else {
|
||||
x
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
d["sketches"] = Value::Array(out);
|
||||
}
|
||||
// Joints: what each is attached to (left out when there are none, or the app is older).
|
||||
if a.get("joints").and_then(Value::as_bool).unwrap_or(true)
|
||||
&& let Ok(j) = exec(b, "joint.inspect", json!({}))
|
||||
&& j["joints"].as_array().is_some_and(|v| !v.is_empty())
|
||||
{
|
||||
d["joints"] = j["joints"].clone();
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// `set_parameter`'s new value: `value` or `expression` (the parameters.change name), one of
|
||||
/// them, or both when they agree (`50` and `"50"` do).
|
||||
fn parameter_value(a: &Map<String, Value>) -> Result<Value, String> {
|
||||
@@ -1268,14 +1432,14 @@ impl Undo {
|
||||
/// `batch`: run steps in order, stop at the first failure and (by default) go back to the
|
||||
/// design as it was before the batch. A batch that went through is then checked against its
|
||||
/// `expect`.
|
||||
fn batch(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
fn batch(b: &mut dyn Backend, a: &Map<String, Value>, opts: Options) -> Value {
|
||||
let expect = match Expect::parse(a) {
|
||||
Ok(e) => e,
|
||||
Err(e) => return text_result(&Value::String(e), true),
|
||||
Err(e) => return text_result(&Value::String(e), true, opts),
|
||||
};
|
||||
match batch_run(b, a) {
|
||||
(reply, true) => text_result(&reply, true),
|
||||
(reply, false) => with_expectation(b, reply, expect),
|
||||
(reply, true) => text_result(&reply, true, opts),
|
||||
(reply, false) => with_expectation(b, reply, expect, opts),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1737,28 +1901,28 @@ fn compact(mut v: Value) -> Value {
|
||||
/// restore that fails is an error saying the values are still in. Every agent session that
|
||||
/// changed a parameter to see its effect spent three to five calls on this loop, and one saved
|
||||
/// the design with the test values still in it.
|
||||
fn check_parameters(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
fn check_parameters(b: &mut dyn Backend, a: &Map<String, Value>, opts: Options) -> Value {
|
||||
let (changes, reports) = match check_parameters_args(a) {
|
||||
Ok(x) => x,
|
||||
Err(e) => return text_result(&Value::String(e), true),
|
||||
Err(e) => return text_result(&Value::String(e), true, opts),
|
||||
};
|
||||
// A name the design has no parameter of is refused before the checkpoint, so nothing
|
||||
// changes: `parameters.change` would make one.
|
||||
if let Err(e) = known_parameters(b, &changes) {
|
||||
return text_result(&Value::String(e), true);
|
||||
return text_result(&Value::String(e), true, opts);
|
||||
}
|
||||
let Some(id) = exec(b, "edit.checkpoint", json!({})).ok().and_then(|v| v["checkpoint"].as_u64()) else {
|
||||
let e = "check_parameters: this app has no edit.checkpoint to put the design back with; use set_parameter and measure, and set the values back yourself";
|
||||
return text_result(&json!(e), true);
|
||||
return text_result(&json!(e), true, opts);
|
||||
};
|
||||
let outcome = try_parameters(b, &changes, &reports);
|
||||
let restore = exec(b, "edit.restore_checkpoint", json!({"checkpoint": id}));
|
||||
match (outcome, restore) {
|
||||
(Ok(mut reply), Ok(_)) => {
|
||||
reply["restored"] = json!(true);
|
||||
text_result(&reply, false)
|
||||
text_result(&reply, false, opts)
|
||||
}
|
||||
(Err(e), Ok(_)) => text_result(&json!({"error": e, "restored": true, "note": "the design is back as it was"}), true),
|
||||
(Err(e), Ok(_)) => text_result(&json!({"error": e, "restored": true, "note": "the design is back as it was"}), true, opts),
|
||||
(outcome, Err(restore_error)) => {
|
||||
let mut reply = match outcome {
|
||||
Ok(r) => r,
|
||||
@@ -1769,7 +1933,7 @@ fn check_parameters(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
reply["note"] = json!(
|
||||
"THE DESIGN STILL HOLDS THE TRIED VALUES: the checkpoint could not be restored. Set them back with set_parameter (or undo) before saving"
|
||||
);
|
||||
text_result(&reply, true)
|
||||
text_result(&reply, true, opts)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1970,13 +2134,13 @@ fn screenshot(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
{"type": "image", "data": base64(&png), "mimeType": "image/png"},
|
||||
{"type": "text", "text": info.to_string()},
|
||||
]}),
|
||||
Err(e) => text_result(&Value::String(e), true),
|
||||
Err(e) => text_result(&Value::String(e), true, Options::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `compare_picture`: run the engine comparison and hand the overlay PNG back as an MCP
|
||||
/// image block, the numbers as text — an agent sees the picture, not a base64 blob.
|
||||
fn compare_picture(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
fn compare_picture(b: &mut dyn Backend, a: &Map<String, Value>, opts: Options) -> Value {
|
||||
let mut params = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]);
|
||||
params["overlay"] = json!(true);
|
||||
match exec(b, "inspect.compare_picture", params) {
|
||||
@@ -1992,7 +2156,7 @@ fn compare_picture(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
}
|
||||
json!({"content": content})
|
||||
}
|
||||
Err(e) => text_result(&Value::String(e), true),
|
||||
Err(e) => text_result(&Value::String(e), true, opts),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,8 @@ pub enum Verdict {
|
||||
|
||||
/// Methods the bridged MCP server uses; nothing else (clicks, preferences, quitting, the chat
|
||||
/// itself) is the agent's.
|
||||
const METHODS: &[&str] = &["engine.commands", "document.inspect", "engine.execute", "engine.batch", "ui.view", "ui.render", "ui.screenshot"];
|
||||
const METHODS: &[&str] =
|
||||
&["engine.commands", "document.inspect", "engine.execute", "engine.batch", "ui.view", "ui.render", "ui.screenshot", "mcp.options"];
|
||||
|
||||
/// Parameter names that hold a file or folder and nothing else.
|
||||
const FILE_KEYS: &[&str] = &["file", "files", "dir", "folder", "out", "output", "filename", "target_path"];
|
||||
@@ -356,6 +357,11 @@ mod tests {
|
||||
assert!(matches!(request("engine.batch", &batch, 0), Verdict::Ask(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mcp_server_may_read_its_output_options() {
|
||||
assert_eq!(request("mcp.options", &json!({}), 0), Verdict::Run { change: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mcp_servers_own_pictures_need_no_question() {
|
||||
let scratch = json!({"path": "/tmp/solidcraft-mcp-41-a3/shot-1.png", "allow_paths": ["/tmp/solidcraft-mcp-41-a3"]});
|
||||
|
||||
@@ -503,6 +503,8 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
connecting_section(app, ui);
|
||||
});
|
||||
ui.add_enabled_ui(app.preferences.ai_features, |ui| pointer_section(app, ui));
|
||||
// Agents through MCP don't use the chat, so this stays on with AI features off.
|
||||
mcp_section(app, ui);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -710,6 +712,22 @@ fn pointer_section(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The AI page's section for agents outside the app, which reach it through the MCP server
|
||||
/// whether or not the chat is on: shown below the chat's settings, with the chat off too.
|
||||
fn mcp_section(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return;
|
||||
}
|
||||
ui_kit::settings_section(ui, "mcp_agents", tr("ui.mcp_agents"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let response =
|
||||
ui_kit::checkbox(ui, tr("ui.mcp_compact"), &mut app.preferences.mcp_compact).backing_on_hover_text(tr("ui.mcp_compact_note"));
|
||||
crate::scenario::publish_handle("prefs:mcp_compact", response.rect.center());
|
||||
ui_kit::help_icon(ui, tr("ui.mcp_compact_note"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The agents: found and added, with Test, Default, a permission override and Remove.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
|
||||
@@ -836,6 +836,8 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
|
||||
DESIGN_WATCH.publish(&app.session.document_id, revision);
|
||||
ok(json!({"document_id": app.session.document_id, "revision": revision}))
|
||||
}
|
||||
// What the MCP server bridged to this app shapes its output with (Preferences › AI).
|
||||
"mcp.options" => ok(json!({"compact": app.preferences.mcp_compact})),
|
||||
"ui.messages" => ok(crate::messages::control(app, p)),
|
||||
"ui.inspect" => ok(json!({
|
||||
"render": crate::render_workspace::inspect_state(app),
|
||||
|
||||
@@ -1562,6 +1562,10 @@ preference_settings! {
|
||||
/// Custom instructions (#8220): text the agent chat adds to its system note when a session
|
||||
/// starts (`agent_chat::acp::system_note`). No page reset discards this user-authored text.
|
||||
agent_instructions: String = String::new();
|
||||
/// Compact output for agents connected through the MCP server (`solidcraft-cli mcp`, docs/mcp.md):
|
||||
/// `inspect_design` summarises sketches and tool JSON is not pretty-printed. Off: as always.
|
||||
/// The server asks once per agent session (`mcp.options`), so a change applies to the next one.
|
||||
mcp_compact: bool = false, PAGE_ASSISTANT;
|
||||
|
||||
// ---- Sketch / selection modifier bindings (classic defaults; alternate mapping is opt-in) ----
|
||||
/// Modifier that suppresses sketch auto-snap while drawing or dragging a sketch point.
|
||||
@@ -6601,6 +6605,25 @@ mod tests {
|
||||
assert!(!app.ui.dark, "an explicit theme does not follow the desktop");
|
||||
}
|
||||
|
||||
/// Compact output for MCP agents: off by default, a checkbox on the AI page (there with the
|
||||
/// chat off too), reported to the bridged MCP server as `mcp.options`, reset by Restore Defaults.
|
||||
#[test]
|
||||
fn mcp_compact_output_is_an_ai_preference_the_server_reads() {
|
||||
use serde_json::json;
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
assert_eq!(h.call("mcp.options", json!({}))["result"], json!({"compact": false}));
|
||||
h.call("ui.prefs", json!({"ai_features": false, "open": "AI"}));
|
||||
h.frames(3);
|
||||
assert!(crate::scenario::handle_at("prefs:mcp_compact").is_some(), "the checkbox is on the AI page with the chat off");
|
||||
// The page scrolls, so the setting is turned on as an agent would, not by a click.
|
||||
h.call("ui.prefs", json!({"mcp_compact": true}));
|
||||
h.frames(2);
|
||||
assert!(h.app.preferences.mcp_compact);
|
||||
assert_eq!(h.call("mcp.options", json!({}))["result"], json!({"compact": true}));
|
||||
h.call("ui.prefs", json!({"button": "defaults"}));
|
||||
assert_eq!(h.call("mcp.options", json!({}))["result"], json!({"compact": false}));
|
||||
}
|
||||
|
||||
/// Theme files (#2255): a built-in one and an imported one turn on through `ui.prefs`, the
|
||||
/// next frame draws with their colours (dark following the base), an export gives the theme
|
||||
/// back complete, imported themes are saved with the preferences, Remove falls back to the
|
||||
|
||||
@@ -428,7 +428,8 @@ reply without `param_check` as unchecked. The bridged MCP server asks once per c
|
||||
| `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut (the user's current first key, or null when cleared), params doc, enabled |
|
||||
| `document.revision` | — | `{document_id, revision}`: the active design's id and a number that moves whenever the design changes, for programs that follow it ([Following the design](#following-the-design)) |
|
||||
| `control.subscribe` | — | `{document_id, revision}`, as `document.revision`; the connection is then sent a `design.changed` line whenever they change ([Following the design](#following-the-design)) |
|
||||
| `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection (assembly joints: `engine.execute` `joint.inspect {joint?}`, which reads only: each joint's two origins with the occurrence, the snap as saved, the feature, face, edge or sketch curve its names refer to, and whether it resolves or why not; kind, offset, angle, flip, values, limits, expressions and motion links) |
|
||||
| `document.inspect` | `measure?`: bool, `sketch_counts?`: bool (default false) | parameters, timeline (errors, timings), bodies, sketches, selection (assembly joints: `engine.execute` `joint.inspect {joint?}`, which reads only: each joint's two origins with the occurrence, the snap as saved, the feature, face, edge or sketch curve its names refer to, and whether it resolves or why not; kind, offset, angle, flip, values, limits, expressions and motion links); with `sketch_counts` each sketch also gives its `plane` and its number of `points` and `constraints` |
|
||||
| `mcp.options` | — | `{"compact": bool}`: the output the MCP server bridged to this app should give its agents (Preferences › AI › Agents through MCP, `ui.prefs` `mcp_compact`, default false; [MCP](mcp.md#compact-output)) |
|
||||
| `document.export` | — | `{name, revision, dirty, format, text}`: the active design as its file holds it, for a host that keeps the files itself ([browser command API](browser-api.md)). `text` is the design's JSON, what a `.json` design file holds; `format` is `"json"`; `revision` is the one `document.revision` answers for this state. Only reads |
|
||||
| `document.import` | `text`: a design's JSON; `name?`: the name it takes | `{name, features, errors, revision}`: replaces the active design with `text`, timeline and parameters as saved; it opens saved, with a new `document_id` and nothing to undo. It does not ask about unsaved changes in the design it replaces: that is the caller's to decide. A text that does not read changes nothing. Waits behind a file loading or a design change, and evaluates on the window thread in the frame it runs |
|
||||
| `document.saved` | `revision`: as `document.export` gave it | `{revision, dirty}`: the host saved the design at that revision, so it counts as saved from there. Refused when the design has changed since |
|
||||
@@ -735,6 +736,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own
|
||||
- `look_at_speed`
|
||||
- `max_design_file_mb` (default 256): the largest design file opened, in MB, from the default up to 16384 (16 GB) (Preferences › General › Largest file to open, #4086; a `--max-file-size` launch flag overrides both for that run; the web app keeps the defaults and refuses other values; [large files](book/src/guide/files.md#large-files))
|
||||
- `max_step_file_mb` (default 512): the largest STEP or import file opened, in MB, from the default up to 16384 (16 GB) (Preferences › General › Largest file to open, #4086; a `--max-file-size` launch flag overrides both for that run; the web app keeps the defaults and refuses other values; [large files](book/src/guide/files.md#large-files))
|
||||
- `mcp_compact` (default false): compact tool output for agents bridged to this app through the MCP server (Preferences › AI › Agents through MCP; the server reads it with `mcp.options`; [MCP compact output](mcp.md#compact-output))
|
||||
- `middle_double_click` (`home` (default), `fit`, `off`)
|
||||
- `msaa`
|
||||
- `nav` (`fusion`, `solidworks`, `creo`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`)
|
||||
|
||||
+32
-1
@@ -151,6 +151,37 @@ folder of the design open in it, under the same rules, so give absolute paths: a
|
||||
resolves against the app's working folder, not the server's. The app's own
|
||||
file dialogs are never limited.
|
||||
|
||||
### Compact output
|
||||
|
||||
Compact output is for agents that pay for every byte. It is off by default, and then every tool
|
||||
behaves as described below. Any one of these turns it on:
|
||||
|
||||
- **Preferences › AI › Agents through MCP › Compact output** in the app, for every server bridged
|
||||
to it (`--connect`, and the agents its chat starts). The server asks the app (`mcp.options` on
|
||||
the [control channel](control-protocol.md)) when the agent first lists or calls a tool, and
|
||||
keeps the answer for the session, so the tools it listed keep their shape: a change applies to
|
||||
agent sessions started after it. An app that is not running yet is asked again on the next call.
|
||||
- `solidcraft-cli mcp --compact`.
|
||||
- The environment variable `SOLIDCRAFT_MCP_COMPACT=1` (`true`, `yes` and `on` work too; `0`,
|
||||
`false`, `no`, `off` or empty leave it off; any other value is an error at start-up).
|
||||
|
||||
The command line can only turn it on: with the preference on, a server started without
|
||||
`--compact` is compact too. With it on:
|
||||
|
||||
- `inspect_design` summarises each sketch (`id`, `name`, `plane`, the number of `points`,
|
||||
`curves`, `constraints` and `profiles`, `dof`, `status`, `visible`) instead of returning its
|
||||
contents: a sketch of 720 points is some 4 KB in the summary and over 80 KB in full. `sketches`
|
||||
takes a list of sketch names or ids to return in full (as `execute` `sketch.inspect` gives
|
||||
them), `true` for all of them, or `false` / `"summary"` (the default). `bodies` (a list of
|
||||
names) keeps only those bodies and measures only them. An unknown sketch or body name is an
|
||||
error that lists the names there are.
|
||||
- Tool results that are JSON are compact, not pretty-printed.
|
||||
|
||||
```sh
|
||||
solidcraft-cli mcp --connect 127.0.0.1:7878 --compact
|
||||
SOLIDCRAFT_MCP_COMPACT=1 solidcraft-cli mcp --connect 127.0.0.1:7878
|
||||
```
|
||||
|
||||
### Tool annotations
|
||||
|
||||
Each tool says what it may do, for clients that ask before running tools (or auto-approve on
|
||||
@@ -315,7 +346,7 @@ refused before anything runs. `expect` is an argument of the tool, not a key of
|
||||
carrying one is treated as any step with a key the batch does not know. Volume and body count
|
||||
say nothing about which kernel built the design, which is the point: the check holds whatever
|
||||
builds it.
|
||||
| `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). |
|
||||
| `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true); with [compact output](#compact-output) `sketches?` (names or ids, `true`, or `false` / `"summary"`: the default) and `bodies?` | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). |
|
||||
| `measure` | `body?` or `items?`, `summary?` (default false) | Area (mm²), bbox, topology counts and `closed` per body. Volume (mm³), volume centre of mass, density and mass are reported only for closed, consistently oriented bodies (null or omitted for open surfaces). Volume/mass totals skip open bodies; `total.open_bodies_skipped` gives their count. Area and topology totals include all bodies. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: faces and edges need only `type`, `body` and `point`; `index` is optional. See below. `summary: true` keeps one short object per body (`name`, `volume_mm3`, `bbox: {min, max}`, `faces`, `closed`; a body that could not be measured keeps its `error`), `body_count` and `total.volume_mm3`, nothing else: what a stage check against computed numbers needs, at a fraction of the size. It applies to the bodies reply, not to `items`. |
|
||||
| `body_topology` | `body`, `faces?` (`all`, `cylinders`; default `all`) | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). `faces: "cylinders"` replies `cylinders` instead of `edges` and `faces`: one entry per cylinder, `{radius, origin, axis, extent, names}`, the halves the kernel splits a cylinder into merged (same radius, same axis line; `origin` and `axis` as the first half's `cylinder` gives them), `extent` the `[min, max]` distance along `axis` from `origin` that the body's points on the cylinder span (the faces' `point`s and the ends of the edges lying on it; left out when none were found), and `names` the merged faces' names, any of which picks the face. Enough to check where every hole and boss is, in a few lines instead of the whole topology. |
|
||||
| `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. An expression `new_name = expression` renames the parameter as it sets it; in any other tool's expression parameter it adds the user parameter `new_name` and the input uses it (`defined`, `definitions` in the reply). |
|
||||
|
||||
Reference in New Issue
Block a user