warder 0.1.0

A policy gate for MCP tool calls - blocks destructive AI agent actions before they run
Documentation
//! `warder` — the Warder stdio shim.
//!
//! The AI client launches this binary *instead of* the real MCP server. It spawns the
//! real server as a child process and relays newline-delimited JSON-RPC in both
//! directions, evaluating policy in-process on every `tools/call` before the message
//! reaches the server.
//!
//! Client config change is one line:
//!
//! ```jsonc
//! // .cursor/mcp.json — before
//! { "mcpServers": { "postgres": { "command": "mcp-server-postgres", "args": ["--dsn", "..."] } } }
//! // after
//! { "mcpServers": { "postgres": { "command": "warder", "args": ["--config", ".warder/postgres.json"] } } }
//! ```
//!
//! Nothing on the allow path touches the network. Policy evaluates against a locally
//! cached signed bundle; audit records go to a bounded in-memory ring buffer and are
//! shipped in batches by the control-plane uploader.

use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::Instant;

use warder::{
    audit::{AuditRecord, AuditSink, Timers},
    config::Config,
    init::{self, InitArgs},
    jsonrpc::Message,
    policy::PolicyEngine,
    preflight::{classify_sql, classify_tool},
    toolpin::ToolPinStore,
};

const USAGE: &str = "\
warder \u{2014} a gate your AI agent's tool calls have to get past

USAGE
  warder init <server> [--dir <path>] [--patch <client-config>] -- <command> [args...]
  warder --config <path>     run as the shim (this is what your AI client invokes)
  warder --version

EXAMPLES
  # wrap a local Postgres MCP server and patch Cursor's config in place
  warder init postgres --patch .cursor/mcp.json -- mcp-server-postgres --dsn $DSN

  # generate config only, and print the snippet to paste yourself
  warder init github -- mcp-server-github
";

