BREP_mcp 0.25.0

The next.BREP.io MCP automation server for the Rust B-rep CAD app: hosts the app headlessly under egui_kittest and serves the BREP_mcp_core Model Context Protocol surface over stdio or streamable HTTP, so an agent can drive the CAD app with no display attached.
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
//! The headless host: the whole `BrepApp` inside `egui_kittest::Harness` on a
//! wgpu device, stepped on demand on a dedicated thread (measured in §12). No
//! window, no display. Answers the `brep_mcp_core` host protocol; the app's
//! own envelope and reply types are converted at the boundary.
use crate::annotate::{Annotated, Annotation};
use brep_app::app::BrepApp;
use brep_app::automation::command::Envelope as AppEnvelope;
use brep_app::automation::AppOptions;
use brep_mcp_core::host::{HostConfig, HostHandle, HostInfo, HostRequest, Reply};
use egui_kittest::Harness;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

pub struct HeadlessConfig {
    pub width: f32,
    pub height: f32,
    pub ppp: f32,
    pub seed: bool,
    /// The session's private store directory.
    pub store_dir: PathBuf,
    /// Frames to step while waiting for one command's reply before giving up.
    pub max_steps: u32,
    /// HANG GUARD on the seed history landing before the first command
    /// (`settle`). Generous on purpose and with NO performance meaning:
    /// nothing about the app is asserted by how long the seed takes, only that
    /// it finishes at all. Sixty seconds to match the other liveness guards in
    /// the UI-side suites.
    pub settle_limit: Duration,
    /// The server's code mode: the app's JavaScript editor runs on it.
    pub scripts: Option<brep_mcp_core::cad::LocalScripts>,
}

/// The editor's runner in a headless session: the serving `brep-mcp`'s own
/// code mode, as an agent's `run_script` reaches it.
struct EditorScripts(brep_mcp_core::cad::LocalScripts);

impl brep_app::javascript::ScriptHost for EditorScripts {
    fn ready(&self) -> Result<bool, String> {
        self.0.ready()
    }
    fn run(&self, source: &str) -> Result<String, String> {
        self.0.run(source)
    }
    fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
        self.0.result(id)
    }
    fn halt(&self, id: &str) -> Result<(), String> {
        self.0.halt(id)
    }
}

impl Default for HeadlessConfig {
    fn default() -> Self {
        Self {
            width: 1400.0,
            height: 960.0,
            ppp: 1.0,
            seed: true,
            store_dir: std::env::temp_dir().join("brep-mcp-store"),
            max_steps: 600,
            settle_limit: Duration::from_secs(60),
            scripts: None,
        }
    }
}

impl From<HostConfig> for HeadlessConfig {
    fn from(c: HostConfig) -> Self {
        Self { width: c.width, height: c.height, ppp: c.ppp, seed: c.seed, store_dir: c.store_dir, scripts: c.scripts, ..Self::default() }
    }
}

/// The last panic message, captured by the hook the host installs.
static LAST_PANIC: Mutex<Option<String>> = Mutex::new(None);

fn install_panic_hook() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            let msg = info
                .payload()
                .downcast_ref::<String>()
                .cloned()
                .or_else(|| info.payload().downcast_ref::<&str>().map(|s| s.to_string()))
                .unwrap_or_else(|| "panic".into());
            let loc = info.location().map(|l| format!(" at {}:{}", l.file(), l.line())).unwrap_or_default();
            *LAST_PANIC.lock().unwrap() = Some(format!("{msg}{loc}"));
            previous(info);
        }));
    });
}

fn take_panic() -> Option<String> {
    LAST_PANIC.lock().unwrap().take()
}

/// Spawn the host thread; returns once the app is built and its seed history
/// has settled, or with the build error.
/// `BREP_FRAME_TRACE=1`: report slow host steps and commands on stderr.
fn trace_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var_os("BREP_FRAME_TRACE").is_some_and(|v| v == "1"))
}

