BREP_mcp_core 0.12.0

The next.BREP.io MCP server core for the Rust B-rep CAD app: the Model Context Protocol surface generated from the app's own registries, its sessions, script runner and transports (stdio and streamable HTTP). Embedded in the app behind `brep-app --mcp`; hosted headlessly by BREP_mcp.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! The one script namespace every host's code runner exposes:
//! `sdk.<namespace>.<action>(args)`, and the `sdk` tool that describes it.
//!
//! An action is a registry tool (`<namespace>` = its group, `<action>` = its
//! name with a leading `<group>_` removed: `scene_entities` in `scene` is
//! `sdk.scene.entities`) or one of a host's own service functions
//! ([`ServiceEntry`]: the native server's operations, documents and
//! artifacts). A [`Surface`] is that catalogue for one tool set; it carries
//! no source text, and nothing is generated ahead of a question: the `sdk`
//! tool renders one action's TypeScript signature when asked for it.
//!
//! Pure and target-free, so the native server (`cad::surface`, `cad::tools`)
//! and the browser's page (`BREP_app/src/webmcp.rs`) answer `sdk` and name
//! the worker's functions from the same code.
use crate::tools::ToolSpec;
use serde_json::{json, Value};

/// The MCP front door: the only tools a client lists and calls.
pub const FRONT_DOOR: &[&str] = &["sdk", "run"];

/// What the `sdk` tool says of itself.
pub const SDK_DOC: &str = "Describe what a `run` program can call. Read-only: it runs nothing and starts nothing. `{}` lists the namespaces and guides with the SDK version; `{topic: \"scene\"}` lists a namespace's actions; `{topic: \"scene.mass_properties\"}` gives that action's TypeScript signature and the types it uses; `{topic: \"guide.design-part\"}` returns a guide's text; `{query: \"fillet edge\"}` searches actions by name and description (`limit`, then `cursor` for the next page).";

/// What the `run` tool says of itself (the native server's; the page adds its own limits).
pub const RUN_DOC: &str = "Run a JavaScript program on the CAD app: a script body with top-level `await` and `return`, e.g. `const r = await sdk.scene.mass_properties({}); return { volume: r.volume };`. `sdk` is a global: every app function is `await sdk.<namespace>.<action>(args)`, one object argument; find them with the `sdk` tool, and read `sdk({topic: \"guide.design-part\"})` once before modelling. The returned value (JSON) is the result; an image a program returns from `sdk.capture.screenshot` is attached to the reply. `{code, key?, wait_ms?}` starts a program and awaits its result (an explicit wait_ms answers its status if it is still running); the same key with the same code answers the same execution, so a lost reply is recovered. `{executionId, wait_ms?}` fetches that execution's result again (wait_ms defaults to 0). `{executionId, halt: true}` stops it; CAD operations it had already started run on. Put multi-line text in template literals. Starts a headless session if none is live.";

/// `sdk`'s arguments.
pub fn sdk_input_schema() -> Value {
    json!({ "type": "object", "properties": {
        "topic": { "type": "string", "minLength": 1, "maxLength": 256, "description": "a namespace (`scene`), an action (`scene.mass_properties`) or a guide (`guide.design-part`)" },
        "query": { "type": "string", "minLength": 1, "maxLength": 256, "description": "words to search action names, summaries and descriptions for" },
        "limit": { "type": "integer", "minimum": 1, "maximum": MAX_MATCHES, "default": DEFAULT_MATCHES, "description": "matches per page (with query)" },
        "cursor": { "type": "string", "maxLength": 64, "description": "nextCursor of the previous page of the same query" }
    }, "additionalProperties": false })
}