fn main() -> anyhow::Result<()> {
    let argv: Vec<String> = std::env::args().skip(1).collect();

    match argv.first().map(|s| s.as_str()) {
        None => {
            eprintln!("{USAGE}");
            std::process::exit(2);
        }
        Some("--version" | "-V") => {
            println!("warder {}", env!("CARGO_PKG_VERSION"));
            return Ok(());
        }
        Some("--help" | "-h" | "help") => {
            println!("{USAGE}");
            return Ok(());
        }
        Some("init") => return run_init(&argv[1..]),
        _ => {}
    }

    let mut config_path = std::env::var("WARDER_CONFIG").unwrap_or_default();
    let mut it = argv.iter();
    while let Some(a) = it.next() {
        if a == "--config" {
            config_path = it.next().cloned().unwrap_or_default();
        }
    }
    if config_path.is_empty() {
        eprintln!("{USAGE}");
        std::process::exit(2);
    }

    let cfg: Config = Config::from_json(&std::fs::read_to_string(&config_path)?)?;
    let policy_src = std::fs::read_to_string(&cfg.policy_path)?;
    let engine = PolicyEngine::from_source(&policy_src, cfg.fail_closed)?;
    let pins = Arc::new(Mutex::new(
        std::fs::read_to_string(&cfg.pin_path)
            .ok()
            .and_then(|s| ToolPinStore::load(&s).ok())
            .unwrap_or_default(),
    ));
    let sink = Arc::new(Mutex::new(AuditSink::new(cfg.audit_buffer)));

    // Launch the real MCP server as a child process. This is the whole point: we are the
    // process the client launches, which is the only vantage point from which stdio
    // traffic is observable at all.
    let mut child = Command::new(&cfg.command)
        .args(&cfg.args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .map_err(|e| anyhow::anyhow!("failed to launch upstream '{}': {e}", cfg.command))?;

    let mut child_stdin = child.stdin.take().expect("child stdin");
    let child_stdout = child.stdout.take().expect("child stdout");

    // Server -> client. Also where tools/list responses are pinned for poisoning checks.
    let pins_up = Arc::clone(&pins);
    let server_name = cfg.server.clone();
    let pin_path = cfg.pin_path.clone();
    let upstream = std::thread::spawn(move || {
        let reader = BufReader::new(child_stdout);
        let stdout = std::io::stdout();
        for line in reader.lines() {
            let Ok(line) = line else { break };
            if let Ok(msg) = Message::parse(&line) {
                if msg.is_tools_list_result() {
                    if let Some(result) = &msg.result {
                        let mut p = pins_up.lock().expect("pin store");
                        for (tool, verdict) in p.check_tools_list(&server_name, result) {
                            eprintln!(
                                "warder: TOOL DESCRIPTION CHANGED for {server_name}::{tool} \
                                 — possible tool poisoning ({verdict:?})"
                            );
                        }
                        if let Some(dir) = std::path::Path::new(&pin_path).parent() {
                            let _ = std::fs::create_dir_all(dir);
                        }
                        let _ = std::fs::write(&pin_path, p.save());
                    }
                }
            }
            let mut h = stdout.lock();
            let _ = writeln!(h, "{line}");
            let _ = h.flush();
        }
    });

    // Client -> server. The enforcement path.
    let stdin = std::io::stdin();
    for line in BufReader::new(stdin.lock()).lines() {
        let Ok(line) = line else { break };
        let t0 = Instant::now();

        let msg = match Message::parse(&line) {
            Ok(m) => m,
            // Not JSON-RPC we understand: relay unchanged rather than breaking the session.
            Err(_) => {
                writeln!(child_stdin, "{line}")?;
                child_stdin.flush()?;
                continue;
            }
        };

        let Some(call) = msg.tool_call() else {
            writeln!(child_stdin, "{line}")?;
            child_stdin.flush()?;
            continue;
        };

        let keys = call.argument_keys();
        let report = match call.sql() {
            Some(sql) => classify_sql(sql),
            None => classify_tool(&call.name, &keys),
        };

        let t_policy = Instant::now();
        let decision = engine.evaluate(&cfg.agent_id, &cfg.server, &call.name, &report);
        let policy_eval_us = t_policy.elapsed().as_micros() as u64;

        let record = AuditRecord::new(
            &cfg.agent_id,
            &cfg.server,
            &call.name,
            &call.arguments,
            keys,
            &report,
            &decision,
            Timers {
                proxy_overhead_us: t0.elapsed().as_micros() as u64,
                policy_eval_us,
                upstream_us: 0,
            },
            cfg.capture_raw_arguments,
        );
        let audit_id = record.audit_id.clone();
        sink.lock().expect("audit sink").push(record);

        if decision.is_blocking() {
            // Answer the client directly; the call never reaches the server.
            let denial = Message::denial(msg.id.clone(), &decision.reason, &audit_id);
            let stdout = std::io::stdout();
            let mut h = stdout.lock();
            writeln!(h, "{}", denial.to_line())?;
            h.flush()?;
            eprintln!(
                "warder: {:?} {}::{} — {} [{}]",
                decision.effect, cfg.server, call.name, decision.reason, audit_id
            );
            continue;
        }

        writeln!(child_stdin, "{line}")?;
        child_stdin.flush()?;
    }

    drop(child_stdin);
    let _ = upstream.join();
    let _ = child.wait();

    let mut s = sink.lock().expect("audit sink");
    let pending = s.drain();
    if !pending.is_empty() || s.dropped() > 0 {
        eprintln!(
            "warder: {} audit records pending upload, {} dropped",
            pending.len(),
            s.dropped()
        );
    }
    Ok(())
}

/// `warder init <server> [--dir d] [--patch p] -- <command> [args...]`
fn run_init(argv: &[String]) -> anyhow::Result<()> {
    let mut server = String::new();
    let mut dir = std::path::PathBuf::from(".warder");
    let mut patch: Option<std::path::PathBuf> = None;
    let mut upstream: Vec<String> = Vec::new();

    let mut i = 0;
    let mut after_sep = false;
    while i < argv.len() {
        let a = &argv[i];
        if after_sep {
            upstream.push(a.clone());
        } else if a == "--" {
            after_sep = true;
        } else if a == "--dir" {
            i += 1;
            dir = std::path::PathBuf::from(argv.get(i).cloned().unwrap_or_default());
        } else if a == "--patch" {
            i += 1;
            patch = Some(std::path::PathBuf::from(
                argv.get(i).cloned().unwrap_or_default(),
            ));
        } else if server.is_empty() && !a.starts_with('-') {
            server = a.clone();
        } else {
            eprintln!("warder init: unexpected argument '{a}'\n\n{USAGE}");
            std::process::exit(2);
        }
        i += 1;
    }

    if server.is_empty() || upstream.is_empty() {
        eprintln!("warder init: need a server name and, after --, the command to wrap\n\n{USAGE}");
        std::process::exit(2);
    }

    println!();
    init::run(InitArgs {
        server,
        command: upstream[0].clone(),
        args: upstream[1..].to_vec(),
        dir,
        patch,
    })?;
    println!();
    Ok(())
}