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
//! The CAD operation service (owner brief 2026-10-28).
//!
//! One semantic CAD API, one operation lifecycle and one code-mode executor,
//! served to MCP clients as the `sdk` and `run` tools and to programs as the
//! `sdk` global. Everything here runs over the host protocol a live session
//! already speaks, so the headless host and the attached desktop window get
//! identical semantics.
//!
//! - [`wire`]      — handles, timestamps, `ApiError`, `Effects`, `Response`.
//! - [`canon`]     — RFC 8785 canonical JSON and SHA-256.
//! - [`keys`]      — authenticated, expiring admission keys.
//! - [`catalogue`] — the operation commands' descriptors, their manifest and its hash.
//! - [`commands`]  — what each semantic command does to the app.
//! - [`ops`]       — admission, idempotency, the request-independent operation lifetime,
//!   cancellation, retention and overload.
//! - [`artifacts`] — opaque, scoped, expiring byte objects (a STEP export, an upload).
//! - [`code`]      — code mode: a program in a host-supervised worker process.
//! - [`surface`]   — the script namespace's native side: the service functions and
//!   the worker's two hooks (`script_names`, `script_call`).
//! - [`declarations`] — one action's TypeScript signature, rendered on demand.
//! - [`diag`]      — bounded, payload-free diagnostic events.
//! - [`tools`]     — the two front-door MCP tools over all of the above.
pub mod artifacts;
pub mod canon;
pub mod catalogue;
pub mod code;
pub mod commands;
pub use crate::declarations;
pub mod diag;
pub mod event_journal;
pub mod event_archive;
pub mod webhooks;
pub mod journal;
pub(crate) mod inputs;
pub mod keys;
pub mod ops;
pub mod output_schema;
pub mod surface;
pub mod tools;
pub mod wire;

use std::sync::Arc;

/// Everything the `cad_*` tools share for the life of the server process:
/// the service is process-scoped, not connection- or session-scoped, so an
/// accepted operation outlives the request that submitted it.
mod files;

pub struct CadService {
    pub files: files::Files,
    pub event_archive: std::sync::OnceLock<event_archive::Archive>,
    /// Webhook deliveries of every event, to operator- and client-registered URLs.
    pub webhooks: webhooks::Webhooks,
    pub ops: ops::Operations,
    pub artifacts: artifacts::Artifacts,
    pub code: code::Executions,
    pub catalogue: catalogue::Catalogue,
    /// This server's own script functions (`sdk.document.list`,
    /// `sdk.operations.submit`, ...), beside the registry's tools.
    pub services: Vec<crate::script_sdk::ServiceEntry>,
    /// The server whose tool registry scripts call as
    /// `sdk.<namespace>.<action>` (set once by `BrepServer::new`).
    pub server: std::sync::OnceLock<std::sync::Weak<crate::server::ServerState>>,
    /// `run`'s retry keys: a client's key → the issued key it stands
    /// for. Here, not in the tool, because the tool set is rebuilt whenever
    /// a session starts — the first submission's own session among them.
    pub retry_keys: std::sync::Mutex<std::collections::HashMap<String, String>>,
}

pub use crate::script_sdk::{script_callable, ScriptTool};

impl CadService {
    pub fn new(slot: crate::tools::app::SessionSlot) -> Arc<Self> {
        let catalogue = catalogue::Catalogue::new();
        Arc::new_cyclic(|weak| CadService {
            files: files::Files::new(),
            event_archive: Default::default(),
            webhooks: Default::default(),
            ops: ops::Operations::new(slot, weak.clone()),
            artifacts: artifacts::Artifacts::new(),
            code: code::Executions::new(weak.clone()),
            services: surface::service_entries(&catalogue),
            catalogue,
            server: std::sync::OnceLock::new(),
            retry_keys: Default::default(),
        })
    }

    pub fn event(&self, kind: &'static str, id: Option<&str>, state: Option<&str>, code: Option<&str>, sequence: Option<u64>) {
        let value = diag::event(kind, id, state, code, sequence);
        self.webhooks.publish(&value);
        if let Some(archive) = self.event_archive.get() { archive.publish(value); }
    }

    pub fn archive_resource(&self, uri: &str) -> Result<serde_json::Value, String> {
        match self.event_archive.get() {
            Some(archive) => archive.resource(uri),
            None if uri == "brep://events/archive" => Ok(serde_json::json!({"enabled":false,"records":[],"persistence":{"status":"disabled"}})),
            None => Err("diagnostic archive is disabled".into()),
        }
    }

    pub(crate) fn server_state(&self) -> Option<Arc<crate::server::ServerState>> {
        self.server.get().and_then(std::sync::Weak::upgrade)
    }

    /// The registry tools a script may call, as of now (a live session adds
    /// the app's). Blocking: called from a code worker's host thread.
    pub fn script_tools(&self) -> Vec<ScriptTool> {
        let Some(state) = self.server_state() else { return vec![] };
        let set = state.tools.blocking_read();
        crate::script_sdk::script_tools(&set.specs)
    }