/// `sdk`'s reply: `version` always, then the fields of the form that was asked.
pub fn sdk_output_schema() -> Value {
    let named = |second: &str| json!({ "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, second: { "type": "string" } }, "required": ["name", second], "additionalProperties": false } });
    json!({ "type": "object", "properties": {
        "version": { "type": "string", "description": "The SDK manifest hash: it changes when any action's signature changes." },
        "namespaces": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "summary": { "type": "string" }, "actions": { "type": "integer", "minimum": 1 } }, "required": ["name", "summary", "actions"], "additionalProperties": false } },
        "guides": named("description"),
        "namespace": { "type": "string" },
        "actions": named("summary"),
        "action": { "type": "string", "description": "The action's path, `<namespace>.<action>`: call it as `await sdk.<namespace>.<action>(args)`." },
        "summary": { "type": "string" },
        "typescript": { "type": "string", "description": "The action's signature, preceded by the named types it refers to." },
        "readOnly": { "type": "boolean" },
        "destructive": { "type": "boolean" },
        "guide": { "type": "string" },
        "text": { "type": "string" },
        "query": { "type": "string" },
        "matches": named("summary"),
        "nextCursor": { "type": ["string", "null"] }
    }, "required": ["version"], "additionalProperties": false })
}

/// `run`'s arguments: one object for its three forms.
pub fn run_input_schema() -> Value {
    json!({ "type": "object", "properties": {
        "code": { "type": "string", "minLength": 1, "maxLength": MAX_CODE_BYTES, "description": "the program: a script body with top-level await and return, at most 256 KiB" },
        "key": { "type": "string", "minLength": 1, "maxLength": 128, "description": "with code: a retry key of your choosing. The same key with the same code answers the SAME execution (submitted once); the same key with other code is refused" },
        "wait_ms": { "type": "integer", "minimum": 0, "maximum": MAX_WAIT_MS, "description": "wait budget in ms. With code: awaits completion when omitted; an explicit budget answers the status if the program is still running. With executionId: defaults to 0" },
        "executionId": { "type": "string", "minLength": 1, "description": "instead of code: the execution to fetch the result of, or to halt" },
        "halt": { "type": "boolean", "description": "with executionId: stop the program now. Accepted CAD operations are not cancelled" }
    }, "additionalProperties": false })
}

pub const MAX_CODE_BYTES: usize = 256 << 10;
pub const MAX_WAIT_MS: u64 = 600_000;

/// Which of `run`'s three forms a call is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunForm {
    /// `{code, key?, wait_ms?}`
    Start,
    /// `{executionId, wait_ms?}`
    Result,
    /// `{executionId, halt: true}`
    Halt,
}

/// The form of a `run` call whose arguments [`validate_front_door`] accepted.
pub fn run_form(args: &Value) -> RunForm {
    if args.get("code").is_some() {
        RunForm::Start
    } else if args.get("halt") == Some(&Value::Bool(true)) {
        RunForm::Halt
    } else {
        RunForm::Result
    }
}

/// Validate a front-door call before starting a session or invoking a
/// handler. Shared by native MCP and the browser adapter.
pub fn validate_front_door(name: &str, args: &Value) -> Result<(), String> {
    let obj = args.as_object().ok_or("arguments must be an object")?;
    if args.to_string().len() > 1 << 20 { return Err("arguments exceed 1 MiB".into()); }
    let fields: &[&str] = match name {
        "run" => &["code", "key", "wait_ms", "executionId", "halt"],
        "sdk" => &["topic", "query", "limit", "cursor"],
        _ => return Err(format!("unknown front-door tool `{name}`; the tools are sdk and run")),
    };
    if let Some(k) = obj.keys().find(|k| !fields.contains(&k.as_str())) {
        return Err(format!("unknown argument `{k}`; {name} takes {{{}}}", fields.join(", ")));
    }
    let text = |key: &str, max: usize| match obj.get(key) {
        None => Ok(false),
        Some(v) if v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= max) => Ok(true),
        Some(_) => Err(format!("{key} must be a nonempty string of at most {max} bytes")),
    };
    if name == "sdk" {
        let (topic, query) = (text("topic", 256)?, text("query", 256)?);
        text("cursor", 64)?;
        if topic && query { return Err("give topic or query, not both".into()); }
        if !query && (obj.contains_key("limit") || obj.contains_key("cursor")) { return Err("limit and cursor page a query".into()); }
        if obj.get("limit").is_some_and(|v| !v.as_u64().is_some_and(|n| (1..=MAX_MATCHES as u64).contains(&n))) { return Err(format!("limit must be an integer from 1 to {MAX_MATCHES}")); }
        return Ok(());
    }
    let code = match obj.get("code") {
        None => false,
        Some(v) if v.as_str().is_some_and(|s| !s.is_empty()) => true,
        Some(_) => return Err("code must be a nonempty string".into()),
    };
    if obj.get("code").and_then(Value::as_str).is_some_and(|s| s.len() > MAX_CODE_BYTES) { return Err("code exceeds 256 KiB".into()); }
    let execution = text("executionId", 256)?;
    let key = text("key", 128)?;
    if obj.get("wait_ms").is_some_and(|v| !v.as_u64().is_some_and(|n| n <= MAX_WAIT_MS)) { return Err(format!("wait_ms must be an integer from 0 to {MAX_WAIT_MS}")); }
    if obj.get("halt").is_some_and(|v| !v.is_boolean()) { return Err("halt must be a boolean".into()); }
    let halt = obj.get("halt") == Some(&Value::Bool(true));
    match (code, execution) {
        (true, true) => Err("give code (start a program) or executionId (its result, or halt), not both".into()),
        (false, false) => Err("run takes {code, key?, wait_ms?}, {executionId, wait_ms?} or {executionId, halt: true}".into()),
        (true, false) if obj.contains_key("halt") => Err("halt stops an execution: give its executionId".into()),
        (false, true) if key => Err("key belongs to a program: give it with code".into()),
        (false, true) if halt && obj.contains_key("wait_ms") => Err("halt answers at once: give no wait_ms".into()),
        _ => Ok(()),
    }
}

