Skip to main content

brep_mcp_core/
server.rs

1//! The dynamic `rmcp::ServerHandler`.
2//!
3//! rmcp's `#[tool]` / `#[tool_router]` macros build a static tool table at
4//! compile time, which is exactly what this server must not have: its tools
5//! come from registries read at session start. So the handler implements the
6//! dynamic side of the trait by hand — `tools/list` and `tools/call` walk a
7//! [`ToolSet`], `resources/list` and `resources/read` walk a [`ResourceSet`] —
8//! and advertises `tools.listChanged` so a session can swap the set.
9use crate::host::Backend;
10use crate::tools::{ToolSet, ToolSpec};
11use base64::Engine as _;
12use rmcp::model::{
13    CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation,
14    ListResourcesResult, ListToolsResult, PaginatedRequestParams, ProtocolVersion, ReadResourceRequestParams,
15    ReadResourceResponse, ReadResourceResult, Resource, ResourceContents, ServerCapabilities, ServerInfo,
16    SubscriptionFilter, Tool, ToolAnnotations,
17};
18use rmcp::service::{NotificationContext, RequestContext, RoleServer, SubscriptionContext, SubscriptionSink};
19use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt};
20use serde_json::{Map, Value};
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::Mutex;
23use std::{future::Future, sync::Arc};
24use tokio::sync::RwLock;
25
26/// Delegate version negotiation to the SDK while narrowing legacy discovery.
27struct InitializationInfo(ServerInfo);
28impl ServerHandler for InitializationInfo {
29    fn get_info(&self) -> ServerInfo { self.0.clone() }
30}
31
32/// A resource the server can list and read. Like tools, resources are produced
33/// by walking registries; this is only the shape they arrive in.
34#[derive(Clone)]
35pub struct ResourceSpec {
36    pub uri: String,
37    pub name: String,
38    pub description: String,
39    pub mime: &'static str,
40    pub read: Arc<dyn Fn() -> Result<String, String> + Send + Sync>,
41}
42
43#[derive(Default, Clone)]
44pub struct ResourceSet {
45    pub specs: Vec<ResourceSpec>,
46}
47
48impl ResourceSet {
49    pub fn get(&self, uri: &str) -> Option<&ResourceSpec> {
50        self.specs.iter().find(|r| r.uri == uri)
51    }
52}
53
54/// Resources that need no app session: the feature catalogue as JSON Schema
55/// and the script format. Everything else arrives with a session's registries.
56pub fn engine_resources() -> ResourceSet { engine_resources_with(crate::skills::Catalogue::embedded()) }
57
58/// The engine resources, serving `skills`' SKILL.md texts.
59pub fn engine_resources_with(skills: &crate::skills::Catalogue) -> ResourceSet {
60    let mut specs = vec![
61        ResourceSpec {
62            uri: "brep://api/commands".into(), name: "application-functions".into(),
63            description: "Every script function, sdk.<namespace>.<action>, with its description, argument and result schemas (large; the sdk tool answers one at a time).".into(),
64            mime: "application/json", read: Arc::new(|| Ok("{}".into())),
65        },
66        ResourceSpec {
67            uri: "brep://schema/features".into(),
68            name: "feature-schemas".into(),
69            description: "Every feature in the kernel catalogue with its inputParams JSON Schema and defaults".into(),
70            mime: "application/json",
71            read: Arc::new(|| serde_json::to_string_pretty(&crate::schema::all()).map_err(|e| e.to_string())),
72        },
73        ResourceSpec {
74            uri: "brep://schema/sketch".into(),
75            name: "sketch-persistent-data".into(),
76            description: "The persistentData block a sketch feature carries — the profile geometry Extrude and Revolve consume — with a working example".into(),
77            mime: "application/json",
78            read: Arc::new(|| {
79                serde_json::to_string_pretty(&serde_json::json!({
80                    "schema": crate::schema::sketch_persistent_schema(),
81                    "example": crate::schema::sketch_example(),
82                }))
83                .map_err(|e| e.to_string())
84            }),
85        },
86        ResourceSpec {
87            uri: "brep://script/format".into(),
88            name: "script-format".into(),
89            description: "JSON Schema of the test-mcp script format".into(),
90            mime: "application/json",
91            read: Arc::new(|| serde_json::to_string_pretty(&crate::script::Script::json_schema()).map_err(|e| e.to_string())),
92        },
93    ];
94    // The CAD API's manifest and one descriptor per method (contract §4),
95    // for focused access without listing the whole catalogue in context.
96    let catalogue = crate::cad::catalogue::Catalogue::new();
97    let manifest = catalogue.manifest_json.clone();
98    let identity = catalogue.identity();
99    specs.push(ResourceSpec {
100        uri: "brep://cad/manifest".into(),
101        name: "cad-manifest".into(),
102        description: "The operation commands' manifest identity {apiVersion, sha256} and their paths (what sdk.operations.submit and sdk.commands.query take as `command`)".into(),
103        mime: "application/json",
104        read: Arc::new(move || {
105            let paths: Vec<&Value> = manifest["methods"].as_array().into_iter().flatten().map(|m| &m["path"]).collect();
106            serde_json::to_string_pretty(&serde_json::json!({ "manifest": identity, "methods": paths })).map_err(|e| e.to_string())
107        }),
108    });
109    for descriptor in &catalogue.descriptors {
110        let json = descriptor.to_json();
111        specs.push(ResourceSpec {
112            uri: format!("brep://cad/method/{}", descriptor.path.replace('%', "%25")),
113            name: format!("cad-method-{}", descriptor.path),
114            description: descriptor.summary.to_string(),
115            mime: "application/json",
116            read: Arc::new(move || serde_json::to_string_pretty(&json).map_err(|e| e.to_string())),
117        });
118    }
119    for entry in crate::schema::entries() {
120        let id = crate::schema::identity(&entry);
121        let ty = id.feature_type.clone();
122        specs.push(ResourceSpec {
123            uri: format!("brep://schema/features/{}", id.feature_type),
124            name: format!("feature-schema-{}", id.feature_type),
125            description: format!("inputParams JSON Schema and defaults of {}", id.long_name),
126            mime: "application/json",
127            read: Arc::new(move || {
128                let entry = crate::schema::entry(&ty).ok_or_else(|| format!("no feature `{ty}`"))?;
129                serde_json::to_string_pretty(&serde_json::json!({
130                    "schema": crate::schema::to_json_schema(&entry),
131                    "defaults": crate::schema::defaults(&ty),
132                }))
133                .map_err(|e| e.to_string())
134            }),
135        });
136    }
137    for (uri, name, description) in [("brep://events/archive", "diagnostic-archive", "Opt-in bounded metadata history across restarts; reports disabled or persistence health"), ("brep://events", "diagnostic-events", "Bounded payload-free events; reconcile state after a sequence gap"), ("brep://documents", "open-documents", "Open document identities and revisions; subscribable") ] {
138        specs.push(ResourceSpec { uri: uri.into(), name: name.into(), description: description.into(), mime:"application/json", read: Arc::new(|| Ok("{}".into())) });
139    }
140    for &skill in &skills.skills {
141        specs.push(ResourceSpec { uri: skill.uri(), name: skill.name.into(), description: skill.description.into(), mime: "text/markdown", read: Arc::new(move || Ok(skill.text.into())) });
142    }
143    ResourceSet { specs }
144}
145
146pub const INSTRUCTIONS: &str = "BREP CAD automation. Two tools: sdk describes what a program can call, run runs a program. \
147A program is a JavaScript script body with top-level await and return: \
148const docs = await sdk.document.docs_list({}); return { open: docs.tabs.length }; \
149sdk is a global: every application function is await sdk.<namespace>.<action>(args), one object argument. \
150Discover them with the sdk tool: sdk({}) lists the namespaces and guides, sdk({topic: 'scene'}) a namespace's actions, \
151sdk({topic: 'scene.mass_properties'}) one TypeScript signature, sdk({query: 'fillet edge'}) searches. \
152Use skills/list to discover optional workflows and resources/read to load a selected skill. \
153Use document identities and expected revisions when editing; await writes sequentially and inspect the result before saving. \
154Supply a unique retry key for each program and reuse it after a lost response; run({executionId}) fetches a result again and run({executionId, halt: true}) stops a program. \
155Scripts may have partial effects; halting a script does not undo changes or cancel accepted CAD operations. \
156The local credential grants application and file access. Coordinates are egui points, origin top-left. \
157Return compact summaries and artifact references; return sdk.capture.screenshot's result to get its image inline. \
158Before building or substantially editing a part or assembly, read the design guide: sdk({topic: 'guide.design-part'}) (the resource skill://design-part/SKILL.md). \
159Design rules: one document per part, joined by assembly components and constraints that leave only the intended freedom; drive editable sizes from expressions; \
160sketch true arcs and splines, use Hole features for fastener holes and Pattern for repeats; fillets and chamfers go last; check featureErrors, solid count and volume after every feature. \
161Author drawings, PDFs and instruction viewers only with the application's own functions, inspecting every exported page; say so when they cannot do what was asked.";
162
163/// Everything the handler shares across requests: the tool and resource sets
164/// (rebuilt from the registries whenever a session starts or stops), the
165/// session slot, and who to tell when the tool list changes.
166pub struct ServerState {
167    pub tools: RwLock<ToolSet>,
168    pub resources: RwLock<ResourceSet>,
169    pub slot: crate::tools::app::SessionSlot,
170    pub session_root: std::path::PathBuf,
171    pub session_start: tokio::sync::Mutex<()>,
172    /// Where sessions run: spawned per session, or the app this server is in.
173    pub backend: Backend,
174    /// The last client to initialise: where a *legacy* client (protocol before
175    /// `2026-07-28`) receives a bare `tools/list_changed`.
176    pub peer: Mutex<Option<rmcp::service::Peer<RoleServer>>>,
177    /// The open `subscriptions/listen` streams: where a modern client receives
178    /// `tools/list_changed`, tagged with its subscription. One per connection
179    /// that asked — the HTTP host serves several at once.
180    pub listeners: Mutex<Vec<Listener>>,
181    next_listener: AtomicU64,
182    /// The operation service: process-scoped, so an accepted
183    /// operation outlives the connection and the request that submitted it.
184    pub cad: Arc<crate::cad::CadService>,
185    /// Tools a HOST adds to every tool set this server composes, whatever the
186    /// session does: the test-mcp runner's own `runner` group (its PLM
187    /// fixture, step records, `session_restart`), which a script reaches as
188    /// `sdk.runner.<tool>` and which must survive the rebuild a session
189    /// restart makes. Empty unless a host sets it.
190    pub extra_tools: Mutex<Vec<ToolSpec>>,
191    /// The skills this server serves: an installed version
192    /// ([`BrepServer::with_skills_dir`]), else the embedded bundle.
193    skills: std::sync::OnceLock<Arc<crate::skills::Catalogue>>,
194}
195
196/// One open `subscriptions/listen` stream. `seq` tells two apart: request ids
197/// (`listen:1`) repeat across connections.
198pub struct Listener {
199    seq: u64,
200    sink: SubscriptionSink,
201}
202
203/// Removes a listener from the state when its `listen` future ends — by
204/// cancellation, or by being dropped with the connection.
205struct ListenerGuard {
206    state: Arc<ServerState>,
207    seq: u64,
208}
209
210impl Drop for ListenerGuard {
211    fn drop(&mut self) {
212        self.state.listeners.lock().unwrap().retain(|l| l.seq != self.seq);
213    }
214}
215
216#[derive(Clone)]
217pub struct BrepServer {
218    pub state: Arc<ServerState>,
219}
220
221impl BrepServer {
222    /// A server that runs sessions on `backend`, keeping their directories
223    /// under `session_root`. Usable from inside or outside a runtime: nothing
224    /// here blocks.
225    pub fn new(session_root: std::path::PathBuf, backend: Backend) -> Self {
226        let slot = Arc::new(RwLock::new(None));
227        let state = Arc::new(ServerState {
228            tools: RwLock::new(ToolSet::default()),
229            resources: RwLock::new(engine_resources()),
230            cad: crate::cad::CadService::new(slot.clone()),
231            extra_tools: Mutex::new(Vec::new()),
232            slot,
233            session_root,
234            session_start: tokio::sync::Mutex::new(()),
235            backend,
236            peer: Mutex::new(None),
237            listeners: Mutex::new(Vec::new()),
238            next_listener: AtomicU64::new(0),
239            skills: std::sync::OnceLock::new(),
240        });
241        let _ = state.cad.server.set(Arc::downgrade(&state));
242        let server = Self { state: state.clone() };
243        // The initial tool set: catalogue tools + session tools. Built
244        // synchronously so `tools/list` is right from the first request.
245        let initial = server.compose_tools(None);
246        *state.tools.try_write().expect("a freshly built server has no readers") = ToolSet::new(initial);
247        server
248    }
249
250    /// Seed discovery from the host's static command registry without starting
251    /// an application, renderer or GPU. Execution still starts a session lazily.
252    pub fn with_commands(self, describe: &Value) -> Self {
253        *self.state.tools.try_write().expect("unserved server") = ToolSet::new(self.compose_tools(Some(describe)));
254        self
255    }
256
257    /// Enable restart-safe admission/outcomes for a named local server. The
258    /// directory must be private and must not be shared by live servers.
259    pub fn with_state_dir(self, directory: &std::path::Path) -> Result<Self, String> {
260        self.state.cad.code.configure_persistence(directory)?;
261        Ok(self)
262    }
263
264    /// Standard Tasks adapts the existing process-scoped execution records.
265    /// A task outlives its HTTP request; a server restart invalidates its epoch.
266    fn execution_task(&self, id: &str) -> Result<rmcp::model::DetailedTask, McpError> {
267        use rmcp::model::{Task, TaskStatus, TaskPayload, DetailedTask};
268        let caller = crate::cad::tools::caller_of_transport();
269        let req = serde_json::json!({"executionId":id});
270        let status = self.state.cad.code.status(&caller, &req).map_err(|e| McpError::invalid_params(e.message, None))?;
271        let created = status["acceptedAt"].as_str().unwrap_or_default();
272        let result = self.state.cad.code.result(&caller, &req);
273        let updated = status["updatedAt"].as_str().unwrap_or(created);
274        let task = Task::new(id, TaskStatus::Working, created, updated)
275            .with_ttl_ms(30 * 60 * 1000).with_poll_interval_ms(500)
276            .with_status_message(format!("{}; {}; accepted CAD operations survive script cancellation", status["state"].as_str().unwrap_or("working"),
277                if self.state.cad.code.persistent() { "durable record; interrupted work requires reconciliation" } else { "process-scoped" }));
278        let payload = match result {
279            Ok(r) if r["state"] == "cancelled" => TaskPayload::Cancelled,
280            Ok(r) => {
281                let failed = r["state"] == "failed";
282                let value = crate::cad::wire::ok(r);
283                // The same reply `run` gives when it awaits: the pictures the
284                // program returned ride as image content.
285                let images = crate::cad::tools::execution_images(&self.state.cad, &caller, &value);
286                let mut response = if failed { CallToolResult::structured_error(value) } else { CallToolResult::structured(value) };
287                response.content.extend(image_blocks(images));
288                TaskPayload::Completed { result: serde_json::to_value(response).unwrap().as_object().unwrap().clone() }
289            }
290            Err(e) if e.code == "not_ready" => {
291                let input_requests = self.state.cad.code.input_requests(&caller, id).map_err(|e| McpError::invalid_params(e.message, None))?;
292                if input_requests.is_empty() { TaskPayload::Working } else { TaskPayload::InputRequired { input_requests } }
293            },
294            Err(e) => return Err(McpError::invalid_params(e.message, None)),
295        };
296        Ok(DetailedTask::new(task, payload))
297    }
298
299    /// Serve the skill version selected in an installer-managed directory
300    /// (`brep-mcp skills install` / `rollback`) instead of the embedded one.
301    /// Verified once here, before serving; a later install or rollback takes
302    /// effect on restart.
303    pub fn with_skills_dir(self, directory: &std::path::Path) -> Result<Self, String> {
304        let catalogue = Arc::new(crate::skill_distribution::load_active(directory)?);
305        *self.state.resources.try_write().map_err(|_| "configure skills before serving")? = engine_resources_with(&catalogue);
306        self.state.skills.set(catalogue).map_err(|_| "skills already configured")?;
307        Ok(self)
308    }
309
310    /// Deliver every diagnostic event to an operator-configured webhook
311    /// (`brep-mcp serve --event-webhook`), signed with `secret`.
312    pub fn with_event_webhook(self, url: &str, secret: &[u8]) -> Result<Self, String> {
313        self.state.cad.webhooks.register(url, secret.to_vec(), crate::cad::webhooks::Origin::Operator)?;
314        Ok(self)
315    }
316
317    /// Enable the independent metadata-only diagnostic archive before serving.
318    /// This performs startup disk I/O; call outside the async request path.
319    pub fn with_event_journal(self, directory: &std::path::Path) -> Result<Self, String> {
320        let archive = crate::cad::event_archive::Archive::open(directory)?;
321        self.state.cad.event_archive.set(archive).map_err(|_| "diagnostic archive already configured")?;
322        Ok(self)
323    }
324
325    async fn observed_resource(&self, uri: &str) -> Result<Value, String> {
326        if uri == "brep://events/archive" || uri.starts_with("brep://events/archive/") { return self.state.cad.archive_resource(uri); }
327        let caller = crate::cad::tools::caller_of_transport();
328        if uri == "brep://events" || uri.starts_with("brep://events/replay/") { return crate::cad::diag::resource(uri); }
329        if uri == "brep://documents" {
330            if self.state.slot.read().await.is_none() { return Ok(serde_json::json!({"documents":[]})); }
331            return self.state.cad.ops.documents(&caller, None).await.map_err(|e| e.message);
332        }
333        if let Some(id) = uri.strip_prefix("brep://execution/") {
334            return self.state.cad.code.status(&caller, &serde_json::json!({"executionId":id})).map_err(|e| e.message);
335        }
336        Err("unknown observable resource".into())
337    }
338
339    /// The registry-independent server: catalogue tools and resources only
340    /// (what `brep-mcp schema` and the unit tests use).
341    pub fn engine_only() -> Self {
342        let slot = Arc::new(RwLock::new(None));
343        let state = Arc::new(ServerState {
344            tools: RwLock::new(ToolSet::new(crate::tools::engine_tools())),
345            resources: RwLock::new(engine_resources()),
346            cad: crate::cad::CadService::new(slot.clone()),
347            extra_tools: Mutex::new(Vec::new()),
348            slot,
349            session_root: std::env::temp_dir(),
350            session_start: tokio::sync::Mutex::new(()),
351            backend: Backend::Spawn { name: "none", spawn: Arc::new(|_| Err("this server hosts no app".into())) },
352            peer: Mutex::new(None),
353            listeners: Mutex::new(Vec::new()),
354            next_listener: AtomicU64::new(0),
355            skills: std::sync::OnceLock::new(),
356        });
357        let _ = state.cad.server.set(Arc::downgrade(&state));
358        Self { state }
359    }
360
361    /// For an attached backend: make the running app the live session now, so
362    /// the tool list carries its commands from the first `tools/list` (the
363    /// HTTP transport may serve requests statelessly, where a later
364    /// `tools/list_changed` reaches nobody). Returns the session info.
365    pub async fn attach(&self, record: bool) -> Result<crate::session::SessionInfo, String> {
366        let cx = self.context();
367        let session = crate::tools::compose::attach_session(&cx, record).await?;
368        self.rebuild_tools().await;
369        Ok(session.info())
370    }
371
372    fn context(&self) -> Arc<crate::tools::compose::ServerContext> {
373        let weak = Arc::downgrade(&self.state);
374        Arc::new(crate::tools::compose::ServerContext {
375            slot: self.state.slot.clone(),
376            session_root: self.state.session_root.clone(),
377            backend: self.state.backend.clone(),
378            cad: Arc::downgrade(&self.state.cad),
379            on_tools_changed: Arc::new(move || {
380                if let Some(state) = weak.upgrade() {
381                    let server = BrepServer { state };
382                    tokio::spawn(async move { server.rebuild_tools().await });
383                }
384            }),
385        })
386    }
387
388    /// The whole tool list for the current state: catalogue + session tools,
389    /// and — when a session is live — every command the app describes plus
390    /// the server-side compositions.
391    fn compose_tools(&self, describe: Option<&Value>) -> Vec<ToolSpec> {
392        let cx = self.context();
393        let slot = self.state.slot.clone();
394        let mut tools = crate::tools::session_engine_tools(slot.clone());
395        tools.extend(crate::tools::compose::described_session_tools(cx, describe));
396        let front_door = crate::cad::tools::front_door_tools(self.state.cad.clone(), slot.clone());
397        if let Some(describe) = describe {
398            tools.extend(crate::tools::app::app_tools(slot.clone(), describe));
399            tools.extend(crate::tools::compose::described_pointer_tools(slot.clone(), describe));
400            tools.extend(crate::tools::compose::described_capture_tools(slot.clone(), describe));
401            tools.extend(crate::tools::compose::document_tools(slot.clone(), describe));
402            tools.extend(crate::tools::compose::feature_tools(slot.clone(), describe));
403            tools.extend(crate::tools::compose::registry_tools(slot));
404        }
405        let service = self.state.cad.clone();
406        tools.extend(crate::files::script_tools(Arc::new(move |args| {
407            let service = service.clone();
408            Box::pin(async move { service.files.call(&service, &crate::cad::ops::Caller::local(), args).await })
409        })));
410        tools.extend(self.state.extra_tools.lock().unwrap().iter().cloned());
411        tools.extend(front_door);
412        tools
413    }
414
415    /// Regenerate the tool set from the live session's command registry (or
416    /// back to the sessionless set) and tell the client the list changed.
417    pub async fn rebuild_tools(&self) {
418        let describe = {
419            let session = self.state.slot.read().await.clone();
420            match session {
421                Some(s) => s.host.call_ok("describe_commands", serde_json::json!({ "full": true })).await.ok().and_then(|r| r.result),
422                None => None,
423            }
424        };
425        let tools = self.compose_tools(describe.as_ref());
426        *self.state.tools.write().await = ToolSet::new(tools);
427        self.notify_tool_list_changed().await;
428        let sinks: Vec<_> = self.state.listeners.lock().unwrap().iter().map(|l| l.sink.clone()).collect();
429        for sink in sinks { if sink.accepted().resources_list_changed == Some(true) { let _ = tokio::time::timeout(std::time::Duration::from_secs(5), sink.notify_resource_list_changed()).await; } }
430    }
431
432    /// Tell every client the tool list changed. A modern client hears it on
433    /// its `subscriptions/listen` stream (and only there: a bare notification
434    /// is not addressed to a subscription, so it ignores one); a legacy client
435    /// hears it on the connection itself. A stream that cannot take the
436    /// notification is finished, and is forgotten.
437    async fn notify_tool_list_changed(&self) {
438        let sinks: Vec<(u64, SubscriptionSink)> = {
439            let listeners = self.state.listeners.lock().unwrap();
440            listeners
441                .iter()
442                .filter(|l| l.sink.accepted().tools_list_changed == Some(true))
443                .map(|l| (l.seq, l.sink.clone()))
444                .collect()
445        };
446        for (seq, sink) in sinks {
447            if !matches!(tokio::time::timeout(std::time::Duration::from_secs(5), sink.notify_tool_list_changed()).await, Ok(Ok(()))) {
448                self.state.listeners.lock().unwrap().retain(|l| l.seq != seq);
449            }
450        }
451        let peer = self.state.peer.lock().unwrap().clone();
452        if let Some(peer) = peer {
453            let legacy = peer.peer_info().is_none_or(|info| info.protocol_version < ProtocolVersion::V_2026_07_28);
454            if legacy {
455                let _ = tokio::time::timeout(std::time::Duration::from_secs(5), peer.notify_tool_list_changed()).await;
456            }
457        }
458    }
459}
460
461fn to_rmcp_tool(spec: &ToolSpec) -> Tool {
462    let schema: Map<String, Value> = spec.input_schema.as_object().cloned().unwrap_or_default();
463    let mut tool = Tool::new(spec.name.clone(), spec.doc.clone(), Arc::new(schema));
464    let mut ann = ToolAnnotations::default();
465    ann.read_only_hint = Some(spec.annotations.read_only);
466    ann.destructive_hint = Some(spec.annotations.destructive);
467    ann.idempotent_hint = Some(spec.annotations.idempotent);
468    // A program reaches whatever the app reaches (files, a PLM server);
469    // `sdk` answers from this server's own catalogue.
470    ann.open_world_hint = Some(spec.name == "run");
471    tool.annotations = Some(ann);
472    tool.output_schema = Some(Arc::new(spec.output_schema.as_object().cloned().unwrap_or_else(|| serde_json::json!({"type":"object"}).as_object().unwrap().clone())));
473    tool
474}
475
476/// A tool's pictures as MCP image content.
477fn image_blocks(images: Vec<crate::tools::ToolImage>) -> impl Iterator<Item = ContentBlock> {
478    images.into_iter().map(|image| ContentBlock::image(base64::engine::general_purpose::STANDARD.encode(&image.png), image.mime))
479}
480
481/// How long a client may keep a list (SEP-2549). Clients on protocol
482/// `2026-07-28` (Claude Code, 2026-09) reject a list result without `ttlMs`
483/// and `cacheScope`. Lists are per session — private — and change when a
484/// session starts or stops, which `tools/list_changed` announces; a minute
485/// bounds a client that missed the notification.
486const LIST_TTL_MS: u64 = 60_000;
487
488fn cacheable(result: ListToolsResult) -> ListToolsResult {
489    result.with_ttl_ms(LIST_TTL_MS).with_cache_scope(CacheScope::Private)
490}
491
492
493fn to_rmcp_resource(spec: &ResourceSpec) -> Resource {
494    let mut r = Resource::new(spec.uri.clone(), spec.name.clone());
495    r.description = Some(spec.description.clone());
496    r.mime_type = Some(spec.mime.to_string());
497    r
498}
499
500impl ServerHandler for BrepServer {
501    fn initialize(&self, request: rmcp::model::InitializeRequestParams, context: RequestContext<RoleServer>) -> impl Future<Output = Result<rmcp::model::InitializeResult, McpError>> + Send + '_ {
502        async move {
503            let mut info = self.get_info();
504            if request.protocol_version.as_str() < ProtocolVersion::V_2026_07_28.as_str() {
505                // Notifications use subscriptions/listen, not the deprecated
506                // resources/subscribe lifecycle. Legacy clients poll resources
507                // and use run's executionId forms rather than Tasks.
508                if let Some(resources) = &mut info.capabilities.resources {
509                    resources.subscribe = None;
510                    resources.list_changed = None;
511                }
512                if let Some(extensions) = &mut info.capabilities.extensions {
513                    extensions.remove(rmcp::model::TASKS_EXTENSION_ID);
514                    extensions.remove(crate::skills::EXTENSION);
515                }
516            }
517            InitializationInfo(info).initialize(request, context).await
518        }
519    }
520    fn get_info(&self) -> ServerInfo {
521        let mut caps = ServerCapabilities::builder()
522            .enable_prompts()
523            .enable_tools()
524            .enable_tool_list_changed()
525            .enable_resources()
526            .enable_resources_subscribe()
527            .enable_resources_list_changed()
528            .enable_tasks()
529            .build();
530        let extensions = caps.extensions.get_or_insert_with(Default::default);
531        extensions.insert(crate::skills::EXTENSION.into(), Default::default());
532        extensions.insert(crate::cad::webhooks::EXTENSION.into(), Default::default());
533        ServerInfo::new(caps)
534            .with_instructions(INSTRUCTIONS)
535            .with_server_info(Implementation::new("brep-mcp", env!("CARGO_PKG_VERSION")))
536    }
537
538    fn list_prompts(&self, request: Option<PaginatedRequestParams>, _context: RequestContext<RoleServer>) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, McpError>> + Send + '_ {
539        std::future::ready(crate::prompts::list_from(self.state.skills(), request.as_ref().and_then(|p| p.cursor.as_deref())))
540    }
541
542    fn get_prompt(&self, request: rmcp::model::GetPromptRequestParams, _context: RequestContext<RoleServer>) -> impl Future<Output = Result<rmcp::model::GetPromptResponse, McpError>> + Send + '_ {
543        std::future::ready(crate::prompts::get_from(self.state.skills(), request).map(Into::into))
544    }
545
546    fn on_custom_request(&self, request: rmcp::model::CustomRequest, _context: RequestContext<RoleServer>) -> impl Future<Output = Result<rmcp::model::CustomResult, McpError>> + Send + '_ {
547        async move {
548            let params = request.params.unwrap_or(serde_json::json!({}));
549            let result = match request.method.as_str() {
550                "skills/list" | "skills/get" => self.state.skills().request(&request.method, &params),
551                method if method.starts_with("events/webhooks/") => self.state.cad.webhooks.request(method, &params),
552                _ => return Err(McpError::new(rmcp::model::ErrorCode::METHOD_NOT_FOUND, "unknown method", None)),
553            };
554            result.map(rmcp::model::CustomResult::new).map_err(|e| McpError::invalid_params(e, None))
555        }
556    }
557
558    /// The client that just initialised is the one `tools/list_changed` goes to.
559    fn on_initialized(&self, context: NotificationContext<RoleServer>) -> impl Future<Output = ()> + Send + '_ {
560        *self.state.peer.lock().unwrap() = Some(context.peer);
561        std::future::ready(())
562    }
563
564    /// `subscriptions/listen` (protocol `2026-07-28`): the stream a modern
565    /// client opens right after `server/discover`, and where
566    /// `tools/list_changed` reaches it. Accept whatever it asks for that the capabilities
567    /// advertise; a server that leaves this unimplemented answers
568    /// method-not-found, which the HTTP transport maps to a 404 and the
569    /// client reads as a dropped connection.
570    fn accepted_subscription_filter(&self, requested: &SubscriptionFilter) -> Option<SubscriptionFilter> {
571        let mut accepted = requested.supported_by(&self.get_info().capabilities);
572        if let Some(uris) = &mut accepted.resource_subscriptions {
573            uris.retain(|uri| matches!(uri.as_str(), "brep://events" | "brep://documents") || uri.starts_with("brep://execution/"));
574            uris.truncate(32);
575        }
576        Some(accepted)
577    }
578
579    /// Hold the stream open until the client cancels it or the connection
580    /// goes; returning early would end it gracefully and send the client
581    /// into a re-listen loop.
582    fn listen(&self, context: SubscriptionContext) -> impl Future<Output = Result<(), McpError>> + Send + '_ {
583        async move {
584            let seq = self.state.next_listener.fetch_add(1, Ordering::Relaxed);
585            {
586                let mut listeners = self.state.listeners.lock().unwrap();
587                if listeners.len() >= 128 { return Err(McpError::internal_error("too many notification subscriptions", None)); }
588                listeners.push(Listener { seq, sink: context.sink().clone() });
589            }
590            let _guard = ListenerGuard { state: self.state.clone(), seq };
591            let uris = context.sink().accepted().resource_subscriptions.clone().unwrap_or_default();
592            let mut last = std::collections::HashMap::new();
593            let mut interval = tokio::time::interval(std::time::Duration::from_millis(500));
594            loop {
595                tokio::select! {
596                    _ = context.cancelled() => break,
597                    _ = interval.tick(), if !uris.is_empty() => {
598                        for uri in &uris {
599                            let observed = tokio::select! {
600                                _ = context.cancelled() => return Ok(()),
601                                result = tokio::time::timeout(std::time::Duration::from_secs(5), self.observed_resource(uri)) => result,
602                            };
603                            let value = match observed {
604                                Ok(Ok(value)) => value,
605                                Ok(Err(error)) => serde_json::json!({"error":error}),
606                                Err(_) => continue, // a busy app is not a resource change
607                            };
608                            let digest = crate::cad::canon::sha256_hex(value.to_string().as_bytes());
609                            if last.insert(uri.clone(), digest.clone()).is_some_and(|old| old != digest) {
610                                if !matches!(tokio::time::timeout(std::time::Duration::from_secs(5), context.sink().notify_resource_updated(uri)).await, Ok(Ok(()))) { return Ok(()); }
611                            }
612                        }
613                    }
614                }
615            }
616            Ok(())
617        }
618    }
619
620    fn list_tools(
621        &self,
622        _request: Option<PaginatedRequestParams>,
623        _context: RequestContext<RoleServer>,
624    ) -> impl Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
625        async move {
626            let set = self.state.tools.read().await;
627            // The front door (`cad::tools::FRONT_DOOR`): everything else is
628            // a script function of `run`.
629            let listed = set.specs.iter().filter(|t| t.group == "script");
630            Ok(cacheable(ListToolsResult::with_all_items(listed.map(to_rmcp_tool).collect())))
631        }
632    }
633
634    fn call_tool(
635        &self,
636        request: CallToolRequestParams,
637        context: RequestContext<RoleServer>,
638    ) -> impl Future<Output = Result<CallToolResponse, McpError>> + Send + '_ {
639        async move {
640            let spec = {
641                let set = self.state.tools.read().await;
642                let front = set.specs.iter().find(|t| t.name == *request.name && t.group == "script");
643                front.or_else(|| set.get(&request.name)).cloned()
644            };
645            let Some(spec) = spec else {
646                return Err(McpError::invalid_params(format!("unknown tool `{}`", request.name), None));
647            };
648            if spec.group != "script" {
649                let script = if crate::cad::script_callable(spec.group, &spec.name) {
650                    format!("call it from a `run` program as `await sdk.{}(args)`", crate::script_sdk::path_of(spec.group, &spec.name))
651                } else {
652                    "it is not exposed over MCP".into()
653                };
654                return Ok(CallToolResult::error(vec![ContentBlock::text(format!("`{}` is not a front-door tool: {script}", request.name))]).into());
655            }
656            let args = Value::Object(request.arguments.unwrap_or_default());
657            if let Err(e) = crate::script_sdk::validate_front_door(&request.name, &args) {
658                return Ok(CallToolResult::error(vec![ContentBlock::text(e)]).into());
659            }
660            // Starting a program with `wait_ms: 0` is a task for a client
661            // that speaks Tasks; fetching a result again or halting never is.
662            let starts = request.name.as_ref() == "run" && crate::script_sdk::run_form(&args) == crate::script_sdk::RunForm::Start;
663            let task_mode = starts && args.get("wait_ms").and_then(Value::as_u64) == Some(0) && context.client_capabilities().is_some_and(|c| c.supports_tasks());
664            let task_form = task_mode && crate::cad::inputs::supports_task_form(&context);
665            let progress = crate::progress::waits(&request.name, &args);
666            let operation = crate::cad::inputs::with_task_form_support(task_form, (spec.handler)(args));
667            match crate::progress::waiting(&context, progress, &self.state.slot, operation).await {
668                Ok(out) => {
669                    if task_mode && out.json["value"]["running"] == true {
670                        let id = out.json["value"]["status"]["executionId"].as_str().ok_or_else(|| McpError::internal_error("missing execution id", None))?;
671                        return Ok(rmcp::model::CreateTaskResult::new(self.execution_task(id)?.task).into());
672                    }
673                    let text = serde_json::to_string(&out.json)
674                        .map_err(|e| McpError::internal_error(format!("serialize result: {e}"), None))?;
675                    let mut content = vec![ContentBlock::text(text)];
676                    content.extend(image_blocks(out.images));
677                    let failed = out.json.get("ok") == Some(&Value::Bool(false))
678                        || (request.name.as_ref() == "run" && out.json["value"]["state"] == "failed");
679                    let mut result = if failed { CallToolResult::error(content) } else { CallToolResult::success(content) };
680                    result.structured_content = Some(out.json);
681                    Ok(result.into())
682                }
683                // A tool that ran and refused is a tool *result* with isError, not a
684                // protocol error: the model reads the text and adapts.
685                Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(e)]).into()),
686            }
687        }
688    }
689
690    fn get_task(&self, request: rmcp::model::GetTaskParams, _context: RequestContext<RoleServer>) -> impl Future<Output = Result<rmcp::model::GetTaskResult, McpError>> + Send + '_ {
691        async move { self.execution_task(&request.task_id).map(rmcp::model::GetTaskResult::new) }
692    }
693
694    fn cancel_task(&self, request: rmcp::model::CancelTaskParams, _context: RequestContext<RoleServer>) -> impl Future<Output = Result<(), McpError>> + Send + '_ {
695        async move {
696            self.state.cad.code.cancel(&crate::cad::tools::caller_of_transport(), &serde_json::json!({"executionId":request.task_id}))
697                .map(|_| ()).map_err(|e| McpError::invalid_params(e.message, None))
698        }
699    }
700
701    fn update_task(&self, request: rmcp::model::UpdateTaskParams, _context: RequestContext<RoleServer>) -> impl Future<Output = Result<(), McpError>> + Send + '_ {
702        async move { self.state.cad.code.update_input(&crate::cad::tools::caller_of_transport(), &request.task_id, &request.input_responses)
703            .map_err(|e| McpError::invalid_params(e.message, None)) }
704    }
705
706    fn list_resource_templates(&self, _request: Option<PaginatedRequestParams>, _context: RequestContext<RoleServer>) -> impl Future<Output = Result<rmcp::model::ListResourceTemplatesResult, McpError>> + Send + '_ {
707        async move {
708            let templates = [
709                ("brep://events/archive/{archiveId}/{sequence}/{limit}", "diagnostic-archive-page", "Synced metadata across restarts; bounded pages, explicit gap records and cursor gaps; limit 1..128"),
710                ("brep://events/replay/{epoch}/{sequence}/{limit}", "event-replay", "Bounded event pages; sequence is the next wanted event, limit 1..128; explicit gaps require state reconciliation"),
711                ("brep://api/function/{path}", "function-contract", "One script function's JSON Schemas, grants and effect annotations; path is <namespace>.<action>, e.g. brep://api/function/scene.mass_properties"),
712                ("brep://api/group/{group}", "function-group", "Every function contract of one namespace, e.g. brep://api/group/scene"),
713                ("brep://execution/{executionId}", "execution-status", "Process-scoped execution status; subscribe for invalidation and reread to reconcile"),
714                ("brep://artifact/{artifactId}", "artifact-manifest", "Metadata for an expiring artifact owned by this local transport scope"),
715                ("brep://artifact/{artifactId}/chunks/{offset}", "artifact-chunk", "At most 64 KiB of artifact bytes as base64 JSON; offset is a decimal byte offset"),
716            ].into_iter().map(|(uri, name, description)| rmcp::model::ResourceTemplate::new(uri, name).with_description(description).with_mime_type("application/json")).collect();
717            Ok(rmcp::model::ListResourceTemplatesResult::with_all_items(templates).with_ttl_ms(LIST_TTL_MS).with_cache_scope(CacheScope::Private))
718        }
719    }
720
721    fn list_resources(
722        &self,
723        _request: Option<PaginatedRequestParams>,
724        _context: RequestContext<RoleServer>,
725    ) -> impl Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ {
726        async move {
727            let mut resources: Vec<Resource> = self.state.resources.read().await.specs.iter().map(to_rmcp_resource).collect();
728            let groups: std::collections::BTreeSet<String> = {
729                let set = self.state.tools.read().await;
730                self.state.cad.surface(&set, None).entries.iter().map(|e| e.namespace.clone()).collect()
731            };
732            for group in groups { resources.push(Resource::new(format!("brep://api/group/{group}"), format!("functions-{group}"))); }
733            let session = self.state.slot.read().await.clone();
734            if let Some(session) = session {
735                let catalogue = session.host.call_ok("plugin_feature_catalogue", serde_json::json!({})).await
736                    .map_err(|error| McpError::internal_error(error, None))?.result.unwrap_or(Value::Null);
737                for entry in catalogue["features"].as_array().into_iter().flatten() {
738                    let id = crate::schema::identity(entry);
739                    if crate::schema::entry(&id.feature_type).is_some() { continue; }
740                    let mut resource = Resource::new(format!("brep://schema/features/{}", id.feature_type), format!("feature-schema-{}", id.feature_type));
741                    resource.description = Some(format!("inputParams JSON Schema and defaults of {}", id.long_name));
742                    resource.mime_type = Some("application/json".into());
743                    resources.push(resource);
744                }
745            }
746            Ok(ListResourcesResult::with_all_items(resources)
747                .with_ttl_ms(LIST_TTL_MS)
748                .with_cache_scope(CacheScope::Private))
749        }
750    }
751
752    fn read_resource(
753        &self,
754        request: ReadResourceRequestParams,
755        _context: RequestContext<RoleServer>,
756    ) -> impl Future<Output = Result<ReadResourceResponse, McpError>> + Send + '_ {
757        async move {
758            if let Some(path) = request.uri.strip_prefix("brep://artifact/") {
759                let caller = crate::cad::tools::caller_of_transport();
760                let owner = crate::cad::artifacts::Owner { scope: caller.scope.clone(), execution: None };
761                let value = if let Some((id, offset)) = path.split_once("/chunks/") {
762                    let offset = offset.parse::<usize>().map_err(|_| McpError::invalid_params("artifact offset must be a decimal byte offset", None))?;
763                    self.state.cad.artifacts.read(&owner, id, offset, None)
764                } else { self.state.cad.artifacts.reference_of(&owner, path) }.map_err(|e| McpError::resource_not_found(e.message, None))?;
765                let mut content = ResourceContents::text(value.to_string(), request.uri.clone());
766                if let ResourceContents::TextResourceContents { mime_type, .. } = &mut content { *mime_type = Some("application/json".into()); }
767                return Ok(ReadResourceResult::new(vec![content]).with_ttl_ms(0).with_cache_scope(CacheScope::Private).into());
768            }
769            if matches!(request.uri.as_str(), "brep://events" | "brep://documents") || request.uri == "brep://events/archive" || request.uri.starts_with("brep://events/archive/") || request.uri.starts_with("brep://events/replay/") || request.uri.starts_with("brep://execution/") {
770                let value = self.observed_resource(&request.uri).await.map_err(|e| McpError::resource_not_found(e, None))?;
771                return Ok(ReadResourceResult::new(vec![ResourceContents::text(value.to_string(), request.uri.clone())]).with_ttl_ms(0).with_cache_scope(CacheScope::Private).into());
772            }
773            let (text, mime) = self.state.reference_text(&request.uri).await?
774                .ok_or_else(|| McpError::resource_not_found(format!("no resource `{}`", request.uri), None))?;
775            let mut contents = ResourceContents::text(text, request.uri.clone());
776            if let ResourceContents::TextResourceContents { mime_type, .. } = &mut contents {
777                *mime_type = Some(mime.to_string());
778            }
779            Ok(ReadResourceResult::new(vec![contents]).with_ttl_ms(LIST_TTL_MS).with_cache_scope(CacheScope::Private).into())
780        }
781    }
782}
783
784impl ServerState {
785    /// The skills this server serves.
786    pub fn skills(&self) -> &crate::skills::Catalogue {
787        self.skills.get().map_or(crate::skills::Catalogue::embedded(), |c| &**c)
788    }
789    /// A reference resource's text and media type: the function and group
790    /// contracts, the feature and sketch schemas, and every listed resource.
791    /// `None` when no resource has that URI.
792    pub async fn reference_text(&self, uri: &str) -> Result<Option<(String, &'static str)>, McpError> {
793        let dynamic = if let Some(path) = uri.strip_prefix("brep://api/function/") {
794            let value = self.cad.describe(&[path.to_string()]).await.map_err(|e| McpError::resource_not_found(e.message, None))?;
795            Some((value.to_string(), "application/json"))
796        } else if let Some(group) = uri.strip_prefix("brep://api/group/") {
797            let set = self.tools.read().await;
798            let surface = self.cad.surface(&set, None);
799            let functions: Vec<Value> = surface.entries.iter().filter(|e| e.namespace == group).map(|e| e.to_json()).collect();
800            if functions.is_empty() { return Err(McpError::resource_not_found("unknown function group", None)); }
801            Some((serde_json::json!({"version":surface.version(),"namespace":group,"functions":functions}).to_string(), "application/json"))
802        } else if uri == "brep://api/commands" {
803            let set = self.tools.read().await;
804            let surface = self.cad.surface(&set, None);
805            let functions: Vec<Value> = surface.entries.iter().map(|e| e.to_json()).collect();
806            Some((serde_json::json!({"version":surface.version(),"functions":functions}).to_string(), "application/json"))
807        } else { None };
808        if dynamic.is_some() { return Ok(dynamic); }
809        let session = self.slot.read().await.clone();
810        if let Some(session) = session {
811            let value = if uri == "brep://schema/features" {
812                let catalogue = session.host.call_ok("plugin_feature_catalogue", serde_json::json!({})).await
813                    .map_err(|error| McpError::internal_error(error, None))?.result.unwrap_or(Value::Null);
814                Some(crate::schema::all_from_catalogue(&catalogue))
815            } else if let Some(ty) = uri.strip_prefix("brep://schema/features/").filter(|ty| ty.contains('/')) {
816                let entry = crate::tools::session_feature_entry(&session, ty).await
817                    .map_err(|error| McpError::resource_not_found(error, None))?;
818                Some(serde_json::json!({"schema":crate::schema::to_json_schema(&entry),"defaults":crate::schema::defaults_from_entry(&entry)}))
819            } else { None };
820            if let Some(value) = value {
821                let text = serde_json::to_string_pretty(&value).map_err(|error| McpError::internal_error(error.to_string(), None))?;
822                return Ok(Some((text, "application/json")));
823            }
824        }
825        let spec = self.resources.read().await.get(uri).cloned();
826        let Some(spec) = spec else { return Ok(None) };
827        let text = (spec.read)().map_err(|e| McpError::internal_error(e, None))?;
828        Ok(Some((text, spec.mime)))
829    }
830}
831
832/// Serve over stdin/stdout until the client disconnects.
833pub async fn serve_stdio(server: BrepServer) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
834    let state = server.state.clone();
835    let running = server.serve(rmcp::transport::io::stdio()).await?;
836    *state.peer.lock().unwrap() = Some(running.peer().clone());
837    let result = running.waiting().await;
838    state.cad.code.shutdown().await;
839    *state.peer.lock().unwrap() = None;
840    // A client that disconnects mid-session must not leave an app thread behind.
841    if let Some(session) = state.slot.write().await.take() {
842        match Arc::try_unwrap(session) {
843            Ok(s) => { tokio::task::spawn_blocking(move || s.host.stop()).await.ok(); }
844            Err(shared) => shared.host.request_stop(),
845        }
846    }
847    result?;
848    Ok(())
849}
850