warder 0.1.0

A policy gate for MCP tool calls - blocks destructive AI agent actions before they run
Documentation
//! `warder init` — one command from "not installed" to "governed".
//!
//! Adoption friction is the whole game for a tool like this. Asking someone to
//! hand-write two JSON files and a policy before they can see it work loses most of
//! them. This writes the config, drops in a starter policy, and — with `--patch` —
//! rewrites the client's own MCP config so the next thing they do is just use their
//! agent normally and watch a destructive call get blocked.

use serde_json::{json, Value};
use std::path::{Path, PathBuf};

pub const STARTER_POLICY: &str = include_str!("../policies/default.cedar");

pub struct InitArgs {
    /// Logical name for the upstream server, e.g. "postgres".
    pub server: String,
    /// The real MCP server command and its arguments.
    pub command: String,
    pub args: Vec<String>,
    /// Directory to write warder's own files into.
    pub dir: PathBuf,
    /// Optional client config to rewrite in place (e.g. .cursor/mcp.json).
    pub patch: Option<PathBuf>,
}

/// Where the well-known clients keep their MCP config, for `--patch` guidance.
pub const KNOWN_CLIENTS: &[(&str, &str)] = &[
    ("cursor", ".cursor/mcp.json"),
    ("vscode", ".vscode/mcp.json"),
    ("claude-code", ".mcp.json"),
    (
        "claude-desktop",
        "~/Library/Application Support/Claude/claude_desktop_config.json",
    ),
];

pub fn run(a: InitArgs) -> anyhow::Result<()> {
    std::fs::create_dir_all(&a.dir)?;

    // Starter policy — only written if absent, so re-running init never clobbers
    // a policy someone has edited.
    let policy_path = a.dir.join("policy.cedar");
    if !policy_path.exists() {
        std::fs::write(&policy_path, STARTER_POLICY)?;
        println!("  created  {}", policy_path.display());
    } else {
        println!("  kept     {} (already exists)", policy_path.display());
    }

    let cfg_path = a.dir.join(format!("{}.json", a.server));
    let cfg = json!({
        "server": a.server,
        "command": a.command,
        "args": a.args,
        "agent_id": "local-agent",
        "policy_path": policy_path.to_string_lossy(),
        "pin_path": a.dir.join("pins.json").to_string_lossy(),
        "fail_closed": false,
        "capture_raw_arguments": false,
        "audit_buffer": 4096
    });
    std::fs::write(
        &cfg_path,
        format!("{}\n", serde_json::to_string_pretty(&cfg)?),
    )?;
    println!("  created  {}", cfg_path.display());

    let exe = std::env::current_exe()
        .ok()
        .and_then(|p| p.file_name().map(|s| s.to_string_lossy().to_string()))
        .unwrap_or_else(|| "warder".into());

    let replacement = json!({
        "command": exe,
        "args": ["--config", cfg_path.to_string_lossy()]
    });

    match &a.patch {
        Some(client_path) => {
            patch_client(client_path, &a.server, &replacement)?;
            println!("  patched  {}", client_path.display());
            println!("\n  Restart your AI client. Tool calls now pass through warder.");
        }
        None => {
            println!("\n  Add this to your client's MCP config, replacing the existing");
            println!("  \"{}\" entry:\n", a.server);
            let snippet = json!({ "mcpServers": { &a.server: replacement } });
            for line in serde_json::to_string_pretty(&snippet)?.lines() {
                println!("    {line}");
            }
            println!("\n  Common locations:");
            for (name, path) in KNOWN_CLIENTS {
                println!("    {name:<16} {path}");
            }
            println!("\n  Or re-run with --patch <path> to have warder edit it for you.");
        }
    }
    Ok(())
}