/// A script call that passes `context` to a tool whose schema does not
/// declare one: such a tool would drop it, and the caller would believe a
/// revision check ran. Every native app command declares it (the frame
/// thread checks it); a tool composed by the server declares it only when it
/// forwards it. Shared by the native bridge and the browser's.
pub fn undeclared_context(name: &str, input_schema: &Value, args: &Value) -> Option<String> {
    if args.get("context").is_none() || input_schema.pointer("/properties/context").is_some() {
        return None;
    }
    Some(format!("`{name}` does not check a document context, so it cannot honour `context`: call it without one. It acts on the visible document; sdk.document.docs_list() names that document and its revision"))
}

/// One registry tool as a script sees it.
#[derive(Debug, Clone)]
pub struct ScriptTool {
    pub name: String,
    pub group: String,
    pub doc: String,
    pub input_schema: Value,
    pub output_schema: Value,
}

impl ScriptTool {
    pub fn of(spec: &ToolSpec) -> ScriptTool {
        ScriptTool { name: spec.name.clone(), group: spec.group.to_string(), doc: spec.doc.clone(), input_schema: spec.input_schema.clone(), output_schema: spec.output_schema.clone() }
    }
}

/// Whether a registry tool is a script function. Not: the `cad_*` group, the
/// session's own lifecycle (a script runs INSIDE a session), and the MCP's
/// front door (a script does not start or halt scripts).
pub fn script_callable(group: &str, name: &str) -> bool {
    matches!(name, "session_info" | "session_record" | "session_script") || !matches!(group, "cad" | "session" | "script")
}

/// The script-callable tools of a set, in its order.
pub fn script_tools<'a>(specs: impl IntoIterator<Item = &'a ToolSpec>) -> Vec<ScriptTool> {
    specs.into_iter().filter(|t| script_callable(t.group, &t.name)).map(ScriptTool::of).collect()
}

/// A JavaScript identifier for a registry name (`doc-new` → `doc_new`).
pub fn ident(name: &str) -> String {
    let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
    if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        out.insert(0, '_');
    }
    out
}

/// A registry tool's action name: its name with a leading `<group>_`
/// removed, and nothing else (`scene_entities` in `scene` → `entities`;
/// `doc_new` in `document` keeps its name).
pub fn method_name(group: &str, name: &str) -> String {
    let stripped = name.strip_prefix(group).and_then(|rest| rest.strip_prefix('_')).filter(|rest| !rest.is_empty());
    ident(stripped.unwrap_or(name))
}

/// A registry tool's path, `<namespace>.<action>`.
pub fn path_of(group: &str, name: &str) -> String {
    format!("{}.{}", ident(group), method_name(group, name))
}

/// The first sentence of a tool's doc: its one-line summary.
pub fn summary(doc: &str) -> String {
    let first = doc.split(". ").next().unwrap_or(doc).trim();
    first.replace("*/", "* /").chars().take(200).collect()
}

