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 MCP front door: `sdk` (what a program can call) and `run` (run a
//! program, fetch its result again, halt it). Everything else the app can do
//! is a script function, `sdk.<namespace>.<action>(args)`
//! ([`super::surface`]).
//!
//! The transport admits a request only with the loopback credential (D3,
//! `http::Credential`; stdio is its launching process's own), so every
//! admitted client is the trusted local caller ([`caller_of_transport`]).
use super::ops::Caller;
use super::wire::{self, ApiError};
use super::CadService;
use crate::script_sdk::{run_form, RunForm};
use crate::tools::{Annotations, ToolImage, ToolOutput, ToolSpec};
use serde_json::{json, Value};
use std::sync::Arc;

/// Who an admitted MCP request is: the local user, whose token the HTTP
/// transport checked (`http::Credential`) or whose process owns stdio.
pub fn caller_of_transport() -> Caller {
    Caller::local()
}

/// The MCP's front door: the only tools a client lists and calls.
pub use crate::script_sdk::FRONT_DOOR;

/// The operation service by its wire names (`cad.operations.submit`,
/// `cad.code.submit`, ...), for a host that drives the service itself: the
/// integration tests and an embedding host. A program is never given these:
/// it has the script functions ([`super::surface`]), and no way to start or
/// inspect an execution. `cad.discovery.*` answers the catalogue's own
/// commands (what `sdk.operations.submit` takes), by exact path.
pub async fn call_service(service: &CadService, caller: &Caller, method: &str, req: &Value) -> Result<Value, ApiError> {
    if req.to_string().len() > 1 << 20 {
        return Err(ApiError::new("resource_limit", "validation", "the request is larger than 1 MiB"));
    }
    match method {
        "cad.discovery.search" => {
            caller.require(&["catalogue.read"])?;
            let query = req.get("query").and_then(Value::as_str).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "query must be a string"))?;
            service.catalogue.search(query, req.get("limit").and_then(Value::as_u64), req.get("cursor").and_then(Value::as_str))
        }
        "cad.discovery.describe" => {
            caller.require(&["catalogue.read"])?;
            let paths: Vec<String> = req.get("paths").and_then(Value::as_array).into_iter().flatten().filter_map(|p| p.as_str().map(str::to_string)).collect();
            service.catalogue.describe(&paths)
        }
        "cad.code.submit" => service.code.submit(caller, req),
        "cad.code.status" => service.code.status(caller, req),
        "cad.code.result" => service.code.result(caller, req),
        "cad.code.cancel" => service.code.cancel(caller, req),
        other => service.call_service(caller, other, req.clone()).await,
    }
}

/// Retry keys `run` remembers; past this many the map starts again
/// (an issued key expires within minutes anyway).
const RETRY_KEYS: usize = 4096;

fn retry_key(keys: &mut std::collections::HashMap<String, String>, caller: &Caller, key: &str) -> Result<String, String> {
    if let Some(issued) = keys.get(key) { return Ok(issued.clone()); }
    if keys.len() >= RETRY_KEYS { return Err("retry key capacity reached; existing keys remain valid; reconcile work before restarting".into()); }
    let issued = super::keys::issue(&caller.scope, super::keys::Purpose::Execution).0;
    keys.insert(key.into(), issued.clone());
    Ok(issued)
}

/// Await the result when no budget is supplied; an explicit budget returns
/// status if the execution is still running at its deadline.
async fn settle_execution(service: &CadService, caller: &Caller, id: &str, wait_ms: Option<u64>) -> Value {
    let deadline = wait_ms.map(|ms| std::time::Instant::now() + std::time::Duration::from_millis(ms));
    loop {
        match service.code.result(caller, &json!({ "executionId": id })) {
            Ok(result) => return wire::ok(result),
            Err(e) if e.code == "not_ready" && deadline.is_none_or(|d| std::time::Instant::now() < d) => {
                tokio::time::sleep(std::time::Duration::from_millis(25)).await;
            }
            Err(e) if e.code == "not_ready" => {
                return wire::respond(service.code.status(caller, &json!({ "executionId": id })).map(|s| json!({ "running": true, "status": s })));
            }
            Err(e) => return wire::fail(&e),
        }
    }
}

/// Start the headless session if none is live, and wait for the app's tools
/// to register (the session's registry is read asynchronously).
pub(super) async fn ensure_session(service: &CadService, slot: &crate::tools::app::SessionSlot) -> Result<(), String> {
    let Some(state) = service.server.get().and_then(std::sync::Weak::upgrade) else { return Ok(()) };
    let _starting = state.session_start.lock().await;
    if slot.read().await.is_some() { return Ok(()); }
    let start = state.tools.read().await.get("session_start").cloned();
    if let Some(start) = start {
        (start.handler)(json!({ "backend": "headless", "seed": true, "record": false })).await?;
        crate::server::BrepServer { state: state.clone() }.rebuild_tools().await;
    }
    Ok(())
}

/// The images a reply may carry: enough for a program that returns a few
/// views, bounded so a program cannot make a reply of them.
const MAX_IMAGES: usize = 4;
const MAX_IMAGE_BYTES: usize = 8 << 20;

