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
//! Webhook delivery of the diagnostic events ([`super::diag`]): the server
//! POSTs them to a URL whether or not any MCP client is connected.
//!
//! A webhook is registered by the operator (`brep-mcp serve --event-webhook
//! <URL> --event-webhook-secret-file <PATH>`, kept for the process) or by a
//! client (`events/webhooks/register`, which answers with a fresh secret
//! once; it lasts until removed or the process ends — the connection that
//! made it may close). Each webhook has its own bounded queue and delivery
//! thread, so a slow receiver never delays CAD work or another webhook.
//!
//! A delivery is one JSON batch of at most [`BATCH`] events with the
//! continuation cursor, signed `BREP-Webhook-Signature: v1=<hex>` =
//! HMAC-SHA256(secret, `<BREP-Webhook-Timestamp>.<body>`). A failed POST is
//! retried with exponential backoff (1 s doubling to 60 s, [`ATTEMPTS`]
//! tries; a 4xx other than 408/429 is not retried). Events are never
//! silently lost: a batch given up on, or events a full queue refused, are
//! announced by the next delivery's `gap`, naming the first missed sequence,
//! so the receiver reads `brep://events/replay/…` or `brep://events/archive`
//! and reconciles current state. Bodies carry the same payload-free
//! metadata as the event ring: no source, arguments, geometry or paths.
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// The capability extension the server advertises for these methods.
pub const EXTENSION: &str = "io.brep/event-webhooks";
pub const MAX_HOOKS: usize = 16;
const QUEUE: usize = 1024;
pub const BATCH: usize = 128;
const FLUSH: Duration = Duration::from_millis(250);
pub const ATTEMPTS: u32 = 8;
const TIMEOUT: Duration = Duration::from_secs(10);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Origin { Operator, Client }

/// The one network step, so the retry and gap logic is testable offline.
pub trait Post: Send + Sync + 'static {
    /// The HTTP status, or a transport error.
    fn post(&self, url: &str, headers: &[(&str, String)], body: &[u8]) -> Result<u16, String>;
}

struct Ureq(ureq::Agent);
impl Post for Ureq {
    fn post(&self, url: &str, headers: &[(&str, String)], body: &[u8]) -> Result<u16, String> {
        let mut request = self.0.post(url);
        for (name, value) in headers { request = request.set(name, value); }
        match request.send_bytes(body) {
            Ok(response) => Ok(response.status()),
            Err(ureq::Error::Status(code, _)) => Ok(code),
            Err(e) => Err(e.kind().to_string()),
        }
    }
}

#[derive(Default)]
struct Status {
    delivered_events: u64,
    delivered_batches: u64,
    failed_batches: u64,
    dropped_events: u64,
    last_error: Option<String>,
    last_delivery_at: Option<u64>,
}

struct Hook {
    id: String,
    url: String,
    origin: Origin,
    sender: mpsc::SyncSender<Value>,
    /// Events the full queue refused since the worker last looked, and the
    /// first of them (u64::MAX when none).
    refused: Arc<AtomicU64>,
    first_refused: Arc<AtomicU64>,
    status: Arc<Mutex<Status>>,
    stop: Arc<AtomicBool>,
}

pub struct Webhooks {
    hooks: Mutex<Vec<Hook>>,
    transport: Arc<dyn Post>,
    /// The first retry's delay; it doubles up to `max_backoff`.
    backoff: Duration,
    max_backoff: Duration,
}

impl Default for Webhooks {
    fn default() -> Self {
        let agent = ureq::AgentBuilder::new().redirects(0).timeout(TIMEOUT).user_agent(concat!("brep-mcp/", env!("CARGO_PKG_VERSION"))).build();
        Self::with_transport(Arc::new(Ureq(agent)), Duration::from_secs(1), Duration::from_secs(60))
    }
}

impl Drop for Webhooks {
    fn drop(&mut self) {
        for hook in self.hooks.get_mut().unwrap().iter() { hook.stop.store(true, Ordering::SeqCst); }
    }
}