/// One of a host's own service functions (the native server's operation
/// service): what a registry tool is, without a registry.
#[derive(Debug, Clone)]
pub struct ServiceEntry {
    pub namespace: &'static str,
    pub action: &'static str,
    /// The host's own name for the function it dispatches to.
    pub method: &'static str,
    pub doc: String,
    pub input_schema: Value,
    pub output_schema: Value,
    pub grants: Vec<&'static str>,
    pub read_only: bool,
    pub destructive: bool,
}

/// What an action runs.
#[derive(Debug, Clone, Copy)]
pub enum Target<'a> {
    Tool(&'a ToolSpec),
    Service(&'a ServiceEntry),
}

/// One `sdk.<namespace>.<action>`.
#[derive(Debug, Clone)]
pub struct Entry<'a> {
    pub namespace: String,
    pub action: String,
    pub target: Target<'a>,
}

impl<'a> Entry<'a> {
    pub fn path(&self) -> String {
        format!("{}.{}", self.namespace, self.action)
    }
    pub fn doc(&self) -> &'a str {
        match self.target { Target::Tool(t) => &t.doc, Target::Service(s) => &s.doc }
    }
    pub fn summary(&self) -> String {
        summary(self.doc())
    }
    pub fn input_schema(&self) -> &'a Value {
        match self.target { Target::Tool(t) => &t.input_schema, Target::Service(s) => &s.input_schema }
    }
    pub fn output_schema(&self) -> &'a Value {
        match self.target { Target::Tool(t) => &t.output_schema, Target::Service(s) => &s.output_schema }
    }
    pub fn read_only(&self) -> bool {
        match self.target { Target::Tool(t) => t.annotations.read_only, Target::Service(s) => s.read_only }
    }
    pub fn destructive(&self) -> bool {
        match self.target { Target::Tool(t) => t.annotations.destructive, Target::Service(s) => s.destructive }
    }
    /// The capabilities a caller needs for this action to exist for it. A
    /// registry tool is the app's (`app.tools`); the file functions also
    /// need the host's files, as the file service checks on each call.
    pub fn grants(&self) -> &'a [&'static str] {
        match self.target {
            Target::Tool(t) if t.group == "files" && t.annotations.read_only => &["app.tools", "host.files.read"],
            Target::Tool(t) if t.group == "files" => &["app.tools", "host.files.write"],
            Target::Tool(_) => &["app.tools"],
            Target::Service(s) => &s.grants,
        }
    }
    /// The whole contract, as `brep://api/function/<path>` serves it.
    pub fn to_json(&self) -> Value {
        json!({
            "path": format!("sdk.{}", self.path()),
            "summary": self.summary(),
            "documentation": self.doc(),
            "inputSchema": self.input_schema(),
            "outputSchema": self.output_schema(),
            "grants": self.grants(),
            "readOnly": self.read_only(),
            "destructive": self.destructive(),
        })
    }
}

/// A guide the `sdk` tool serves by name: a skill's text.
#[derive(Debug, Clone, Copy)]
pub struct Guide<'a> {
    pub name: &'a str,
    pub description: &'a str,
    pub text: &'a str,
}

/// The catalogue of one tool set: every action a script may be given, by path.
#[derive(Debug, Clone)]
pub struct Surface<'a> {
    pub entries: Vec<Entry<'a>>,
    pub guides: Vec<Guide<'a>>,
    /// Service functions dropped because a registry tool has their path
    /// (the registry tool is kept), as `<namespace>.<action>`.
    pub clashes: Vec<String>,
    /// Registry tools dropped because an earlier one has their path.
    pub duplicates: Vec<String>,
}

const DEFAULT_MATCHES: usize = 10;
const MAX_MATCHES: usize = 50;

impl<'a> Surface<'a> {
    /// The script-callable tools of `specs`, then `services`; sorted by path.
    pub fn new(specs: impl IntoIterator<Item = &'a ToolSpec>, services: &'a [ServiceEntry], guides: Vec<Guide<'a>>) -> Self {
        let mut entries: Vec<Entry<'a>> = Vec::new();
        let mut seen: std::collections::HashSet<String> = Default::default();
        let (mut clashes, mut duplicates) = (Vec::new(), Vec::new());
        for spec in specs {
            if !script_callable(spec.group, &spec.name) { continue; }
            let entry = Entry { namespace: ident(spec.group), action: method_name(spec.group, &spec.name), target: Target::Tool(spec) };
            if seen.insert(entry.path()) { entries.push(entry) } else { duplicates.push(entry.path()) }
        }
        for service in services {
            let entry = Entry { namespace: service.namespace.into(), action: service.action.into(), target: Target::Service(service) };
            if seen.insert(entry.path()) { entries.push(entry) } else { clashes.push(entry.path()) }
        }
        entries.sort_by(|a, b| (&a.namespace, &a.action).cmp(&(&b.namespace, &b.action)));
        Surface { entries, guides, clashes, duplicates }
    }

