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
//! TypeScript for one `sdk.<namespace>.<action>`, rendered on demand from
//! the action's own JSON Schemas (the `sdk` tool's `{topic: "ns.action"}`):
//! the argument and result types are read off the schemas the host
//! validates with, so what an agent reads is what the call takes. Nothing is
//! written ahead of a question; there is no declaration file.
//!
//! Schema → TypeScript: string → `string`; number/integer → `number`;
//! boolean, null → themselves; `const` / `enum` → literal unions; an object's
//! declared properties → an object type with required/optional fidelity
//! (additional properties are not admitted); arrays → `T[]`; `oneOf`,
//! `anyOf` and type lists → unions; local JSON Pointer references → their
//! definitions. Unsupported or recursive shapes fall back to `unknown`
//! (never `any`), with bounded expansion.
use serde_json::Value;

fn literal(v: &Value) -> String {
    match v {
        Value::String(s) => serde_json::to_string(s).unwrap_or_default(),
        other => other.to_string(),
    }
}

/// One schema as a TypeScript type expression. Local references always resolve
/// against this root, including while rendering nested properties and unions.
pub fn ts_type(schema: &Value) -> String {
    let mut renderer = SchemaTypes { root: schema, references: Vec::new(), remaining: 4096, names: Default::default() };
    renderer.render(schema, 0)
}

/// Module-scoped aliases preserve recursive object/array references. Pure
/// reference cycles still use the anonymous renderer's bounded fallback.
fn named_type(schema: &Value, prefix: &str) -> (String, String) {
    fn collect(node: &Value, root: &Value, depth: usize, remaining: &mut usize, pointers: &mut std::collections::BTreeSet<String>) {
        if depth >= 64 || *remaining == 0 { return; }
        *remaining -= 1;
        if let Some(reference) = node.get("$ref").and_then(Value::as_str) {
            if let Some(pointer) = local_pointer(reference) {
                if let Some(target) = root.pointer(&pointer) {
                    if matches!(target.get("type").and_then(Value::as_str), Some("object" | "array"))
                        && ["$ref", "oneOf", "anyOf"].iter().all(|key| target.get(key).is_none()) {
                        pointers.insert(pointer);
                    }
                }
            }
        }
        match node {
            Value::Object(map) => for value in map.values() { collect(value, root, depth + 1, remaining, pointers); },
            Value::Array(values) => for value in values { collect(value, root, depth + 1, remaining, pointers); },
            _ => {}
        }
    }
    let mut pointers = std::collections::BTreeSet::new();
    collect(schema, schema, 0, &mut 4096, &mut pointers);
    let names: std::collections::BTreeMap<_,_> = pointers.into_iter().enumerate()
        .map(|(i,pointer)| (pointer,format!("{prefix}Ref{i}"))).collect();
    let mut renderer = SchemaTypes { root: schema, references: Vec::new(), remaining: 4096, names };
    let expression = renderer.render(schema, 0);
    let mut declarations = String::new();
    for (pointer,name) in renderer.names.clone() {
        // One shared work budget bounds the complete declaration, not merely
        // each definition. References retain their names if a body truncates.
        let body = renderer.render(schema.pointer(&pointer).unwrap(), 0);
        declarations.push_str(&format!("  type {name} = {body};\n"));
    }
    (expression, declarations)
}

struct SchemaTypes<'a> {
    root: &'a Value,
    references: Vec<String>,
    remaining: usize,
    names: std::collections::BTreeMap<String, String>,
}