/// Rewrite one server entry in a client's MCP config, preserving everything else and
/// leaving a backup. Anything unexpected is an error rather than a guess — silently
/// mangling somebody's editor config is a good way to never be trusted again.
fn patch_client(path: &Path, server: &str, replacement: &Value) -> anyhow::Result<()> {
    let raw = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", path.display()))?;
    let mut doc: Value = serde_json::from_str(&raw)
        .map_err(|e| anyhow::anyhow!("{} is not valid JSON: {e}", path.display()))?;

    let backup = path.with_extension("json.warder-backup");
    std::fs::write(&backup, &raw)?;
    println!("  backup   {}", backup.display());

    let servers = doc
        .get_mut("mcpServers")
        .and_then(|v| v.as_object_mut())
        .ok_or_else(|| anyhow::anyhow!("{} has no \"mcpServers\" object", path.display()))?;

    if !servers.contains_key(server) {
        anyhow::bail!(
            "{} has no \"{server}\" server. Present: {}",
            path.display(),
            servers.keys().cloned().collect::<Vec<_>>().join(", ")
        );
    }
    servers.insert(server.to_string(), replacement.clone());
    std::fs::write(path, format!("{}\n", serde_json::to_string_pretty(&doc)?))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tmp(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("warder-init-{name}"));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn writes_config_and_starter_policy() {
        let d = tmp("basic");
        run(InitArgs {
            server: "postgres".into(),
            command: "mcp-server-postgres".into(),
            args: vec!["--dsn".into(), "x".into()],
            dir: d.clone(),
            patch: None,
        })
        .unwrap();

        let cfg: Value =
            serde_json::from_str(&std::fs::read_to_string(d.join("postgres.json")).unwrap())
                .unwrap();
        assert_eq!(cfg["server"], "postgres");
        assert_eq!(cfg["command"], "mcp-server-postgres");
        assert_eq!(cfg["args"][0], "--dsn");
        assert_eq!(
            cfg["capture_raw_arguments"], false,
            "raw capture must default off"
        );
        assert!(d.join("policy.cedar").exists());
    }

    #[test]
    fn rerunning_init_does_not_clobber_an_edited_policy() {
        let d = tmp("keep");
        let args = || InitArgs {
            server: "pg".into(),
            command: "x".into(),
            args: vec![],
            dir: d.clone(),
            patch: None,
        };
        run(args()).unwrap();
        std::fs::write(d.join("policy.cedar"), "// my edits").unwrap();
        run(args()).unwrap();
        assert_eq!(
            std::fs::read_to_string(d.join("policy.cedar")).unwrap(),
            "// my edits"
        );
    }

    #[test]
    fn patch_rewrites_only_the_named_server_and_leaves_a_backup() {
        let d = tmp("patch");
        let client = d.join("mcp.json");
        std::fs::write(
            &client,
            r#"{"mcpServers":{"postgres":{"command":"mcp-server-postgres","args":["--dsn","secret"]},
                              "github":{"command":"mcp-server-github"}},
                "otherKey":{"keep":true}}"#,
        )
        .unwrap();

        run(InitArgs {
            server: "postgres".into(),
            command: "mcp-server-postgres".into(),
            args: vec![],
            dir: d.clone(),
            patch: Some(client.clone()),
        })
        .unwrap();

        let doc: Value = serde_json::from_str(&std::fs::read_to_string(&client).unwrap()).unwrap();
        assert!(doc["mcpServers"]["postgres"]["args"][0]
            .as_str()
            .unwrap()
            .contains("--config"));
        assert_eq!(
            doc["mcpServers"]["github"]["command"], "mcp-server-github",
            "other servers must be untouched"
        );
        assert_eq!(doc["otherKey"]["keep"], true, "unrelated keys must survive");
        assert!(
            client.with_extension("json.warder-backup").exists(),
            "a backup must be written"
        );
    }

    #[test]
    fn patch_refuses_when_the_server_is_absent() {
        let d = tmp("absent");
        let client = d.join("mcp.json");
        std::fs::write(&client, r#"{"mcpServers":{"github":{"command":"x"}}}"#).unwrap();
        let err = run(InitArgs {
            server: "postgres".into(),
            command: "x".into(),
            args: vec![],
            dir: d,
            patch: Some(client),
        })
        .unwrap_err();
        assert!(err.to_string().contains("no \"postgres\" server"));
    }

    #[test]
    fn patch_refuses_to_touch_invalid_json() {
        let d = tmp("invalid");
        let client = d.join("mcp.json");
        std::fs::write(&client, "{ not json").unwrap();
        assert!(run(InitArgs {
            server: "pg".into(),
            command: "x".into(),
            args: vec![],
            dir: d,
            patch: Some(client),
        })
        .is_err());
    }

    #[test]
    fn starter_policy_is_the_shipped_one_and_compiles() {
        use crate::policy::PolicyEngine;
        assert!(STARTER_POLICY.contains("deny-destructive"));
        assert!(PolicyEngine::from_source(STARTER_POLICY, true).is_ok());
    }
}