    /// Only what a caller holding the grants `has` answers for may call.
    pub fn granted(mut self, has: impl Fn(&str) -> bool) -> Self {
        self.entries.retain(|e| e.grants().iter().all(|g| has(g)));
        self
    }

    /// Every action's path, `<namespace>.<action>`, sorted.
    pub fn names(&self) -> Vec<String> {
        self.entries.iter().map(Entry::path).collect()
    }

    /// The action at `path` (`scene.entities`; a leading `sdk.` is allowed).
    pub fn get(&self, path: &str) -> Option<&Entry<'a>> {
        let path = path.strip_prefix("sdk.").unwrap_or(path);
        let (namespace, action) = path.split_once('.')?;
        self.entries.iter().find(|e| e.namespace == namespace && e.action == action)
    }

    /// The manifest hash: every action's path with its input and output
    /// schema, so it changes when any signature does (and not when a
    /// description is reworded).
    pub fn version(&self) -> String {
        let mut hash = Fnv::default();
        for e in &self.entries {
            use std::io::Write as _;
            let _ = write!(hash, "{}\u{0}", e.path());
            let _ = serde_json::to_writer(&mut hash, e.input_schema());
            let _ = hash.write_all(&[0]);
            let _ = serde_json::to_writer(&mut hash, e.output_schema());
            let _ = hash.write_all(&[0]);
        }
        format!("{:016x}", hash.0)
    }

    fn namespaces(&self) -> Vec<(&str, Vec<&Entry<'a>>)> {
        let mut out: Vec<(&str, Vec<&Entry<'a>>)> = Vec::new();
        for e in &self.entries {
            match out.last_mut() {
                Some((name, list)) if *name == e.namespace => list.push(e),
                _ => out.push((e.namespace.as_str(), vec![e])),
            }
        }
        out
    }

    /// `sdk({})`.
    pub fn overview(&self) -> Value {
        let namespaces: Vec<Value> = self.namespaces().into_iter().map(|(name, list)| {
            // A namespace has no description of its own: its actions say what it is.
            let mut summary = String::new();
            for (i, e) in list.iter().enumerate() {
                if summary.len() + e.action.len() > 96 { summary.push_str(", …"); break; }
                if i > 0 { summary.push_str(", "); }
                summary.push_str(&e.action);
            }
            json!({ "name": name, "summary": summary, "actions": list.len() })
        }).collect();
        let guides: Vec<Value> = self.guides.iter().map(|g| json!({ "name": g.name, "description": g.description })).collect();
        json!({ "version": self.version(), "namespaces": namespaces, "guides": guides })
    }

    /// `sdk({topic})`: a namespace, an action or a guide.
    pub fn topic(&self, topic: &str) -> Result<Value, String> {
        let topic = topic.trim();
        let topic = topic.strip_prefix("sdk.").unwrap_or(topic);
        if let Some(name) = topic.strip_prefix("guide.") {
            let key = guide_key(name);
            let guide = self.guides.iter().find(|g| g.name == key).ok_or_else(|| {
                let names: Vec<&str> = self.guides.iter().map(|g| g.name).collect();
                format!("no guide `{name}`{}; the guides are {}", did_you_mean(&suggest(&key, names.iter().copied()), "guide."), if names.is_empty() { "none on this host".to_string() } else { names.join(", ") })
            })?;
            return Ok(json!({ "version": self.version(), "guide": guide.name, "text": guide.text }));
        }
        if let Some(entry) = self.get(topic) {
            return Ok(json!({
                "version": self.version(),
                "action": entry.path(),
                "summary": entry.summary(),
                "typescript": crate::declarations::signature(entry),
                "readOnly": entry.read_only(),
                "destructive": entry.destructive(),
            }));
        }
        if topic.contains('.') {
            return Err(self.unknown(topic));
        }
        let listed = self.namespaces().into_iter().find(|(name, _)| *name == topic);
        let Some((name, list)) = listed else {
            let names: Vec<&str> = self.namespaces().into_iter().map(|(name, _)| name).collect();
            return Err(format!("no namespace `{topic}`{}; sdk({{}}) lists the namespaces, sdk({{query: \"{topic}\"}}) searches the actions", did_you_mean(&suggest(topic, names.iter().copied()), "")));
        };
        let actions: Vec<Value> = list.iter().map(|e| json!({ "name": e.path(), "summary": e.summary() })).collect();
        Ok(json!({ "version": self.version(), "namespace": name, "actions": actions }))
    }

    /// `sdk({query})`: lexical and case-insensitive over path, summary and
    /// description; each word scores its best place (path, then summary,
    /// then description), ties by path. The cursor binds the query and the
    /// version, so pages of two catalogues never mix.
    pub fn search(&self, query: &str, limit: Option<u64>, cursor: Option<&str>) -> Result<Value, String> {
        if !(1..=256).contains(&query.chars().count()) { return Err("query must be 1 to 256 characters".into()); }
        let limit = limit.unwrap_or(DEFAULT_MATCHES as u64);
        if !(1..=MAX_MATCHES as u64).contains(&limit) { return Err(format!("limit must be 1 to {MAX_MATCHES}")); }
        let q = query.to_lowercase();
        let terms: Vec<&str> = q.split_whitespace().collect();
        let mut hits: Vec<(u32, String, String)> = self.entries.iter().filter_map(|e| {
            let (path, summary) = (e.path(), e.summary());
            let (p, s, doc) = (path.to_lowercase(), summary.to_lowercase(), e.doc().to_lowercase());
            let mut score = 0;
            for t in &terms {
                score += if p.contains(t) { 100 } else if s.contains(t) { 10 } else if doc.contains(t) { 1 } else { 0 };
            }
            (score > 0).then_some((score, path, summary))
        }).collect();
        hits.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
        let version = self.version();
        let mut bound = Fnv::default();
        { use std::io::Write as _; let _ = write!(bound, "{q}\u{0}{version}"); }
        let binding = format!("{:016x}", bound.0);
        let start = match cursor {
            None => 0,
            Some(c) => {
                let (offset, of) = c.split_once(':').ok_or("cursor is not from this search")?;
                if of != binding { return Err("cursor belongs to another query or SDK version".into()); }
                offset.parse::<usize>().map_err(|_| "cursor is not from this search")?
            }
        };
        let page: Vec<Value> = hits.iter().skip(start).take(limit as usize).map(|(_, path, summary)| json!({ "name": path, "summary": summary })).collect();
        let next = start + page.len();
        Ok(json!({
            "version": version,
            "query": query,
            "matches": page,
            "nextCursor": if next < hits.len() { Value::String(format!("{next}:{binding}")) } else { Value::Null },
        }))
    }

    /// The `sdk` tool: its arguments (already [`validate_front_door`]ed) to its reply.
    pub fn answer(&self, args: &Value) -> Result<Value, String> {
        validate_front_door("sdk", args)?;
        if let Some(topic) = args.get("topic").and_then(Value::as_str) {
            return self.topic(topic);
        }
        if let Some(query) = args.get("query").and_then(Value::as_str) {
            return self.search(query, args.get("limit").and_then(Value::as_u64), args.get("cursor").and_then(Value::as_str));
        }
        Ok(self.overview())
    }

    /// Why `path` names nothing here, with the nearest names that do: the
    /// same action in another namespace, a tool's registry name spelled as
    /// its action, then the closest paths.
    pub fn unknown(&self, path: &str) -> String {
        let path = path.strip_prefix("sdk.").unwrap_or(path);
        let (namespace, action) = path.split_once('.').unwrap_or(("", path));
        let mut hints: Vec<String> = Vec::new();
        let mut hint = |p: String| if !hints.contains(&p) { hints.push(p) };
        for e in &self.entries {
            let registry_name = matches!(e.target, Target::Tool(t) if squash(&t.name) == squash(action));
            if squash(&e.action) == squash(action) || (registry_name && e.namespace == namespace) { hint(e.path()); }
        }
        let paths: Vec<String> = self.entries.iter().filter(|e| namespace.is_empty() || e.namespace == namespace).map(Entry::path).collect();
        for near in suggest(path, paths.iter().map(String::as_str)) { hint(near.to_string()); }
        hints.truncate(3);
        let listing = if self.entries.iter().any(|e| e.namespace == namespace) { format!("sdk({{topic: \"{namespace}\"}}) lists sdk.{namespace}.*") } else { "sdk({}) lists the namespaces".to_string() };
        format!("sdk.{path} does not exist{} (the sdk tool: {listing})", did_you_mean(&hints.iter().map(String::as_str).collect::<Vec<_>>(), "sdk."))
    }
}

