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