    /// One script-callable registry tool by name.
    pub async fn script_tool(&self, name: &str) -> Option<crate::tools::ToolSpec> {
        let state = self.server_state()?;
        // By name AND a script-callable group: the front door's `screenshot`
        // shares its name with the capture tool a script calls.
        let set = state.tools.read().await;
        set.specs.iter().find(|t| t.name == name && script_callable(t.group, &t.name)).cloned()
    }

    /// The contracts of 1..8 script functions by path (`scene.entities`,
    /// with or without `sdk.`), as `brep://api/function/<path>` serves them.
    /// An old `brep.<group>.<tool>` spelling still names its registry tool.
    pub async fn describe(&self, paths: &[String]) -> Result<serde_json::Value, wire::ApiError> {
        use serde_json::json;
        if paths.is_empty() || paths.len() > 8 { return Err(wire::ApiError::new("invalid_arguments", "validation", "describe takes 1..8 paths")); }
        let state = self.server_state();
        let empty = crate::tools::ToolSet::default();
        let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
        let surface = self.surface(guard.as_deref().unwrap_or(&empty), None);
        let mut methods = Vec::new();
        for path in paths {
            let registry = |old: &str| {
                let (group, tool) = old.split_once('.')?;
                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}"))))
            };
            let entry = surface.get(path).or_else(|| path.strip_prefix("brep.").and_then(registry))
                .ok_or_else(|| wire::ApiError::new("method_unknown", "lookup", surface.unknown(path)))?;
            methods.push(entry.to_json());
        }
        let result = json!({"manifest":self.catalogue.identity(),"version":surface.version(),"methods":methods});
        if result.to_string().len() > 64 << 10 { return Err(wire::ApiError::new("resource_limit", "validation", "describe fewer paths")); }
        Ok(result)
    }

    /// Run a program for the app itself (its JavaScript editor): the local
    /// user, trusted as the MCP's `run` is — every app tool, no
    /// execution control. Must be called inside the server's tokio runtime
    /// (`Handle::enter`); returns at once with the execution id.
    pub fn run_local(&self, source: &str) -> Result<String, String> {
        let caller = tools::caller_of_transport();
        let (key, _) = keys::issue(&caller.scope, keys::Purpose::Execution);
        let req = serde_json::json!({
            "manifest": self.catalogue.identity(),
            "source": source,
            "initialDocuments": [],
            "requestedCapabilities": [],
            "idempotencyKey": key,
        });
        let status = self.code.submit_as(&caller, &req, true).map_err(|e| e.message)?;
        Ok(status["executionId"].as_str().unwrap_or_default().to_string())
    }

    /// A [`Self::run_local`] execution's result once it has ended (`None`
    /// while it runs), with its console lines as `logText`.
    pub fn result_local(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
        let caller = tools::caller_of_transport();
        match self.code.result(&caller, &serde_json::json!({ "executionId": id })) {
            Ok(mut result) => {
                let log = result["logArtifact"]["artifactId"].as_str().map(str::to_string);
                if let Some(log) = log {
                    if let Ok((bytes, _)) = self.artifacts.lease(&caller.owner(), &log) {
                        self.artifacts.release(&log);
                        result["logText"] = String::from_utf8_lossy(&bytes).into_owned().into();
                    }
                }
                Ok(Some(result))
            }
            Err(e) if e.code == "not_ready" => Ok(None),
            Err(e) => Err(e.message),
        }
    }

    /// Halt a [`Self::run_local`] execution: its worker is killed.
    pub fn halt_local(&self, id: &str) -> Result<(), String> {
        let caller = tools::caller_of_transport();
        self.code.cancel(&caller, &serde_json::json!({ "executionId": id })).map(|_| ()).map_err(|e| e.message)
    }
}

/// The app's own handle on code mode, for its JavaScript editor: the
/// server's [`CadService`] and the runtime it runs on, so a frame can submit,
/// poll and halt without awaiting anything.
#[derive(Clone)]
pub struct LocalScripts {
    cad: std::sync::Weak<CadService>,
    runtime: tokio::runtime::Handle,
}

impl std::fmt::Debug for LocalScripts {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("LocalScripts")
    }
}

impl LocalScripts {
    pub fn new(cad: &Arc<CadService>, runtime: tokio::runtime::Handle) -> Self {
        LocalScripts { cad: Arc::downgrade(cad), runtime }
    }

    fn cad(&self) -> Result<Arc<CadService>, String> {
        self.cad.upgrade().ok_or_else(|| "the script runner has stopped".to_string())
    }

    /// Whether the app's tools are registered (a program's `sdk` names are
    /// read from them at submit). Never blocks.
    pub fn ready(&self) -> Result<bool, String> {
        let state = self.cad()?.server_state().ok_or("the server is stopping")?;
        Ok(state.tools.try_read().is_ok_and(|set| set.specs.iter().any(|t| t.name == "docs_list")))
    }

    pub fn run(&self, source: &str) -> Result<String, String> {
        let _enter = self.runtime.enter();
        self.cad()?.run_local(source)
    }

    pub fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
        self.cad()?.result_local(id)
    }

    pub fn halt(&self, id: &str) -> Result<(), String> {
        let _enter = self.runtime.enter();
        self.cad()?.halt_local(id)
    }
}