/// The image artifacts a finished program's output refers to, by id: every
/// `{artifactId, mediaType: "image/..."}` in it (a screenshot's reply holds
/// its picture so), each once, in order, at most `max`. `reply` is `run`'s
/// envelope; nothing is taken from a failure or a running status.
pub fn returned_images(reply: &Value, max: usize) -> Vec<String> {
    fn walk(value: &Value, depth: usize, max: usize, found: &mut Vec<String>) {
        if depth > 16 || found.len() >= max { return; }
        match value {
            Value::Object(map) => {
                let image = map.get("mediaType").and_then(Value::as_str).is_some_and(|m| m.starts_with("image/"));
                match map.get("artifactId").and_then(Value::as_str) {
                    Some(id) if image => { if !found.iter().any(|f| f == id) { found.push(id.to_string()); } }
                    _ => for v in map.values() { walk(v, depth + 1, max, found); },
                }
            }
            Value::Array(items) => for v in items { walk(v, depth + 1, max, found); },
            _ => {}
        }
    }
    let mut found = Vec::new();
    if reply["ok"] == true && reply["value"]["state"] == "succeeded" {
        walk(&reply["value"]["output"], 0, max, &mut found);
    }
    found
}

fn did_you_mean(names: &[&str], prefix: &str) -> String {
    if names.is_empty() { return String::new(); }
    format!("; did you mean {}?", names.iter().map(|n| format!("{prefix}{n}")).collect::<Vec<_>>().join(" or "))
}

