BREP_mcp 0.1.0

The BREP MCP automation server: hosts the BREP CAD app headlessly under egui_kittest and serves the BREP_mcp_core Model Context Protocol surface over stdio or streamable HTTP, so an agent can drive the CAD app with no display attached. The same server the app embeds behind `brep-app --mcp`.
Documentation
//! `brep-mcp` — the BREP MCP automation server binary.
//!
//!   brep-mcp serve [--http PORT]      speak MCP over stdio (what `.mcp.json` runs), or streamable HTTP
//!   brep-mcp schema [--type T|--all] [--write DIR]
//!                                     the feature catalogue as JSON Schema / the generated docs
//!   brep-mcp test <scripts…>          run test-mcp scripts headlessly
//!   brep-mcp shot <doc> <png>         render one document to an image
use brep_mcp::server::BrepServer;
use clap::{Parser, Subcommand};
use serde_json::{json, Value};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "brep-mcp", version, about = "BREP MCP automation server")]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Serve MCP over stdio, or over streamable HTTP with `--http`.
    Serve {
        /// Where sessions keep their store, shots and logs (default: the OS temp dir).
        #[arg(long)]
        session_root: Option<PathBuf>,
        /// Serve the streamable-HTTP transport on this loopback port instead of
        /// stdio — the same transport `brep-app --mcp` exposes, with no window.
        /// 0 picks a free port; the URL is printed on stderr.
        #[arg(long, value_name = "PORT")]
        http: Option<u16>,
    },
    /// Print the kernel feature catalogue rendered as JSON Schema.
    Schema {
        /// One feature (type or shortName) instead of the whole catalogue.
        #[arg(long = "type")]
        feature_type: Option<String>,
        /// Also print the test-mcp script format schema.
        #[arg(long)]
        all: bool,
        /// Write the generated docs (commands / features, md + json) into this directory
        /// instead of printing (`docs/developer/mcp/generated`).
        #[arg(long)]
        write: Option<PathBuf>,
    },
    /// Run test-mcp scripts through a headless session each.
    Test {
        scripts: Vec<PathBuf>,
        #[arg(long, default_value = "headless")]
        backend: String,
        #[arg(long)]
        out: Option<PathBuf>,
        #[arg(long)]
        update_baselines: bool,
        #[arg(long)]
        session_root: Option<PathBuf>,
    },
    /// Render a document to a PNG through the headless host.
    Shot {
        doc: PathBuf,
        png: PathBuf,
        #[arg(long, default_value = "ISO")]
        view: String,
        #[arg(long, default_value = "1280x800")]
        size: String,
        #[arg(long, default_value_t = 1.0)]
        ppp: f32,
        #[arg(long)]
        session_root: Option<PathBuf>,
    },
}

fn session_root(explicit: Option<PathBuf>) -> PathBuf {
    explicit
        .or_else(|| std::env::var_os("BREP_MCP_SESSION_ROOT").map(PathBuf::from))
        .unwrap_or_else(|| std::env::temp_dir().join("brep-mcp"))
}

/// Call a tool by name on the server's current tool set.
async fn call(server: &BrepServer, name: &str, args: Value) -> Result<brep_mcp::tools::ToolOutput, String> {
    let spec = server.state.tools.read().await.get(name).cloned().ok_or_else(|| format!("no tool `{name}`"))?;
    (spec.handler)(args).await
}

/// Start a headless session for a script and regenerate the tool set.
async fn start_session(server: &BrepServer, args: Value) -> Result<(), String> {
    call(server, "session_start", args).await?;
    server.rebuild_tools().await;
    Ok(())
}

async fn stop_session(server: &BrepServer) {
    let _ = call(server, "session_stop", json!({})).await;
    server.rebuild_tools().await;
}