/// `https://…` anywhere, or `http://` to this machine only (events would
/// otherwise cross a network in clear). No credentials in the URL: it is
/// listed back to clients.
pub fn check_url(url: &str) -> Result<(), String> {
    if url.len() > 2048 || url.chars().any(|c| c.is_control() || c.is_whitespace()) {
        return Err("webhook URL must be at most 2048 characters without spaces or control characters".into());
    }
    let (secure, rest) = if let Some(rest) = url.strip_prefix("https://") { (true, rest) }
        else if let Some(rest) = url.strip_prefix("http://") { (false, rest) }
        else { return Err("webhook URL must start with https:// (or http:// to this machine)".into()) };
    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    if authority.is_empty() { return Err("webhook URL has no host".into()); }
    if authority.contains('@') { return Err("webhook URL must not carry credentials; the signature authenticates deliveries".into()); }
    let host = if authority.starts_with('[') {
        authority.split_once(']').map(|(h, _)| &h[1..]).ok_or("webhook URL has an unterminated IPv6 host")?
    } else { authority.rsplit_once(':').map_or(authority, |(h, _)| h) };
    if !secure && !matches!(host.to_ascii_lowercase().as_str(), "127.0.0.1" | "localhost" | "::1") {
        return Err("a plain http:// webhook must be on this machine (127.0.0.1, ::1 or localhost); use https:// otherwise".into());
    }
    Ok(())
}

pub fn sign(secret: &[u8], timestamp: u64, body: &[u8]) -> String {
    let mut key = [0u8; 64];
    if secret.len() > 64 { key[..32].copy_from_slice(&Sha256::digest(secret)); } else { key[..secret.len()].copy_from_slice(secret); }
    let (mut ipad, mut opad) = ([0x36u8; 64], [0x5cu8; 64]);
    for i in 0..64 { ipad[i] ^= key[i]; opad[i] ^= key[i]; }
    let inner = Sha256::new().chain_update(ipad).chain_update(format!("{timestamp}.")).chain_update(body).finalize();
    let mac = Sha256::new().chain_update(opad).chain_update(inner).finalize();
    format!("v1={}", mac.iter().map(|b| format!("{b:02x}")).collect::<String>())
}

fn now_secs() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) }

fn sequence(event: &Value) -> Option<u64> { event["eventSequence"].as_str().and_then(|s| s.parse().ok()) }

impl Webhooks {
    pub fn with_transport(transport: Arc<dyn Post>, backoff: Duration, max_backoff: Duration) -> Self {
        Self { hooks: Mutex::new(Vec::new()), transport, backoff, max_backoff }
    }

    /// Queue `event` for every webhook. Never blocks: a full queue counts the
    /// event as refused and the next delivery reports the gap.
    pub fn publish(&self, event: &Value) {
        for hook in self.hooks.lock().unwrap().iter() {
            if hook.sender.try_send(event.clone()).is_err() {
                hook.refused.fetch_add(1, Ordering::SeqCst);
                let _ = hook.first_refused.fetch_min(sequence(event).unwrap_or(u64::MAX), Ordering::SeqCst);
                hook.status.lock().unwrap().dropped_events += 1;
            }
        }
    }

    pub fn register(&self, url: &str, secret: Vec<u8>, origin: Origin) -> Result<String, String> {
        check_url(url)?;
        if secret.len() < 16 { return Err("a webhook secret must be at least 16 bytes".into()); }
        let mut hooks = self.hooks.lock().unwrap();
        if hooks.len() >= MAX_HOOKS { return Err(format!("at most {MAX_HOOKS} webhooks; remove one first")); }
        let id = super::wire::mint("hook");
        let (sender, receiver) = mpsc::sync_channel(QUEUE);
        let hook = Hook { id: id.clone(), url: url.into(), origin, sender, refused: Arc::new(AtomicU64::new(0)),
            first_refused: Arc::new(AtomicU64::new(u64::MAX)), status: Default::default(), stop: Arc::new(AtomicBool::new(false)) };
        let worker = Worker { id: id.clone(), url: url.into(), secret, receiver, refused: hook.refused.clone(), first_refused: hook.first_refused.clone(),
            status: hook.status.clone(), stop: hook.stop.clone(), transport: self.transport.clone(), backoff: self.backoff, max_backoff: self.max_backoff };
        std::thread::Builder::new().name("brep-event-webhook".into()).spawn(move || worker.run()).map_err(|e| e.to_string())?;
        hooks.push(hook);
        Ok(id)
    }