pub fn spawn(cfg: impl Into<HeadlessConfig>) -> Result<HostHandle, String> {
    let cfg: HeadlessConfig = cfg.into();
    install_panic_hook();
    // Publishers are off in a plain native run; a host is what turns them on.
    brep_app::automation::registry::set_enabled(true);
    // ...and the registry is process-global while the app is not: the previous
    // script's session published into this same map and nothing has emptied it.
    // A reader would otherwise answer THIS session from the LAST one's frame
    // for any key this app has not published yet.
    brep_app::automation::registry::clear();
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<HostRequest>();
    let (ready_tx, ready_rx) = std::sync::mpsc::channel::<Result<HostInfo, String>>();
    let join = std::thread::Builder::new()
        .name("brep-mcp-headless".into())
        .spawn(move || {
            let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| build(&cfg)));
            let (mut harness, info) = match built {
                Ok(Ok(v)) => v,
                Ok(Err(e)) => {
                    let _ = ready_tx.send(Err(e));
                    return;
                }
                Err(_) => {
                    let _ = ready_tx.send(Err(format!("the app panicked while starting: {}", take_panic().unwrap_or_default())));
                    return;
                }
            };
            let queue = harness.state().app().automation().clone();
            let ppp = cfg.ppp;
            // Let the seed history land before the first command. A settle
            // that does not reach the idle contract is a FAILED START, not a
            // slow one. Sending `Ok(info)` regardless — which is what this did
            // until 2026-09-21 — handed the script an app with work still in
            // flight, and the script then failed further down, on whichever
            // expectation happened to touch the state that had not landed: a
            // hang reported as a wrong answer somewhere else.
            if let Err(why) = settle(&mut harness, &queue, ppp, cfg.settle_limit) {
                let _ = ready_tx.send(Err(format!("app was not settled before command 1 \u{2014} {why}")));
                return;
            }
            let _ = ready_tx.send(Ok(info));

            // Commands are served CONCURRENTLY, as the desktop host serves
            // them (a task per command): each is submitted to the app queue
            // on arrival and answered on the frame its reply comes, so a
            // command the queue is polling for seconds (`Outcome::Poll`)
            // never holds a `frame_info` behind it. Frames step while any
            // command is in flight; the thread blocks only when none is.
            struct InFlight {
                id: u64,
                cmd: String,
                rx: std::sync::mpsc::Receiver<brep_app::automation::command::Reply>,
                reply: tokio::sync::oneshot::Sender<Reply>,
                steps: u32,
                started: Instant,
            }
            let mut inflight: Vec<InFlight> = Vec::new();
            let mut stopping = false;
            loop {
                let req = if stopping {
                    None
                } else if inflight.is_empty() {
                    match rx.blocking_recv() {
                        Some(req) => Some(req),
                        None => break,
                    }
                } else {
                    match rx.try_recv() {
                        Ok(req) => Some(req),
                        Err(tokio::sync::mpsc::error::TryRecvError::Empty) => None,
                        Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
                            stopping = true;
                            None
                        }
                    }
                };
                match req {
                    Some(HostRequest::Stop) => stopping = true,
                    Some(HostRequest::Command { envelope, reply }) => {
                        let id = envelope.id;
                        let cmd = envelope.cmd.clone();
                        let rx_reply = queue.submit_for(AppEnvelope { id, cmd: envelope.cmd, args: envelope.args }, None, envelope.client);
                        inflight.push(InFlight { id, cmd, rx: rx_reply, reply, steps: 0, started: Instant::now() });
                    }
                    // The DOCS ANNOTATION overlay (`crate::annotate`): set the
                    // caption and the ring, then draw one frame so the next
                    // capture — and anything that reads the session — sees it.
                    // The keys are checked HERE, against what the app is
                    // publishing right now, so a renamed control fails the
                    // walkthrough by name instead of dropping its highlight.
                    Some(HostRequest::Annotate { spec, reply }) => {
                        let result = (|| {
                            let note = Annotation::parse(&spec)?;
                            let missing = crate::annotate::unknown_keys(&note.highlight);
                            if !missing.is_empty() {
                                return Err(format!("annotate: {}", missing.join("; ")));
                            }
                            let highlighted = note.highlight.len();
                            harness.state_mut().note = note;
                            step(&mut harness, &queue, ppp)?;
                            Ok(serde_json::json!({
                                "frame": queue.frame(),
                                "highlighted": highlighted,
                            }))
                        })();
                        let _ = reply.send(result);
                    }
                    Some(HostRequest::Screenshot { region, reply }) => {
                        let result = (|| {
                            step(&mut harness, &queue, ppp)?;
                            let image = harness.render().map_err(|e| format!("headless render: {e}"))?;
                            let view = harness.state().app().view_rect();
                            let region: brep_app::automation::cmd_capture::Region =
                                serde_json::from_value(region).map_err(|e| format!("region: {e}"))?;
                            let color = egui::ColorImage {
                                size: [image.width() as usize, image.height() as usize],
                                source_size: egui::vec2(image.width() as f32, image.height() as f32),
                                pixels: image
                                    .pixels()
                                    .map(|p| egui::Color32::from_rgba_premultiplied(p.0[0], p.0[1], p.0[2], p.0[3]))
                                    .collect(),
                            };
                            brep_app::automation::cmd_capture::encode_capture(&color, ppp, view, &region)
                        })();
                        let _ = reply.send(result);
                    }
                    None => {}
                }
                if stopping && inflight.is_empty() {
                    break;
                }
                // Answer what has replied (or failed) before stepping again.
                let mut i = 0;
                while i < inflight.len() {
                    let f = &inflight[i];
                    let done = if let Ok(r) = f.rx.try_recv() {
                        Some(r.into_host())
                    } else if queue.is_poisoned() {
                        Some(Reply::err(f.id, queue.frame(), "session poisoned"))
                    } else if f.steps >= cfg.max_steps && !queue.is_polling(f.id) {
                        // A command the queue is POLLING has started work that
                        // lands on later frames: it keeps its frames, bounded
                        // by its own deadline.
                        Some(Reply::err(f.id, queue.frame(), format!("no reply after {} frames", cfg.max_steps)))
                    } else {
                        None
                    };
                    match done {
                        Some(result) => {
                            let f = inflight.swap_remove(i);
                            if trace_on() && f.started.elapsed() > Duration::from_millis(1000) {
                                eprintln!("[frame-trace] headless command {} took {} ms over {} frame(s)", f.cmd, f.started.elapsed().as_millis(), f.steps);
                            }
                            let _ = f.reply.send(result);
                        }
                        None => i += 1,
                    }
                }
                if inflight.is_empty() {
                    continue;
                }
                let stepped = Instant::now();
                if let Err(why) = step(&mut harness, &queue, ppp) {
                    queue.poison(why.clone());
                    for f in inflight.drain(..) {
                        let _ = f.reply.send(Reply::err(f.id, queue.frame(), why.clone()));
                    }
                    continue;
                }
                if trace_on() && stepped.elapsed() > Duration::from_millis(250) {
                    eprintln!("[frame-trace] headless step {} ms", stepped.elapsed().as_millis());
                }
                for f in &mut inflight {
                    f.steps += 1;
                }
                if inflight.iter().all(|f| f.steps > 2) {
                    std::thread::sleep(Duration::from_millis(2));
                }
            }
        })
        .map_err(|e| format!("spawn host thread: {e}"))?;
    // A start that failed has no handle to stop it by: its thread is on its
    // way out, releasing the app and its graphics device, and is joined here
    // so that it has finished before the caller goes on (and never runs
    // beside the process's own exit).
    let failed = match ready_rx.recv() {
        Ok(Ok(info)) => return Ok(HostHandle::new(tx, info, join)),
        Ok(Err(e)) => e,
        Err(_) => "the host thread ended before the app was ready".to_string(),
    };
    let _ = join.join();
    Err(failed)
}

