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