/// A guide name as agents write it: `Design Part`, `design_part.md`,
/// `skill://design-part/SKILL.md` all name `design-part`.
pub fn guide_key(name: &str) -> String {
    let name = name.trim();
    let name = name.strip_prefix("skill://").unwrap_or(name);
    let name = name.strip_suffix("/SKILL.md").or_else(|| name.strip_suffix(".md")).unwrap_or(name);
    name.to_ascii_lowercase().replace([' ', '_'], "-")
}

fn squash(name: &str) -> String {
    name.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect()
}

fn distance(a: &str, b: &str) -> usize {
    let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
    let mut row: Vec<usize> = (0..=b.len()).collect();
    for i in 1..=a.len() {
        let mut previous = row[0];
        row[0] = i;
        for j in 1..=b.len() {
            let next = (row[j] + 1).min(row[j - 1] + 1).min(previous + usize::from(a[i - 1] != b[j - 1]));
            previous = row[j];
            row[j] = next;
        }
    }
    row[b.len()]
}

/// The up-to-three candidates nearest `name`: the same letters spelled
/// another way (`massProperties`), else within a third of its length.
pub fn suggest<'a>(name: &str, candidates: impl Iterator<Item = &'a str>) -> Vec<&'a str> {
    let want = squash(name);
    let bound = (want.len() / 3).max(2);
    let mut near: Vec<(usize, &str)> = candidates.map(|c| (distance(&squash(c), &want), c)).filter(|(d, _)| *d <= bound).collect();
    near.sort();
    near.into_iter().take(3).map(|(_, c)| c).collect()
}

/// FNV-1a, 64 bits, over what is written to it: a change detector for the
/// manifest (the base crate carries no cryptographic hash, and needs none
/// here).
struct Fnv(u64);

impl Default for Fnv {
    fn default() -> Self {
        Fnv(0xcbf2_9ce4_8422_2325)
    }
}

impl std::io::Write for Fnv {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        for b in bytes {
            self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3);
        }
        Ok(bytes.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}