    pub fn remove(&self, id: &str) -> Result<(), String> {
        let mut hooks = self.hooks.lock().unwrap();
        let index = hooks.iter().position(|h| h.id == id).ok_or("unknown webhook id")?;
        if hooks[index].origin == Origin::Operator { return Err("this webhook was configured by the server operator; it is removed by restarting without --event-webhook".into()); }
        // Dropping the sender ends the worker once it is idle; the flag ends
        // a retry in progress.
        hooks.remove(index).stop.store(true, Ordering::SeqCst);
        Ok(())
    }

    pub fn list(&self) -> Value {
        let hooks = self.hooks.lock().unwrap();
        json!({"webhooks": hooks.iter().map(|h| {
            let s = h.status.lock().unwrap();
            json!({"webhookId":h.id,"url":h.url,"origin":match h.origin { Origin::Operator => "operator", Origin::Client => "client" },
                "deliveredEvents":s.delivered_events,"deliveredBatches":s.delivered_batches,"failedBatches":s.failed_batches,
                "droppedEvents":s.dropped_events,"lastError":s.last_error,"lastDeliveryAt":s.last_delivery_at})
        }).collect::<Vec<_>>(), "limit": MAX_HOOKS})
    }

    /// `events/webhooks/register|list|remove`.
    pub fn request(&self, method: &str, params: &Value) -> Result<Value, String> {
        let only = |allowed: &[&str]| -> Result<(), String> {
            match params.as_object() {
                Some(o) => o.keys().filter(|k| k.as_str() != "_meta").find(|k| !allowed.contains(&k.as_str()))
                    .map_or(Ok(()), |k| Err(format!("unknown parameter `{k}`"))),
                None => Err("parameters must be an object".into()),
            }
        };
        match method {
            "events/webhooks/register" => {
                only(&["url"])?;
                let url = params["url"].as_str().ok_or("url is required")?;
                let secret: String = (0..2).flat_map(|_| super::wire::random_128()).map(|b| format!("{b:02x}")).collect();
                let id = self.register(url, secret.clone().into_bytes(), Origin::Client)?;
                Ok(json!({"webhookId":id,"secret":secret,
                    "signature":"BREP-Webhook-Signature: v1=hex(HMAC-SHA256(secret, BREP-Webhook-Timestamp + '.' + body)); the secret is shown only now",
                    "lifetime":"until events/webhooks/remove or the server process ends; it does not end with this connection"}))
            }
            "events/webhooks/list" => { only(&[])?; Ok(self.list()) }
            "events/webhooks/remove" => {
                only(&["webhookId"])?;
                self.remove(params["webhookId"].as_str().ok_or("webhookId is required")?)?;
                Ok(json!({"removed":true}))
            }
            _ => Err("unknown events/webhooks method".into()),
        }
    }
}

struct Worker {
    id: String,
    url: String,
    secret: Vec<u8>,
    receiver: mpsc::Receiver<Value>,
    refused: Arc<AtomicU64>,
    first_refused: Arc<AtomicU64>,
    status: Arc<Mutex<Status>>,
    stop: Arc<AtomicBool>,
    transport: Arc<dyn Post>,
    backoff: Duration,
    max_backoff: Duration,
}