fn main() {
    let cli = Cli::parse();
    let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
    let code = match cli.command {
        Command::Serve { session_root: root, http } => {
            let server = BrepServer::new(session_root(root), brep_mcp::headless_backend());
            let result = match http {
                // Streamable HTTP: bind first, so a busy port is a launch error
                // rather than a server nobody can reach, then print the URL the
                // way `brep-app --mcp` does.
                Some(port) => rt.block_on(async {
                    let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
                        .await
                        .map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}"))?;
                    let bound = listener.local_addr().map_err(|e| e.to_string())?.port();
                    eprintln!("brep-mcp listening on {}", brep_mcp::http::url(bound));
                    brep_mcp::http::serve_http(server, listener).await.map_err(|e| e.to_string())
                }),
                None => rt.block_on(brep_mcp::server::serve_stdio(server)).map_err(|e| e.to_string()),
            };
            match result {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("brep-mcp: {e}");
                    1
                }
            }
        }
        Command::Schema { feature_type, all, write } => {
            if let Some(dir) = write {
                // The generated docs are rendered from a LIVE headless session:
                // the app's command registry, its state registry and every
                // panel's hit-key docs, exactly as a client would see them.
                let server = BrepServer::new(session_root(None), brep_mcp::headless_backend());
                let result: Result<Vec<String>, String> = rt.block_on(async {
                    let (tools, reg) = brep_mcp::generate::live_registries(&server).await?;
                    stop_session(&server).await;
                    brep_mcp::generate::write_with(&dir, &tools, &reg).map_err(|e| e.to_string())
                });
                match result {
                    Ok(files) => {
                        for f in files {
                            println!("wrote {}", dir.join(f).display());
                        }
                        std::process::exit(0);
                    }
                    Err(e) => {
                        eprintln!("brep-mcp: {e}");
                        std::process::exit(brep_mcp::script::exit::HOST_ERROR);
                    }
                }
            }
            let out = match feature_type {
                Some(ty) => match brep_mcp::schema::entry(&ty) {
                    Some(entry) => json!({
                        "schema": brep_mcp::schema::to_json_schema(&entry),
                        "defaults": brep_mcp::schema::defaults(&ty),
                    }),
                    None => {
                        eprintln!("brep-mcp: unknown feature type `{ty}`");
                        std::process::exit(2);
                    }
                },
                None if all => json!({
                    "features": brep_mcp::schema::all(),
                    "scriptFormat": brep_mcp::script::Script::json_schema(),
                }),
                None => brep_mcp::schema::all(),
            };
            println!("{}", serde_json::to_string_pretty(&out).unwrap());
            0
        }
        Command::Test { scripts, backend, out, update_baselines, session_root: root } => {
            if backend != "headless" {
                eprintln!("brep-mcp: backend `{backend}` is not available yet; using headless");
            }
            let server = BrepServer::new(session_root(root), brep_mcp::headless_backend());
            let out_root = out.unwrap_or_else(|| PathBuf::from("target/test-mcp"));
            let baselines = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/baselines");
            let mut worst = brep_mcp::script::exit::PASS;
            for path in &scripts {
                let script = match std::fs::read_to_string(path).map_err(|e| e.to_string()).and_then(|t| brep_mcp::script::Script::parse(&t)) {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("brep-mcp: {}: {e}", path.display());
                        worst = worst.max(brep_mcp::script::exit::TOOL_ERROR);
                        continue;
                    }
                };
                // A script that only uses catalogue tools needs no app.
                let needs_app = script.steps.iter().any(|s| !matches!(s.tool.as_str(), "feature_catalogue" | "feature_schema"));
                if needs_app {
                    let args = json!({
                        "backend": "headless",
                        "width": script.size[0], "height": script.size[1], "ppp": script.ppp,
                        "seed": script.seed, "document": script.document, "record": false,
                    });
                    if let Err(e) = rt.block_on(start_session(&server, args)) {
                        eprintln!("FAIL {} (host: {e})", script.name);
                        worst = worst.max(brep_mcp::script::exit::HOST_ERROR);
                        continue;
                    }
                }
                let opts = brep_mcp::runner::RunOptions {
                    out_dir: out_root.join(&script.name),
                    baselines_dir: baselines.clone(),
                    update_baselines,
                    stop_on_fail: true,
                };
                let result = rt.block_on(async {
                    let tools = server.state.tools.read().await;
                    brep_mcp::runner::run(&script, &tools, &opts).await
                });
                if needs_app {
                    rt.block_on(stop_session(&server));
                }
                let status = if result.passed { "PASS" } else { "FAIL" };
                eprintln!("{status} {} ({} steps, exit {})", script.name, result.steps.len(), result.exit_code);
                for step in result.steps.iter().filter(|s| !s.failures.is_empty()) {
                    for f in &step.failures {
                        eprintln!("  step {} `{}`: {f}", step.index, step.tool);
                    }
                }
                worst = worst.max(result.exit_code);
            }
            worst
        }
        Command::Shot { doc, png, view, size, ppp, session_root: root } => {
            let (w, h) = size
                .split_once('x')
                .and_then(|(a, b)| Some((a.parse::<f32>().ok()?, b.parse::<f32>().ok()?)))
                .unwrap_or((1280.0, 800.0));
            let server = BrepServer::new(session_root(root), brep_mcp::headless_backend());
            let result: Result<(), String> = rt.block_on(async {
                start_session(&server, json!({ "backend": "headless", "width": w, "height": h, "ppp": ppp, "document": doc.display().to_string(), "record": false })).await?;
                call(&server, "standard_view", json!({ "name": view })).await?;
                call(&server, "zoom_to_fit", json!({})).await?;
                call(&server, "wait_idle", json!({})).await?;
                let out = call(&server, "screenshot", json!({ "region": "viewport", "cursor": false, "max_width": 100000, "save_as": png.display().to_string() })).await?;
                eprintln!("wrote {} ({}x{})", png.display(), out.json["width"], out.json["height"]);
                stop_session(&server).await;
                Ok(())
            });
            match result {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("brep-mcp: {e}");
                    brep_mcp::script::exit::HOST_ERROR
                }
            }
        }
    };
    std::process::exit(code);
}