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)]
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 spellings of an Agent's deny list that Claude and pre-v1 Mars wrote; every translation
247/// reads them as one set, and each name in it is a `deny` rule.
248pub(crate) const DISALLOWED_SPELLINGS: [&str; 3] =
249    ["disallowedTools", "disallowed-tools", "disallowed_tools"];
250
251/// The tool names in a `tools:` / `disallowed-tools:` value. A scalar is Claude's own
252/// agent-file spelling, `tools: Read, Grep`: a comma-separated list. Commas inside a scope
253/// (`bash(rg a,b)`) belong to the entry.
254pub(crate) fn tool_entries(val: &Value) -> Vec<String> {
255    let Value::String(raw) = val else {
256        return yaml_str_list(val);
257    };
258    let mut entries = Vec::new();
259    let mut depth = 0usize;
260    let mut start = 0;
261    for (index, ch) in raw.char_indices() {
262        match ch {
263            '(' => depth += 1,
264            ')' => depth = depth.saturating_sub(1),
265            // Claude writes tool lists comma- or space-separated; parentheses stay whole.
266            ',' | ' ' | '\t' | '\n' if depth == 0 => {
267                entries.push(&raw[start..index]);
268                start = index + 1;
269            }
270            _ => {}
271        }
272    }
273    entries.push(&raw[start..]);
274    entries
275        .into_iter()
276        .map(str::trim)
277        .filter(|entry| !entry.is_empty())
278        .map(str::to_owned)
279        .collect()
280}
281
282pub fn yaml_str_list(val: &Value) -> Vec<String> {
283    match val {
284        Value::Sequence(seq) => seq
285            .iter()
286            .filter_map(|v| v.as_str())
287            .map(str::to_owned)
288            .collect(),
289        Value::String(s) => vec![s.clone()],
290        _ => vec![],
291    }
292}
293
294type OnInvalid<'a> = &'a mut dyn FnMut(Vec<crate::diagnostic::PathSegment>, &str, &'static str);
295
296/// Read a v1 profile's `tools:` action map into one policy.
297///
298/// `on_invalid` gets `(field, value, allowed)` for each entry Mars rejects.
299pub fn parse_tool_policy(tools: Option<&Value>, on_invalid: OnInvalid<'_>) -> EffectiveToolPolicy {
300    let mut policy = EffectiveToolPolicy::default();
301    if let Some(value) = tools {
302        for rule in parse_tools_field(value, on_invalid) {
303            policy.push_unique(rule);
304        }
305    }
306    policy
307}
308
309fn parse_tool_rule(
310    path: Vec<crate::diagnostic::PathSegment>,
311    raw: &str,
312    action: ToolAction,
313    on_invalid: OnInvalid<'_>,
314) -> Option<ToolRule> {
315    match parse_mars_tool_name(raw) {
316        Ok(parsed) => Some(ToolRule::from_parsed(parsed, action)),
317        Err(err) => {
318            on_invalid(path, raw, err.allowed());
319            None
320        }
321    }
322}
323
324/// Parse the v1 `tools:` action map.
325fn parse_tools_field(val: &Value, on_invalid: OnInvalid<'_>) -> Vec<ToolRule> {
326    use crate::diagnostic::{PathSegment, key_path};
327    let field = key_path("tools");
328    if permission_replace_entries(val).is_some() {
329        on_invalid(
330            field.clone(),
331            &crate::ordered::plain(val),
332            "plain list or mapping of tool to allow|deny|ask; package profiles cannot replace a permission set",
333        );
334        return Vec::new();
335    }
336    match val {
337        Value::Mapping(mapping) => {
338            let mut rules = Vec::new();
339            for (key, value) in mapping {
340                let Some(tool_name) = key.as_str() else {
341                    on_invalid(
342                        field.clone(),
343                        &crate::ordered::plain(key),
344                        "string tool keys",
345                    );
346                    continue;
347                };
348
349                let mut entry_path = field.clone();
350                entry_path.push(PathSegment::Key(tool_name.to_owned()));
351                let Some(policy) = value.as_str() else {
352                    on_invalid(entry_path, &crate::ordered::plain(value), ACTIONS_ALLOWED);
353                    continue;
354                };
355                let Some(action) = ToolAction::parse(policy) else {
356                    on_invalid(entry_path, policy, ACTIONS_ALLOWED);
357                    continue;
358                };
359                if let Some(rule) = parse_tool_rule(entry_path, tool_name, action, on_invalid) {
360                    rules.push(rule);
361                }
362            }
363            rules
364        }
365        // `tools: allow` / `tools: deny` was a Meridian-side shorthand that never worked
366        // here: it read as a tool named `allow`. Say so instead of guessing.
367        Value::String(raw) if raw == "allow" || raw == "deny" => {
368            on_invalid(
369                field,
370                raw,
371                "list of tool names or mapping of tool to allow|deny|ask",
372            );
373            Vec::new()
374        }
375        _ => {
376            on_invalid(
377                field,
378                &crate::ordered::plain(val),
379                "mapping of tool to allow|deny|ask",
380            );
381            Vec::new()
382        }
383    }
384}
385
386fn permission_replace_entries(value: &Value) -> Option<&Value> {
387    let mapping = value.as_mapping()?;
388    (mapping.len() == 1)
389        .then(|| mapping.get(Value::String("replace".to_string())))
390        .flatten()
391}
392
393const ACTIONS_ALLOWED: &str = "allow, deny, or ask";
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    fn rule(origin: RuleOrigin) -> ToolRule {
400        ToolRule {
401            capability: Capability::Builtin("bash"),
402            pattern: Some("git push *".into()),
403            action: ToolAction::Deny,
404            origin,
405        }
406    }
407
408    #[test]
409    fn origin_is_not_part_of_identity() {
410        assert_eq!(rule(RuleOrigin::Profile), rule(RuleOrigin::Project));
411
412        let mut policy = EffectiveToolPolicy::default();
413        policy.push_unique(rule(RuleOrigin::Profile));
414        policy.push_unique(rule(RuleOrigin::Overlay));
415        assert_eq!(policy.rules.len(), 1);
416        assert_eq!(policy.rules[0].origin, RuleOrigin::Profile);
417        policy.push_unique(rule(RuleOrigin::Project));
418        assert_eq!(policy.rules.len(), 1);
419        assert_eq!(policy.rules[0].origin, RuleOrigin::Profile);
420    }
421}