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