Skip to main content

mars_schema/
tool_policy.rs

1//! Canonical authored tool-policy values and frontmatter parsing.
2
3use crate::frontmatter::Frontmatter;
4use crate::tool_names::{Capability, ParsedToolName, parse_mars_tool_name, render_scoped};
5use serde::ser::{Serialize, SerializeMap, Serializer};
6use serde_yaml::Value;
7
8/// What a rule does when its capability (and pattern) match.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
10#[serde(rename_all = "lowercase")]
11pub enum ToolAction {
12    Allow,
13    Deny,
14    Ask,
15}
16
17impl ToolAction {
18    pub fn as_str(self) -> &'static str {
19        match self {
20            Self::Allow => "allow",
21            Self::Deny => "deny",
22            Self::Ask => "ask",
23        }
24    }
25
26    /// How restrictive the action is; the stricter action of two rules that match a call wins.
27    pub fn strictness(self) -> u8 {
28        match self {
29            Self::Allow => 0,
30            Self::Ask => 1,
31            Self::Deny => 2,
32        }
33    }
34
35    pub fn parse(raw: &str) -> Option<Self> {
36        match raw {
37            "allow" => Some(Self::Allow),
38            "deny" => Some(Self::Deny),
39            "ask" => Some(Self::Ask),
40            _ => None,
41        }
42    }
43}
44
45/// Where a rule came from. It is not part of a rule's identity: two rules with the same
46/// capability, pattern and action are one rule whatever their origin.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize)]
48#[serde(rename_all = "lowercase")]
49pub enum RuleOrigin {
50    /// The agent's or skill's own profile.
51    #[default]
52    Profile,
53    /// `allowed` / `disallowed` or a rule map in an `[agents.<name>.tools]` overlay.
54    Overlay,
55    /// `[settings.tools]`, which holds for every agent.
56    Project,
57    /// `[package.tools]`, added to every Agent the package ships that does not name the key.
58    Package,
59}
60
61impl RuleOrigin {
62    pub fn as_str(self) -> &'static str {
63        match self {
64            Self::Profile => "profile",
65            Self::Overlay => "overlay",
66            Self::Project => "project",
67            Self::Package => "package",
68        }
69    }
70}
71
72/// One tool-policy statement: `action` for `capability`, optionally narrowed by `pattern`.
73///
74/// Rules are kept in profile order, which carries no precedence: of the rules that match a call,
75/// the strictest action wins (deny, then ask, then allow), however narrow a key is.
76/// [`crate::tool_project::project`] applies the same order to a native name two rules share, and
77/// gives a rule that a stricter one covers no native name.
78#[derive(Debug, Clone)]
79pub struct ToolRule {
80    pub capability: Capability,
81    /// Scope inside `capability(...)`. `None` for `*` and `mcp`, whose scope is the capability.
82    pub pattern: Option<String>,
83    pub action: ToolAction,
84    pub origin: RuleOrigin,
85}
86
87/// Equality ignores `origin`: `merge_permission_set` and `push_unique` rely on it to fold a
88/// rule that two layers both state into one.
89impl PartialEq for ToolRule {
90    fn eq(&self, other: &Self) -> bool {
91        self.capability == other.capability
92            && self.pattern == other.pattern
93            && self.action == other.action
94    }
95}
96
97impl Eq for ToolRule {}
98
99impl ToolRule {
100    pub fn from_parsed(parsed: ParsedToolName, action: ToolAction) -> Self {
101        Self {
102            capability: parsed.capability,
103            pattern: parsed.pattern,
104            action,
105            origin: RuleOrigin::Profile,
106        }
107    }
108
109    /// A rule from its wire shape (`{capability, pattern, action}`, as `agent::read` reports
110    /// it and `Serialize` writes it), parsed like the authored key it renders to.
111    pub fn from_wire(
112        capability: &str,
113        pattern: Option<&str>,
114        action: ToolAction,
115    ) -> Result<Self, crate::tool_names::ToolNameParseError> {
116        let key = match (capability, pattern) {
117            ("mcp", Some(pattern)) => format!("mcp({pattern})"),
118            _ => render_scoped(capability, pattern),
119        };
120        Ok(Self::from_parsed(parse_mars_tool_name(&key)?, action))
121    }
122
123    pub fn with_origin(mut self, origin: RuleOrigin) -> Self {
124        self.origin = origin;
125        self
126    }
127
128    pub fn is_wildcard(&self) -> bool {
129        matches!(self.capability, Capability::Any)
130    }
131
132    pub fn is_mcp(&self) -> bool {
133        matches!(self.capability, Capability::Mcp(_))
134    }
135
136    /// Canonical `capability(pattern)` spelling, for diagnostics and frontmatter.
137    pub fn render(&self) -> String {
138        match &self.capability {
139            Capability::Mcp(mcp_ref) => mcp_ref.to_canonical(),
140            capability => render_scoped(capability.name(), self.pattern.as_deref()),
141        }
142    }
143
144    /// The pattern as the bundle and `show --json` print it: an `mcp` rule's `server/tool`.
145    fn wire_pattern(&self) -> Option<String> {
146        match &self.capability {
147            Capability::Mcp(mcp_ref) => Some(mcp_ref.to_pattern()),
148            _ => self.pattern.clone(),
149        }
150    }
151}
152
153/// The rule's wire shape, shared by the launch bundle's `tools.rules` and `agents show --json`:
154/// `{capability, pattern, action, origin}`. `capability` is `*` for "every other tool" and
155/// `mcp` for an MCP ref, whose `pattern` is its `server/tool`.
156impl Serialize for ToolRule {
157    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
158        let mut map = serializer.serialize_map(None)?;
159        map.serialize_entry("capability", self.capability.name())?;
160        map.serialize_entry("pattern", &self.wire_pattern())?;
161        map.serialize_entry("action", self.action.as_str())?;
162        map.serialize_entry("origin", self.origin.as_str())?;
163        map.end()
164    }
165}
166
167/// The tool rules of an agent or skill.
168#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
169#[serde(transparent)]
170pub struct EffectiveToolPolicy {
171    pub rules: Vec<ToolRule>,
172}
173
174impl EffectiveToolPolicy {
175    pub fn with_action(&self, action: ToolAction) -> impl Iterator<Item = &ToolRule> {
176        self.rules.iter().filter(move |rule| rule.action == action)
177    }
178    pub fn describe(&self) -> Vec<String> {
179        self.rules
180            .iter()
181            .map(|rule| format!("{}:{}", rule.action.as_str(), rule.render()))
182            .collect()
183    }
184    pub fn rendered(&self, action: ToolAction) -> Vec<String> {
185        self.with_action(action)
186            .filter(|rule| !rule.is_wildcard())
187            .map(ToolRule::render)
188            .collect()
189    }
190    pub fn is_allowlist(&self) -> bool {
191        self.rules
192            .iter()
193            .any(|rule| rule.is_wildcard() && rule.action == ToolAction::Deny)
194    }
195    /// Add `rule` unless an equal one is there. The first rule's origin stays: consumers act on
196    /// origin (a continued session replaces `Project` rules with the current ones, and the
197    /// platform `task` opt-out reads only profile and overlay rules), and the rule already
198    /// held says what the copy would.
199    pub fn push_unique(&mut self, rule: ToolRule) {
200        if !self.rules.contains(&rule) {
201            self.rules.push(rule);
202        }
203    }
204}
205
206/// Append whole-server `mcp(server)` entries to the frontmatter `tools:` list or map.
207pub fn append_mcp_server_entries_to_tools(fm: &mut Frontmatter, servers: &[String]) -> bool {
208    let entries: Vec<String> = servers
209        .iter()
210        .map(|server| server.trim())
211        .filter(|server| !server.is_empty())
212        .map(|server| format!("mcp({server})"))
213        .collect();
214    if entries.is_empty() {
215        return false;
216    }
217
218    let Some(existing) = fm.get("tools").cloned() else {
219        // Map form: an absent `tools:` inherits every tool, and a list here would read as an
220        // allowlist of only these MCP servers.
221        let grants = entries
222            .into_iter()
223            .map(|entry| (Value::String(entry), Value::String("allow".into())))
224            .collect::<serde_yaml::Mapping>();
225        fm.insert("tools", Value::Mapping(grants));
226        return true;
227    };
228
229    match existing {
230        Value::Mapping(mut mapping) => {
231            let mut changed = false;
232            for entry in entries {
233                let key = Value::String(entry);
234                if !mapping.contains_key(&key) {
235                    mapping.insert(key, Value::String("allow".into()));
236                    changed = true;
237                }
238            }
239            if changed {
240                fm.insert("tools", Value::Mapping(mapping));
241            }
242            changed
243        }
244        other => {
245            let mut tools = tool_entries(&other);
246            let mut changed = false;
247            for entry in entries {
248                if !tools.iter().any(|existing| existing == &entry) {
249                    tools.push(entry);
250                    changed = true;
251                }
252            }
253            if changed {
254                fm.insert(
255                    "tools",
256                    Value::Sequence(tools.into_iter().map(Value::String).collect()),
257                );
258            }
259            changed
260        }
261    }
262}
263
264/// The spellings of an Agent's deny list that Claude and pre-v1 Mars wrote; every translation
265/// reads them as one set, and each name in it is a `deny` rule.
266pub(crate) const DISALLOWED_SPELLINGS: [&str; 3] =
267    ["disallowedTools", "disallowed-tools", "disallowed_tools"];
268
269/// The tool names in a `tools:` / `disallowed-tools:` value. A scalar is Claude's own
270/// agent-file spelling, `tools: Read, Grep`: a comma-separated list. Commas inside a scope
271/// (`bash(rg a,b)`) belong to the entry.
272pub(crate) fn tool_entries(val: &Value) -> Vec<String> {
273    let Value::String(raw) = val else {
274        return yaml_str_list(val);
275    };
276    let mut entries = Vec::new();
277    let mut depth = 0usize;
278    let mut start = 0;
279    for (index, ch) in raw.char_indices() {
280        match ch {
281            '(' => depth += 1,
282            ')' => depth = depth.saturating_sub(1),
283            // Claude writes tool lists comma- or space-separated; parentheses stay whole.
284            ',' | ' ' | '\t' | '\n' if depth == 0 => {
285                entries.push(&raw[start..index]);
286                start = index + 1;
287            }
288            _ => {}
289        }
290    }
291    entries.push(&raw[start..]);
292    entries
293        .into_iter()
294        .map(str::trim)
295        .filter(|entry| !entry.is_empty())
296        .map(str::to_owned)
297        .collect()
298}
299
300pub fn yaml_str_list(val: &Value) -> Vec<String> {
301    match val {
302        Value::Sequence(seq) => seq
303            .iter()
304            .filter_map(|v| v.as_str())
305            .map(str::to_owned)
306            .collect(),
307        Value::String(s) => vec![s.clone()],
308        _ => vec![],
309    }
310}
311
312type OnInvalid<'a> = &'a mut dyn FnMut(Vec<crate::diagnostic::PathSegment>, &str, &'static str);
313
314/// Read a v1 profile's `tools:` action map into one policy.
315///
316/// `on_invalid` gets `(field, value, allowed)` for each entry Mars rejects.
317pub fn parse_tool_policy(tools: Option<&Value>, on_invalid: OnInvalid<'_>) -> EffectiveToolPolicy {
318    let mut policy = EffectiveToolPolicy::default();
319    if let Some(value) = tools {
320        for rule in parse_tools_field(value, on_invalid) {
321            policy.push_unique(rule);
322        }
323    }
324    policy
325}
326
327fn parse_tool_rule(
328    path: Vec<crate::diagnostic::PathSegment>,
329    raw: &str,
330    action: ToolAction,
331    on_invalid: OnInvalid<'_>,
332) -> Option<ToolRule> {
333    match parse_mars_tool_name(raw) {
334        Ok(parsed) => Some(ToolRule::from_parsed(parsed, action)),
335        Err(err) => {
336            on_invalid(path, raw, err.allowed());
337            None
338        }
339    }
340}
341
342/// Parse the v1 `tools:` action map.
343fn parse_tools_field(val: &Value, on_invalid: OnInvalid<'_>) -> Vec<ToolRule> {
344    use crate::diagnostic::{PathSegment, key_path};
345    let field = key_path("tools");
346    if permission_replace_entries(val).is_some() {
347        on_invalid(
348            field.clone(),
349            &crate::ordered::plain(val),
350            "plain list or mapping of tool to allow|deny|ask; package profiles cannot replace a permission set",
351        );
352        return Vec::new();
353    }
354    match val {
355        Value::Mapping(mapping) => {
356            let mut rules = Vec::new();
357            for (key, value) in mapping {
358                let Some(tool_name) = key.as_str() else {
359                    on_invalid(
360                        field.clone(),
361                        &crate::ordered::plain(key),
362                        "string tool keys",
363                    );
364                    continue;
365                };
366
367                let mut entry_path = field.clone();
368                entry_path.push(PathSegment::Key(tool_name.to_owned()));
369                let Some(policy) = value.as_str() else {
370                    on_invalid(entry_path, &crate::ordered::plain(value), ACTIONS_ALLOWED);
371                    continue;
372                };
373                let Some(action) = ToolAction::parse(policy) else {
374                    on_invalid(entry_path, policy, ACTIONS_ALLOWED);
375                    continue;
376                };
377                if let Some(rule) = parse_tool_rule(entry_path, tool_name, action, on_invalid) {
378                    rules.push(rule);
379                }
380            }
381            rules
382        }
383        // `tools: allow` / `tools: deny` was a Meridian-side shorthand that never worked
384        // here: it read as a tool named `allow`. Say so instead of guessing.
385        Value::String(raw) if raw == "allow" || raw == "deny" => {
386            on_invalid(
387                field,
388                raw,
389                "list of tool names or mapping of tool to allow|deny|ask",
390            );
391            Vec::new()
392        }
393        _ => {
394            on_invalid(
395                field,
396                &crate::ordered::plain(val),
397                "mapping of tool to allow|deny|ask",
398            );
399            Vec::new()
400        }
401    }
402}
403
404fn permission_replace_entries(value: &Value) -> Option<&Value> {
405    let mapping = value.as_mapping()?;
406    (mapping.len() == 1)
407        .then(|| mapping.get(Value::String("replace".to_string())))
408        .flatten()
409}
410
411const ACTIONS_ALLOWED: &str = "allow, deny, or ask";
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    fn rule(origin: RuleOrigin) -> ToolRule {
418        ToolRule {
419            capability: Capability::Builtin("bash"),
420            pattern: Some("git push *".into()),
421            action: ToolAction::Deny,
422            origin,
423        }
424    }
425
426    #[test]
427    fn origin_is_not_part_of_identity() {
428        assert_eq!(rule(RuleOrigin::Profile), rule(RuleOrigin::Project));
429
430        let mut policy = EffectiveToolPolicy::default();
431        policy.push_unique(rule(RuleOrigin::Profile));
432        policy.push_unique(rule(RuleOrigin::Overlay));
433        assert_eq!(policy.rules.len(), 1);
434        assert_eq!(policy.rules[0].origin, RuleOrigin::Profile);
435        policy.push_unique(rule(RuleOrigin::Project));
436        assert_eq!(policy.rules.len(), 1);
437        assert_eq!(policy.rules[0].origin, RuleOrigin::Profile);
438    }
439}