/// The harness's state is [`Annotated`] — `BrepApp` plus the docs-annotation
/// overlay painted over it — so the app is reached through `state().app()`.
/// See `crate::annotate` for why the overlay lives inside an `update` rather
/// than in the image compositor.
type App = Harness<'static, Annotated>;

/// The text face every headless session draws with — the face the scripts'
/// pinned layouts were recorded in. A family name, resolved through fontconfig
/// (the repo ships no font file); [`SCRIPT_FONT_FILE`] is how its file is
/// recognised when fontconfig substitutes another.
const SCRIPT_FONT: &str = "DejaVu Sans Mono";
const SCRIPT_FONT_FILE: &str = "DejaVuSansMono";

/// `BREP_MCP_ADAPTER=gpu`: render on a hardware GPU, for MEASUREMENT runs only
/// (playback timings on a machine that has one). kittest's own setup ranks a
/// CPU rasteriser first, so screenshots come out the same on every machine, and
/// the gated test-mcp keeps it: its baselines were recorded that way. This
/// ranks discrete over integrated over any other GPU and falls back to the CPU
/// adapter with a notice. The adapter used is in `__brepDiagnostics`, which a
/// timing record quotes.
fn gpu_setup() -> Option<eframe::egui_wgpu::WgpuSetup> {
    use eframe::egui_wgpu::{wgpu, WgpuSetup};
    match std::env::var("BREP_MCP_ADAPTER").ok()?.to_ascii_lowercase().as_str() {
        "gpu" => {}
        "" | "cpu" => return None,
        other => {
            eprintln!("brep-mcp: BREP_MCP_ADAPTER={other} is not gpu or cpu; using the CPU adapter");
            return None;
        }
    }
    let mut setup = egui_kittest::wgpu::default_wgpu_setup();
    if let WgpuSetup::CreateNew(create) = &mut setup {
        create.native_adapter_selector = Some(Arc::new(|adapters, _surface| {
            let rank = |a: &&wgpu::Adapter| match a.get_info().device_type {
                wgpu::DeviceType::DiscreteGpu => 0,
                wgpu::DeviceType::IntegratedGpu => 1,
                wgpu::DeviceType::Other | wgpu::DeviceType::VirtualGpu => 2,
                wgpu::DeviceType::Cpu => 3,
            };
            let mut ranked: Vec<&wgpu::Adapter> = adapters.iter().collect();
            ranked.sort_by_key(rank);
            let chosen = ranked.first().map(|a| (*a).clone()).ok_or_else(|| "No adapter found".to_owned())?;
            if chosen.get_info().device_type == wgpu::DeviceType::Cpu {
                eprintln!("brep-mcp: BREP_MCP_ADAPTER=gpu but no GPU adapter is available; using {}", chosen.get_info().name);
            }
            Ok(chosen)
        }));
    }
    Some(setup)
}