/// The pictures a finished program returned: every image artifact its
/// output refers to (`sdk.capture.screenshot` answers its picture as an
/// artifact of the execution), as bytes for the reply's image content. An
/// artifact that has expired, or that a restart took, is skipped: the
/// result still names it.
pub fn execution_images(service: &CadService, caller: &Caller, reply: &Value) -> Vec<ToolImage> {
    let mut images = Vec::new();
    let mut total = 0;
    for id in crate::script_sdk::returned_images(reply, MAX_IMAGES) {
        let Ok((bytes, media)) = service.artifacts.lease(&caller.owner(), &id) else { continue };
        service.artifacts.release(&id);
        let mime = match media.as_str() {
            "image/png" => "image/png",
            "image/jpeg" => "image/jpeg",
            "image/gif" => "image/gif",
            _ => continue,
        };
        if total + bytes.len() > MAX_IMAGE_BYTES { continue; }
        total += bytes.len();
        images.push(ToolImage { png: bytes, mime });
    }
    images
}

/// A settled execution's reply with the pictures its program returned.
fn with_images(service: &CadService, caller: &Caller, reply: Value) -> ToolOutput {
    let images = execution_images(service, caller, &reply);
    ToolOutput { json: reply, images }
}

/// The front door (group `script`): `sdk` and `run`.
pub fn front_door_tools(service: Arc<CadService>, slot: crate::tools::app::SessionSlot) -> Vec<ToolSpec> {
    let describe = service.clone();
    let mut sdk = ToolSpec::new(
        "sdk",
        "script",
        crate::script_sdk::SDK_DOC,
        crate::script_sdk::sdk_input_schema(),
        Annotations { read_only: true, destructive: false, idempotent: true, waits: false },
        move |args| {
            let service = describe.clone();
            Box::pin(async move {
                // Answered from the tool set as it is: no session is started,
                // nothing is read from disk and nothing runs.
                let caller = caller_of_transport();
                let state = service.server_state();
                let empty = crate::tools::ToolSet::default();
                let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
                let surface = service.surface(guard.as_deref().unwrap_or(&empty), state.as_deref()).granted(|g| caller.grants.has(g));
                surface.answer(&args).map(ToolOutput::json)
            })
        },
    );
    sdk.output_schema = crate::script_sdk::sdk_output_schema();
    let mut run = ToolSpec::new(
        "run",
        "script",
        crate::script_sdk::RUN_DOC,
        crate::script_sdk::run_input_schema(),
        Annotations { read_only: false, destructive: true, idempotent: false, waits: false },
        move |args| {
            let service = service.clone();
            let slot = slot.clone();
            Box::pin(async move {
                crate::script_sdk::validate_front_door("run", &args)?;
                let caller = caller_of_transport();
                let wait_ms = args.get("wait_ms").and_then(Value::as_u64).map(|ms| ms.min(crate::script_sdk::MAX_WAIT_MS));
                let execution = args.get("executionId").and_then(Value::as_str).unwrap_or_default();
                match run_form(&args) {
                    // Halt: the worker is killed wherever it is; CAD
                    // operations it had already started run on.
                    RunForm::Halt => return Ok(ToolOutput::json(wire::respond(service.code.cancel(&caller, &json!({ "executionId": execution }))))),
                    // The result again, waiting up to wait_ms (default 0).
                    RunForm::Result => {
                        let reply = settle_execution(&service, &caller, execution, Some(wait_ms.unwrap_or(0))).await;
                        return Ok(with_images(&service, &caller, reply));
                    }
                    RunForm::Start => {}
                }
                // A client's retry key stands for one issued key, so a
                // resubmission binds to the execution it already started.
                let key = match args.get("key").and_then(Value::as_str) {
                    Some(_) if service.code.persistent() => super::keys::issue(&caller.scope, super::keys::Purpose::Execution).0,
                    Some(k) => {
                        let mut keys = service.retry_keys.lock().unwrap();
                        retry_key(&mut keys, &caller, k)?
                    }
                    None => super::keys::issue(&caller.scope, super::keys::Purpose::Execution).0,
                };
                let req = json!({
                    "manifest": service.catalogue.identity(),
                    "source": args.get("code").and_then(Value::as_str).unwrap_or_default(),
                    "initialDocuments": [],
                    "requestedCapabilities": [],
                    "idempotencyKey": key,
                });
                let retry = args.get("key").and_then(Value::as_str);
                let replay = match service.code.replay(&caller, &req, true, retry) {
                    Ok(status) => status,
                    Err(e) => return Ok(ToolOutput::json(wire::fail(&e))),
                };
                let submitted = if let Some(status) = replay { Ok(status) } else {
                    ensure_session(&service, &slot).await?;
                    service.code.submit_with_retry(&caller, &req, true, retry)
                };
                let status = match submitted {
                    Ok(s) => s,
                    Err(e) => return Ok(ToolOutput::json(wire::fail(&e))),
                };
                let id = status["executionId"].as_str().unwrap_or_default().to_string();
                let reply = settle_execution(&service, &caller, &id, wait_ms).await;
                Ok(with_images(&service, &caller, reply))
            })
        },
    );
    run.output_schema = super::output_schema::run();
    vec![sdk, run]
}