impl Worker {
    fn run(self) {
        // The first sequence a receiver has not been sent, with why.
        let mut gap: Option<(&'static str, u64)> = None;
        loop {
            if self.stop.load(Ordering::SeqCst) { return; }
            let mut batch = Vec::new();
            match self.receiver.recv_timeout(FLUSH) {
                Ok(event) => batch.push(event),
                Err(mpsc::RecvTimeoutError::Timeout) => {}
                Err(mpsc::RecvTimeoutError::Disconnected) => return,
            }
            while batch.len() < BATCH {
                match self.receiver.try_recv() { Ok(event) => batch.push(event), Err(_) => break }
            }
            if self.refused.swap(0, Ordering::SeqCst) > 0 {
                let first = self.first_refused.swap(u64::MAX, Ordering::SeqCst);
                gap = Some(gap.map_or(("queue_overflow", first), |(reason, at)| (reason, at.min(first))));
            }
            if batch.is_empty() && gap.is_none() { continue; }
            let first = batch.first().and_then(sequence);
            match self.deliver(&batch, gap) {
                Ok(()) => {
                    gap = None;
                    let mut s = self.status.lock().unwrap();
                    s.delivered_events += batch.len() as u64; s.delivered_batches += 1;
                    s.last_delivery_at = Some(now_secs()); s.last_error = None;
                }
                Err(error) => {
                    if self.stop.load(Ordering::SeqCst) { return; }
                    let missed = first.unwrap_or(u64::MAX);
                    gap = Some(gap.map_or(("delivery_failed", missed), |(reason, at)| (reason, at.min(missed))));
                    let mut s = self.status.lock().unwrap();
                    s.failed_batches += 1; s.last_error = Some(error);
                }
            }
        }
    }

    fn body(&self, batch: &[Value], gap: Option<(&'static str, u64)>) -> (String, Vec<u8>) {
        let epoch = super::wire::epoch();
        let delivery = super::wire::mint("delivery");
        let next = batch.last().and_then(sequence).map_or_else(|| super::diag::head(), |n| n + 1);
        let gap = gap.map(|(reason, from)| {
            let from = if from == u64::MAX { next } else { from };
            json!({"reason":reason,"missedFromSequence":from.to_string(),"reconciliationRequired":true,
                "replayUri":format!("brep://events/replay/{epoch}/{from}/{}", super::diag::PAGE_LIMIT),
                "recovery":"Events from missedFromSequence were not delivered. Read replayUri (or brep://events/archive) for what is still retained, then read current document and execution state; never replay CAD work from events."})
        });
        let body = json!({"webhookId":self.id,"deliveryId":delivery,"epoch":epoch,"events":batch,
            "cursor":format!("{epoch}:{next}"),"nextUri":format!("brep://events/replay/{epoch}/{next}/{}", super::diag::PAGE_LIMIT),"gap":gap});
        (delivery, serde_json::to_vec(&body).expect("events serialize"))
    }

    fn deliver(&self, batch: &[Value], gap: Option<(&'static str, u64)>) -> Result<(), String> {
        let (delivery, body) = self.body(batch, gap);
        let mut wait = self.backoff;
        let mut last = String::new();
        for attempt in 1..=ATTEMPTS {
            let timestamp = now_secs();
            let headers = [("Content-Type", "application/json".to_string()), ("BREP-Webhook-Id", self.id.clone()),
                ("BREP-Delivery-Id", delivery.clone()), ("BREP-Delivery-Attempt", attempt.to_string()),
                ("BREP-Webhook-Timestamp", timestamp.to_string()), ("BREP-Webhook-Signature", sign(&self.secret, timestamp, &body))];
            match self.transport.post(&self.url, &headers, &body) {
                Ok(code) if (200..300).contains(&code) => return Ok(()),
                Ok(code) => {
                    last = format!("HTTP {code}");
                    if (400..500).contains(&code) && code != 408 && code != 429 { return Err(format!("{last} (not retried)")); }
                }
                Err(error) => last = error,
            }
            if attempt == ATTEMPTS { break; }
            // Sleep in slices so a removal ends a long backoff promptly.
            let until = std::time::Instant::now() + wait;
            while std::time::Instant::now() < until {
                if self.stop.load(Ordering::SeqCst) { return Err("removed".into()); }
                std::thread::sleep(Duration::from_millis(10).min(until - std::time::Instant::now()));
            }
            wait = (wait * 2).min(self.max_backoff);
        }
        Err(format!("{last} after {ATTEMPTS} attempts"))
    }
}