impl SchemaTypes<'_> {
    fn render(&mut self, schema: &Value, depth: usize) -> String {
        // Recursive JSON Schemas cannot be expanded into finite anonymous TS
        // expressions. Bound both depth and total work, including acyclic
        // references that repeatedly expand the same large definition.
        if depth >= 64 || self.remaining == 0 {
            return "unknown".into();
        }
        self.remaining -= 1;
        if schema == &Value::Bool(false) {
            return "never".into();
        }
        if let Some(reference) = schema.get("$ref") {
            let Some(reference) = reference.as_str() else { return "unknown".into() };
            let Some(pointer) = local_pointer(reference) else { return "unknown".into() };
            let referenced = if let Some(name) = self.names.get(&pointer) {
                name.clone()
            } else {
                if self.references.contains(&pointer) { return "unknown".into(); }
                let root = self.root;
                let Some(target) = root.pointer(&pointer) else { return "unknown".into() };
                self.references.push(pointer);
                let rendered = self.render(target, depth + 1);
                self.references.pop();
                rendered
            };
            // Modern JSON Schema permits constraints beside $ref. Preserve
            // representable siblings instead of silently discarding them.
            if ["type", "const", "enum", "oneOf", "anyOf"].iter().any(|key| schema.get(key).is_some()) {
                let mut sibling = schema.clone();
                sibling.as_object_mut().unwrap().remove("$ref");
                return format!("({referenced}) & ({})", self.render(&sibling, depth + 1));
            }
            return referenced;
        }
        if let Some(c) = schema.get("const") {
            return literal(c);
        }
        if let Some(e) = schema.get("enum").and_then(Value::as_array) {
            return if e.is_empty() { "never".into() } else { e.iter().map(literal).collect::<Vec<_>>().join(" | ") };
        }
        if let Some(alts) = schema.get("oneOf").or_else(|| schema.get("anyOf")).and_then(Value::as_array) {
            if alts.is_empty() { return "never".into(); }
            let union = alts.iter().map(|alternative| self.render(alternative, depth + 1)).collect::<Vec<_>>().join(" | ");
            // Serde-flattened tagged enums place common object fields beside
            // the alternatives. Those fields constrain every union member.
            if schema.get("type").and_then(Value::as_str) == Some("object")
                && schema.get("properties").and_then(Value::as_object).is_some_and(|p| !p.is_empty()) {
                return format!("({}) & ({union})", self.object(schema, depth + 1));
            }
            return union;
        }
        match schema.get("type") {
            Some(Value::Array(types)) => {
                if types.is_empty() { return "never".into(); }
                types.iter().map(|kind| {
                    // Retain items/properties/required/additionalProperties:
                    // a nullable array of strings is not an array of unknowns.
                    let mut alternative = schema.clone();
                    alternative["type"] = kind.clone();
                    self.render(&alternative, depth + 1)
                }).collect::<Vec<_>>().join(" | ")
            }
            Some(Value::String(t)) => match t.as_str() {
                "string" => "string".into(),
                "number" | "integer" => "number".into(),
                "boolean" => "boolean".into(),
                "null" => "null".into(),
                "array" => {
                    let item = schema.get("items").map_or_else(|| "unknown".to_string(), |items| self.render(items, depth + 1));
                    if item.contains(' ') { format!("Array<{item}>") } else { format!("{item}[]") }
                }
                "object" => self.object(schema, depth + 1),
                _ => "unknown".into(),
            },
            _ => "unknown".into(),
        }
    }

    fn object(&mut self, schema: &Value, depth: usize) -> String {
        // No declared properties: a dictionary, unless the schema closes it.
        let closed = schema.get("additionalProperties") == Some(&Value::Bool(false));
        let Some(props) = schema.get("properties").and_then(Value::as_object).filter(|props| !props.is_empty()) else {
            return if closed { "Record<string, never>".into() }
                else if let Some(value) = schema.get("additionalProperties").filter(|v| v.is_object()) {
                    format!("Record<string, {}>", self.render(value, depth))
                } else { "Record<string, unknown>".into() };
        };
        let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
        let fields: Vec<String> = props.iter().map(|(key, value)| {
            format!("{}{}: {}", property_name(key), if required.contains(&key.as_str()) { "" } else { "?" }, self.render(value, depth))
        }).collect();
        let declared = format!("{{ {} }}", fields.join("; "));
        if schema.get("additionalProperties") == Some(&Value::Bool(true)) {
            return format!("{declared} & Record<string, unknown>");
        }
        // JSON Schema excludes explicit properties from additionalProperties.
        // TypeScript index signatures do not: include declared field types in
        // the index union so envelope fields do not make dictionaries unusable.
        if let Some(additional) = schema.get("additionalProperties").filter(|value| value.is_object()) {
            let mut types = vec![self.render(additional, depth)];
            for (name, value) in props {
                types.push(self.render(value, depth));
                if !required.contains(&name.as_str()) { types.push("undefined".into()); }
            }
            types.sort();
            types.dedup();
            return format!("{declared} & Record<string, {}>", types.join(" | "));
        }
        declared
    }
}

/// A URI-fragment JSON Pointer, decoded before serde_json applies ~0/~1.
/// External references and named anchors are deliberately not fetched/resolved.
fn local_pointer(reference: &str) -> Option<String> {
    let fragment = reference.strip_prefix('#')?;
    let mut bytes = Vec::with_capacity(fragment.len());
    let mut input = fragment.as_bytes().iter().copied();
    while let Some(byte) = input.next() {
        if byte == b'%' {
            let high = (input.next()? as char).to_digit(16)?;
            let low = (input.next()? as char).to_digit(16)?;
            bytes.push((high * 16 + low) as u8);
        } else {
            bytes.push(byte);
        }
    }
    let pointer = String::from_utf8(bytes).ok()?;
    if !pointer.is_empty() && !pointer.starts_with('/') { return None; }
    let mut characters = pointer.chars();
    while let Some(character) = characters.next() {
        if character == '~' && !matches!(characters.next(), Some('0' | '1')) { return None; }
    }
    Some(pointer)
}

fn property_name(key: &str) -> String {
    let mut chars = key.chars();
    if chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') {
        key.into()
    } else {
        serde_json::to_string(key).unwrap_or_default()
    }
}

/// One action's signature as the `sdk` tool serves it: the named types its
/// schemas refer to (recursive definitions only; everything else is inline),
/// its description, then `sdk.<namespace>.<action>(args): Promise<result>`.
/// `args` is optional when no argument is required.
pub fn signature(entry: &crate::script_sdk::Entry<'_>) -> String {
    let (input, input_aliases) = named_type(entry.input_schema(), "Args");
    let (output, output_aliases) = named_type(entry.output_schema(), "Result");
    let required = entry.input_schema().get("required").and_then(Value::as_array).is_some_and(|r| !r.is_empty());
    let doc = entry.doc().trim().replace("*/", "* /");
    format!(
        "{}{}/** {doc} */\nsdk.{}(args{}: {input}): Promise<{output}>",
        input_aliases.replace("  type ", "type "),
        output_aliases.replace("  type ", "type "),
        entry.path(),
        if required { "" } else { "?" },
    )
}