Skip to main content

mars_schema/
tool_rule_map.rs

1//! An ordered map from tool key to action: `[settings.tools]` and the rule entries of
2//! `[agents.<name>.tools]` in `mars.toml`.
3
4use std::fmt;
5
6use serde::de::{Error as _, MapAccess, Visitor};
7use serde::ser::SerializeMap;
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use crate::tool_names::{OverlayToolName, ParsedToolName};
11use crate::tool_policy::ToolAction;
12
13/// Tool rules keyed by tool name, in the order the author wrote them.
14///
15/// Two spellings of one key (`Bash` beside `bash`, or `bash(git push:*)` beside
16/// `bash(git push *)`) are one key: a table that holds both fails to load, since file order
17/// would otherwise pick the winner.
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub struct ToolRuleMap {
20    entries: Vec<(OverlayToolName, ToolAction)>,
21}
22
23impl ToolRuleMap {
24    pub fn is_empty(&self) -> bool {
25        self.entries.is_empty()
26    }
27
28    pub fn len(&self) -> usize {
29        self.entries.len()
30    }
31
32    pub fn iter(&self) -> impl Iterator<Item = (&OverlayToolName, ToolAction)> {
33        self.entries.iter().map(|(name, action)| (name, *action))
34    }
35
36    /// The message that refuses a `*` rule in `table`, where it was written: `*` is one agent's
37    /// default, so only a table that speaks for one agent may set it. `reason` says why this
38    /// table cannot.
39    pub fn wildcard_refusal(&self, table: &str, reason: &str) -> Option<String> {
40        let (name, action) = self
41            .iter()
42            .find(|(name, _)| name.parsed().capability == crate::tool_names::Capability::Any)?;
43        Some(format!(
44            "`{table}` `{}` = \"{}\": `*` is not accepted: {reason}",
45            String::from(name.clone()),
46            action.as_str()
47        ))
48    }
49
50    pub fn contains_key(&self, key: &ParsedToolName) -> bool {
51        self.entries.iter().any(|(name, _)| name.parsed() == key)
52    }
53
54    /// `lower` with every key that `higher` names replaced by `higher`'s entry, then the rest
55    /// of `higher`. Keys compare by their parsed form, and `higher`'s spelling is the one kept.
56    pub fn merge_by_key(lower: &Self, higher: &Self) -> Self {
57        let mut entries: Vec<_> = lower
58            .entries
59            .iter()
60            .filter(|(name, _)| !higher.contains_key(name.parsed()))
61            .cloned()
62            .collect();
63        entries.extend(higher.entries.iter().cloned());
64        Self { entries }
65    }
66}
67
68impl Serialize for ToolRuleMap {
69    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
70        let mut map = serializer.serialize_map(Some(self.entries.len()))?;
71        for (name, action) in &self.entries {
72            map.serialize_entry(&String::from(name.clone()), action)?;
73        }
74        map.end()
75    }
76}
77
78impl<'de> Deserialize<'de> for ToolRuleMap {
79    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
80        struct MapVisitor;
81
82        impl<'de> Visitor<'de> for MapVisitor {
83            type Value = ToolRuleMap;
84
85            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86                f.write_str("a table of tool name to allow, deny or ask")
87            }
88
89            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
90                let mut entries: Vec<(OverlayToolName, ToolAction)> = Vec::new();
91                while let Some(raw) = map.next_key::<String>()? {
92                    let action = map.next_value::<ToolAction>()?;
93                    let name = OverlayToolName::try_from(raw).map_err(A::Error::custom)?;
94                    if let Some((earlier, _)) = entries
95                        .iter()
96                        .find(|(earlier, _)| earlier.parsed() == name.parsed())
97                    {
98                        return Err(A::Error::custom(format!(
99                            "`{}` and `{}` name the same tool",
100                            String::from(earlier.clone()),
101                            String::from(name)
102                        )));
103                    }
104                    entries.push((name, action));
105                }
106                Ok(ToolRuleMap { entries })
107            }
108        }
109
110        deserializer.deserialize_map(MapVisitor)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    fn parse(toml: &str) -> Result<ToolRuleMap, toml::de::Error> {
119        toml::from_str(toml)
120    }
121
122    fn keys(map: &ToolRuleMap) -> Vec<(String, &'static str)> {
123        map.iter()
124            .map(|(name, action)| (String::from(name.clone()), action.as_str()))
125            .collect()
126    }
127
128    #[test]
129    fn reads_in_file_order_and_keeps_the_authored_spelling() {
130        let map =
131            parse("zeta = \"deny\"\n\"Bash(git push:*)\" = \"ask\"\nalpha = \"allow\"\n").unwrap();
132        assert_eq!(
133            keys(&map),
134            [
135                ("zeta".into(), "deny"),
136                ("Bash(git push:*)".into(), "ask"),
137                ("alpha".into(), "allow"),
138            ]
139        );
140        let saved = toml::to_string(&map).unwrap();
141        assert_eq!(parse(&saved).unwrap(), map);
142        assert!(saved.contains("\"Bash(git push:*)\""));
143    }
144
145    #[test]
146    fn two_spellings_of_one_key_fail_naming_both() {
147        for (a, b) in [
148            ("Bash", "bash"),
149            ("shell", "bash"),
150            ("bash(git push:*)", "bash(git push *)"),
151        ] {
152            let err = parse(&format!("\"{a}\" = \"deny\"\n\"{b}\" = \"allow\"\n"))
153                .unwrap_err()
154                .to_string();
155            assert!(err.contains(&format!("`{a}`")), "{err}");
156            assert!(err.contains(&format!("`{b}`")), "{err}");
157        }
158    }
159
160    #[test]
161    fn rejects_a_malformed_name_and_an_unknown_action() {
162        assert!(parse("\"bash(\" = \"deny\"\n").is_err());
163        assert!(parse("mcp = \"deny\"\n").is_err());
164        assert!(parse("bash = \"block\"\n").is_err());
165        assert!(parse("bash = 1\n").is_err());
166    }
167
168    #[test]
169    fn merge_replaces_by_parsed_key() {
170        let lower =
171            parse("Bash = \"allow\"\nread = \"deny\"\n\"bash(git push:*)\" = \"allow\"\n").unwrap();
172        let higher =
173            parse("shell = \"deny\"\n\"bash(git push *)\" = \"deny\"\nedit = \"ask\"\n").unwrap();
174        let merged = ToolRuleMap::merge_by_key(&lower, &higher);
175        assert_eq!(
176            keys(&merged),
177            [
178                ("read".into(), "deny"),
179                ("shell".into(), "deny"),
180                ("bash(git push *)".into(), "deny"),
181                ("edit".into(), "ask"),
182            ]
183        );
184        assert_eq!(
185            ToolRuleMap::merge_by_key(&lower, &ToolRuleMap::default()),
186            lower
187        );
188    }
189}