Skip to main content

brep_mcp_core/cad/
mod.rs

1//! The CAD operation service (owner brief 2026-10-28).
2//!
3//! One semantic CAD API, one operation lifecycle and one code-mode executor,
4//! served to MCP clients as the `sdk` and `run` tools and to programs as the
5//! `sdk` global. Everything here runs over the host protocol a live session
6//! already speaks, so the headless host and the attached desktop window get
7//! identical semantics.
8//!
9//! - [`wire`]      — handles, timestamps, `ApiError`, `Effects`, `Response`.
10//! - [`canon`]     — RFC 8785 canonical JSON and SHA-256.
11//! - [`keys`]      — authenticated, expiring admission keys.
12//! - [`catalogue`] — the operation commands' descriptors, their manifest and its hash.
13//! - [`commands`]  — what each semantic command does to the app.
14//! - [`ops`]       — admission, idempotency, the request-independent operation lifetime,
15//!   cancellation, retention and overload.
16//! - [`artifacts`] — opaque, scoped, expiring byte objects (a STEP export, an upload).
17//! - [`code`]      — code mode: a program in a host-supervised worker process.
18//! - [`surface`]   — the script namespace's native side: the service functions and
19//!   the worker's two hooks (`script_names`, `script_call`).
20//! - [`declarations`] — one action's TypeScript signature, rendered on demand.
21//! - [`diag`]      — bounded, payload-free diagnostic events.
22//! - [`tools`]     — the two front-door MCP tools over all of the above.
23pub mod artifacts;
24pub mod canon;
25pub mod catalogue;
26pub mod code;
27pub mod commands;
28pub use crate::declarations;
29pub mod diag;
30pub mod event_journal;
31pub mod event_archive;
32pub mod webhooks;
33pub mod journal;
34pub(crate) mod inputs;
35pub mod keys;
36pub mod ops;
37pub mod output_schema;
38pub mod surface;
39pub mod tools;
40pub mod wire;
41
42use std::sync::Arc;
43
44/// Everything the `cad_*` tools share for the life of the server process:
45/// the service is process-scoped, not connection- or session-scoped, so an
46/// accepted operation outlives the request that submitted it.
47mod files;
48
49pub struct CadService {
50    pub files: files::Files,
51    pub event_archive: std::sync::OnceLock<event_archive::Archive>,
52    /// Webhook deliveries of every event, to operator- and client-registered URLs.
53    pub webhooks: webhooks::Webhooks,
54    pub ops: ops::Operations,
55    pub artifacts: artifacts::Artifacts,
56    pub code: code::Executions,
57    pub catalogue: catalogue::Catalogue,
58    /// This server's own script functions (`sdk.document.list`,
59    /// `sdk.operations.submit`, ...), beside the registry's tools.
60    pub services: Vec<crate::script_sdk::ServiceEntry>,
61    /// The server whose tool registry scripts call as
62    /// `sdk.<namespace>.<action>` (set once by `BrepServer::new`).
63    pub server: std::sync::OnceLock<std::sync::Weak<crate::server::ServerState>>,
64    /// `run`'s retry keys: a client's key → the issued key it stands
65    /// for. Here, not in the tool, because the tool set is rebuilt whenever
66    /// a session starts — the first submission's own session among them.
67    pub retry_keys: std::sync::Mutex<std::collections::HashMap<String, String>>,
68}
69
70pub use crate::script_sdk::{script_callable, ScriptTool};
71
72impl CadService {
73    pub fn new(slot: crate::tools::app::SessionSlot) -> Arc<Self> {
74        let catalogue = catalogue::Catalogue::new();
75        Arc::new_cyclic(|weak| CadService {
76            files: files::Files::new(),
77            event_archive: Default::default(),
78            webhooks: Default::default(),
79            ops: ops::Operations::new(slot, weak.clone()),
80            artifacts: artifacts::Artifacts::new(),
81            code: code::Executions::new(weak.clone()),
82            services: surface::service_entries(&catalogue),
83            catalogue,
84            server: std::sync::OnceLock::new(),
85            retry_keys: Default::default(),
86        })
87    }
88
89    pub fn event(&self, kind: &'static str, id: Option<&str>, state: Option<&str>, code: Option<&str>, sequence: Option<u64>) {
90        let value = diag::event(kind, id, state, code, sequence);
91        self.webhooks.publish(&value);
92        if let Some(archive) = self.event_archive.get() { archive.publish(value); }
93    }
94
95    pub fn archive_resource(&self, uri: &str) -> Result<serde_json::Value, String> {
96        match self.event_archive.get() {
97            Some(archive) => archive.resource(uri),
98            None if uri == "brep://events/archive" => Ok(serde_json::json!({"enabled":false,"records":[],"persistence":{"status":"disabled"}})),
99            None => Err("diagnostic archive is disabled".into()),
100        }
101    }
102
103    pub(crate) fn server_state(&self) -> Option<Arc<crate::server::ServerState>> {
104        self.server.get().and_then(std::sync::Weak::upgrade)
105    }
106
107    /// The registry tools a script may call, as of now (a live session adds
108    /// the app's). Blocking: called from a code worker's host thread.
109    pub fn script_tools(&self) -> Vec<ScriptTool> {
110        let Some(state) = self.server_state() else { return vec![] };
111        let set = state.tools.blocking_read();
112        crate::script_sdk::script_tools(&set.specs)
113    }
114
115    /// One script-callable registry tool by name.
116    pub async fn script_tool(&self, name: &str) -> Option<crate::tools::ToolSpec> {
117        let state = self.server_state()?;
118        // By name AND a script-callable group: the front door's `screenshot`
119        // shares its name with the capture tool a script calls.
120        let set = state.tools.read().await;
121        set.specs.iter().find(|t| t.name == name && script_callable(t.group, &t.name)).cloned()
122    }
123
124    /// The contracts of 1..8 script functions by path (`scene.entities`,
125    /// with or without `sdk.`), as `brep://api/function/<path>` serves them.
126    /// An old `brep.<group>.<tool>` spelling still names its registry tool.
127    pub async fn describe(&self, paths: &[String]) -> Result<serde_json::Value, wire::ApiError> {
128        use serde_json::json;
129        if paths.is_empty() || paths.len() > 8 { return Err(wire::ApiError::new("invalid_arguments", "validation", "describe takes 1..8 paths")); }
130        let state = self.server_state();
131        let empty = crate::tools::ToolSet::default();
132        let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
133        let surface = self.surface(guard.as_deref().unwrap_or(&empty), None);
134        let mut methods = Vec::new();
135        for path in paths {
136            let registry = |old: &str| {
137                let (group, tool) = old.split_once('.')?;
138                surface.entries.iter().find(|e| matches!(e.target, crate::script_sdk::Target::Tool(t) if crate::script_sdk::ident(t.group) == group && (t.name == tool || t.name == format!("files_{tool}"))))
139            };
140            let entry = surface.get(path).or_else(|| path.strip_prefix("brep.").and_then(registry))
141                .ok_or_else(|| wire::ApiError::new("method_unknown", "lookup", surface.unknown(path)))?;
142            methods.push(entry.to_json());
143        }
144        let result = json!({"manifest":self.catalogue.identity(),"version":surface.version(),"methods":methods});
145        if result.to_string().len() > 64 << 10 { return Err(wire::ApiError::new("resource_limit", "validation", "describe fewer paths")); }
146        Ok(result)
147    }
148
149    /// Run a program for the app itself (its JavaScript editor): the local
150    /// user, trusted as the MCP's `run` is — every app tool, no
151    /// execution control. Must be called inside the server's tokio runtime
152    /// (`Handle::enter`); returns at once with the execution id.
153    pub fn run_local(&self, source: &str) -> Result<String, String> {
154        let caller = tools::caller_of_transport();
155        let (key, _) = keys::issue(&caller.scope, keys::Purpose::Execution);
156        let req = serde_json::json!({
157            "manifest": self.catalogue.identity(),
158            "source": source,
159            "initialDocuments": [],
160            "requestedCapabilities": [],
161            "idempotencyKey": key,
162        });
163        let status = self.code.submit_as(&caller, &req, true).map_err(|e| e.message)?;
164        Ok(status["executionId"].as_str().unwrap_or_default().to_string())
165    }
166
167    /// A [`Self::run_local`] execution's result once it has ended (`None`
168    /// while it runs), with its console lines as `logText`.
169    pub fn result_local(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
170        let caller = tools::caller_of_transport();
171        match self.code.result(&caller, &serde_json::json!({ "executionId": id })) {
172            Ok(mut result) => {
173                let log = result["logArtifact"]["artifactId"].as_str().map(str::to_string);
174                if let Some(log) = log {
175                    if let Ok((bytes, _)) = self.artifacts.lease(&caller.owner(), &log) {
176                        self.artifacts.release(&log);
177                        result["logText"] = String::from_utf8_lossy(&bytes).into_owned().into();
178                    }
179                }
180                Ok(Some(result))
181            }
182            Err(e) if e.code == "not_ready" => Ok(None),
183            Err(e) => Err(e.message),
184        }
185    }
186
187    /// Halt a [`Self::run_local`] execution: its worker is killed.
188    pub fn halt_local(&self, id: &str) -> Result<(), String> {
189        let caller = tools::caller_of_transport();
190        self.code.cancel(&caller, &serde_json::json!({ "executionId": id })).map(|_| ()).map_err(|e| e.message)
191    }
192}
193
194/// The app's own handle on code mode, for its JavaScript editor: the
195/// server's [`CadService`] and the runtime it runs on, so a frame can submit,
196/// poll and halt without awaiting anything.
197#[derive(Clone)]
198pub struct LocalScripts {
199    cad: std::sync::Weak<CadService>,
200    runtime: tokio::runtime::Handle,
201}
202
203impl std::fmt::Debug for LocalScripts {
204    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205        f.write_str("LocalScripts")
206    }
207}
208
209impl LocalScripts {
210    pub fn new(cad: &Arc<CadService>, runtime: tokio::runtime::Handle) -> Self {
211        LocalScripts { cad: Arc::downgrade(cad), runtime }
212    }
213
214    fn cad(&self) -> Result<Arc<CadService>, String> {
215        self.cad.upgrade().ok_or_else(|| "the script runner has stopped".to_string())
216    }
217
218    /// Whether the app's tools are registered (a program's `sdk` names are
219    /// read from them at submit). Never blocks.
220    pub fn ready(&self) -> Result<bool, String> {
221        let state = self.cad()?.server_state().ok_or("the server is stopping")?;
222        Ok(state.tools.try_read().is_ok_and(|set| set.specs.iter().any(|t| t.name == "docs_list")))
223    }
224
225    pub fn run(&self, source: &str) -> Result<String, String> {
226        let _enter = self.runtime.enter();
227        self.cad()?.run_local(source)
228    }
229
230    pub fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
231        self.cad()?.result_local(id)
232    }
233
234    pub fn halt(&self, id: &str) -> Result<(), String> {
235        let _enter = self.runtime.enter();
236        self.cad()?.halt_local(id)
237    }
238}