fn build(cfg: &HeadlessConfig) -> Result<(App, HostInfo), String> {
    std::fs::create_dir_all(&cfg.store_dir).map_err(|e| format!("store dir {}: {e}", cfg.store_dir.display()))?;
    let store_dir = cfg.store_dir.clone();
    let scripts = cfg.scripts.clone();
    let seed = cfg.seed;
    let adapter = Arc::new(Mutex::new(String::new()));
    let adapter_out = adapter.clone();
    let builder = Harness::builder()
        .with_size(egui::vec2(cfg.width, cfg.height))
        .with_pixels_per_point(cfg.ppp)
        .with_step_dt(1.0 / 60.0);
    let builder = match gpu_setup() {
        Some(setup) => builder.wgpu_setup(setup),
        None => builder.wgpu(),
    };
    let harness = builder
        .build_eframe(move |cc| {
            // One named face, never whatever the machine answers for
            // `monospace`: the scripts' recorded chrome/camera values were
            // recorded with it and must hold on every host.
            let font = brep_app::fonts::install_matching(&cc.egui_ctx, SCRIPT_FONT);
            if !font.as_deref().is_some_and(|path| path.contains(SCRIPT_FONT_FILE)) {
                eprintln!(
                    "brep-mcp: fontconfig has no {SCRIPT_FONT} (got {font:?}); \
                     script layouts will not match their recorded values"
                );
            }
            let store = brep_app::store::native_store_at(store_dir.clone());
            let mut app = BrepApp::new_with(cc, AppOptions { store: Some(store), seed })
                .expect("BrepApp::new_with under kittest");
            if let Some(scripts) = scripts.clone() {
                app.set_script_host(Box::new(EditorScripts(scripts)));
            }
            // The app's OWN diagnostics, not a second reading of the same
            // adapter: `HostInfo.adapter`, the `diagnostics` command and the
            // Info window must all name the same device (brep_app::diagnostics).
            *adapter_out.lock().unwrap() = app.diagnostics().adapter_line();
            Annotated::new(app)
        });
    let info = HostInfo {
        backend: "headless",
        adapter: adapter.lock().unwrap().clone(),
        platform: std::env::consts::OS,
        width: cfg.width,
        height: cfg.height,
        ppp: cfg.ppp,
    };
    Ok((harness, info))
}

