warder 0.1.0

A policy gate for MCP tool calls - blocks destructive AI agent actions before they run
Documentation
//! Newline-delimited JSON-RPC framing for the MCP stdio transport.
//!
//! On stdio there is no header layer: all request metadata is carried inline in the
//! JSON-RPC body. That is precisely why a network gateway cannot govern this transport,
//! and why the shim has to parse every message rather than routing on headers the way an
//! HTTP intermediary can under the 2026-07-28 spec.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A single JSON-RPC message flowing in either direction between client and server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jsonrpc: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub params: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<Value>,
}

impl Message {
    pub fn parse(line: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(line)
    }

    pub fn is_tool_call(&self) -> bool {
        self.method.as_deref() == Some("tools/call")
    }

    pub fn is_tools_list_result(&self) -> bool {
        self.result
            .as_ref()
            .map(|r| r.get("tools").map(|t| t.is_array()).unwrap_or(false))
            .unwrap_or(false)
    }

    /// Extract the tool name and arguments from a `tools/call` request.
    pub fn tool_call(&self) -> Option<ToolCall> {
        if !self.is_tool_call() {
            return None;
        }
        let p = self.params.as_ref()?;
        Some(ToolCall {
            name: p.get("name")?.as_str()?.to_string(),
            arguments: p.get("arguments").cloned().unwrap_or(Value::Null),
        })
    }

    /// Build a JSON-RPC error response denying a call, echoing the original id so the
    /// client correlates it correctly. -32020 is the spec's HeaderMismatch code; we use
    /// the application-defined -32001 range for policy denials so a denial is never
    /// mistaken for a protocol fault.
    pub fn denial(id: Option<Value>, reason: &str, audit_id: &str) -> Self {
        Message {
            jsonrpc: Some("2.0".into()),
            id,
            method: None,
            params: None,
            result: None,
            error: Some(serde_json::json!({
                "code": -32001,
                "message": format!("Blocked by warder policy: {reason}"),
                "data": { "audit_id": audit_id, "source": "warder" }
            })),
        }
    }

    pub fn to_line(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{}".into())
    }
}

#[derive(Debug, Clone)]
pub struct ToolCall {
    pub name: String,
    pub arguments: Value,
}

impl ToolCall {
    /// Best-effort extraction of a SQL statement from common argument shapes.
    /// Postgres, MySQL, Snowflake and BigQuery MCP servers all use one of these keys.
    pub fn sql(&self) -> Option<&str> {
        for key in ["sql", "query", "statement", "q"] {
            if let Some(s) = self.arguments.get(key).and_then(|v| v.as_str()) {
                return Some(s);
            }
        }
        None
    }

    /// Argument *key* names only — never values. The audit record stores shapes and
    /// key names by default; raw values require explicit per-tenant opt-in.
    pub fn argument_keys(&self) -> Vec<String> {
        match &self.arguments {
            Value::Object(m) => {
                let mut k: Vec<String> = m.keys().cloned().collect();
                k.sort();
                k
            }
            _ => vec![],
        }
    }
}

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

    #[test]
    fn parses_tool_call() {
        let line = r#"{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"execute_sql","arguments":{"sql":"SELECT 1"}}}"#;
        let m = Message::parse(line).unwrap();
        assert!(m.is_tool_call());
        let tc = m.tool_call().unwrap();
        assert_eq!(tc.name, "execute_sql");
        assert_eq!(tc.sql(), Some("SELECT 1"));
    }

    #[test]
    fn ignores_non_tool_calls() {
        let line = r#"{"jsonrpc":"2.0","id":1,"method":"resources/list","params":{}}"#;
        let m = Message::parse(line).unwrap();
        assert!(!m.is_tool_call());
        assert!(m.tool_call().is_none());
    }

    #[test]
    fn denial_preserves_id_and_carries_audit_id() {
        let d = Message::denial(Some(serde_json::json!(7)), "destructive", "aud-1");
        assert_eq!(d.id, Some(serde_json::json!(7)));
        let err = d.error.unwrap();
        assert_eq!(err["data"]["audit_id"], "aud-1");
    }

    #[test]
    fn argument_keys_are_sorted_and_values_excluded() {
        let line =
            r#"{"method":"tools/call","params":{"name":"t","arguments":{"z":"secret","a":1}}}"#;
        let tc = Message::parse(line).unwrap().tool_call().unwrap();
        assert_eq!(tc.argument_keys(), vec!["a".to_string(), "z".to_string()]);
    }

    #[test]
    fn detects_tools_list_result() {
        let line =
            r#"{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"a","description":"d"}]}}"#;
        assert!(Message::parse(line).unwrap().is_tools_list_result());
    }
}