/// One frame: drain input into the harness's RawInput, step, check for a panic.
fn step(harness: &mut App, queue: &Arc<brep_app::automation::queue::AutomationQueue>, ppp: f32) -> Result<(), String> {
    let frame = harness.ctx.cumulative_frame_nr();
    let view = harness.state().app().view_rect();
    let ctx = harness.ctx.clone();
    queue.drain_input(harness.input_mut(), frame, ppp, view, &ctx);
    let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| harness.step()));
    match r {
        Ok(()) => Ok(()),
        Err(_) => Err(format!("the app panicked: {}", take_panic().unwrap_or_else(|| "(no message)".into()))),
    }
}

/// Why a `settle` never reached the idle contract.
///
/// It exists because the two ways of not settling used to be spelled the same
/// as settling: the function returned `()`, the deadline simply ended the loop
/// and a failed frame simply returned. A caller could not tell a settled app
/// from an app that had run out of time, so it proceeded with the second one.
#[derive(Debug, Clone)]
pub enum SettleError {
    /// The hang guard expired. `pending` names the work still in flight, which
    /// is the whole diagnostic: "still pending: mesh_imports" says which part
    /// of the app is stuck, and an EMPTY list says the app had gone idle but
    /// not for the two consecutive frames the contract asks for.
    DeadlineExpired { limit: Duration, frames: u32, pending: Vec<&'static str> },
    /// A frame failed (the app panicked); the message is `step`'s.
    StepFailed(String),
}

impl std::fmt::Display for SettleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SettleError::DeadlineExpired { limit, frames, pending } => {
                let plural = if *frames == 1 { "" } else { "s" };
                write!(f, "the {} ms hang guard expired after {frames} frame{plural}; still pending: ", limit.as_millis())?;
                if pending.is_empty() {
                    write!(f, "nothing, but the app had not been idle for two consecutive frames")
                } else {
                    write!(f, "{}", pending.join(", "))
                }
            }
            SettleError::StepFailed(why) => write!(f, "a frame failed: {why}"),
        }
    }
}

/// What the app still has in flight, named.
///
/// The SAME six the app's own idle contract reads
/// (`brep_app::automation::cmd_frame::frame_info` — `pending` and the
/// `idle` computed from it, which is what every waiting tool polls). Settling
/// on fewer than the app calls idle is the same defect in a smaller costume:
/// the host would declare the app ready while `frame` still called it busy.
fn pending_work(harness: &App) -> Vec<&'static str> {
    let e = harness.state().app().docs_engine();
    [
        ("run", e.run_pending()),
        ("queries", e.queries_pending()),
        ("mesh_imports", e.mesh_imports_pending()),
        ("step_probes", e.step_probes_pending()),
        ("topology", e.topology_pending()),
        ("projection", e.sheet_lines_pending()),
    ]
    .into_iter()
    .filter_map(|(name, on)| on.then_some(name))
    .collect()
}

/// Step until the app is idle two frames running, or say why it is not.
///
/// `limit` is a HANG GUARD with no performance meaning: it is not a claim about
/// how long a seed run may take, only a refusal to step forever. Blowing it is
/// reported, never absorbed.
fn settle(
    harness: &mut App,
    queue: &Arc<brep_app::automation::queue::AutomationQueue>,
    ppp: f32,
    limit: Duration,
) -> Result<(), SettleError> {
    let start = Instant::now();
    let mut idle_frames = 0u32;
    let mut frames = 0u32;
    loop {
        // One frame ALWAYS runs before the deadline is consulted, so the
        // pending list in the error was read from a stepped app rather than
        // from whatever it happened to hold before the first frame.
        step(harness, queue, ppp).map_err(SettleError::StepFailed)?;
        frames += 1;
        let pending = pending_work(harness);
        if pending.is_empty() {
            idle_frames += 1;
            if idle_frames >= 2 {
                return Ok(());
            }
        } else {
            idle_frames = 0;
        }
        if start.elapsed() >= limit {
            return Err(SettleError::DeadlineExpired { limit, frames, pending });
        }
        if !pending.is_empty() {
            std::thread::sleep(Duration::from_millis(8));
        }
    }
}

#[allow(dead_code)]
fn _value(_: Value) {}