Skip to main content

mars_schema/
tool_project.rs

1//! Lowering a tool policy onto one host: the native names each rule becomes, the gaps Mars
2//! cannot name, and which stricter rule wins a shared name.
3//!
4//! Canonical Mars profiles express tool gating with a `tools:` action map (`rule: allow`,
5//! `deny` or `ask`), whole-server or per-tool MCP grants being `mcp(...)` keys in it.
6//! [`project`] spells a policy for one [`Host`]: a harness the binary writes files for, or
7//! Meridian Flow, which only consumes the result. Native agent lowering, skill lowering, the
8//! launch bundle and the WASM export all read that projection; nothing else turns a rule into
9//! native permission names or unscoped harness tool names.
10
11use crate::Host;
12use crate::harness::McpNaming;
13use crate::mcp::{McpRef, McpSegment};
14use crate::tool_cover::covered;
15use crate::tool_names::{Capability, is_mcp_wire_token, render_scoped};
16use crate::tool_natives::{self, Native};
17use crate::tool_policy::{EffectiveToolPolicy, ToolAction, ToolRule};
18use serde::Serialize;
19use serde::ser::{SerializeStruct, Serializer};
20
21/// An MCP ref as `mcp` names it. Server and tool segments are kept verbatim, never re-cased.
22/// Only the hosts that name MCP tools in a tool list reach here: `project_rule` routes
23/// [`McpNaming::Ungated`] and [`McpNaming::ConnectionTools`] before.
24fn mcp_token(mcp: McpNaming, r: &McpRef) -> Result<String, &'static str> {
25    let segment = |segment: &McpSegment| match segment {
26        McpSegment::Any => "*".to_owned(),
27        McpSegment::Named(name) => name.clone(),
28    };
29    let (server, tool) = (segment(&r.server), segment(&r.tool));
30    match mcp {
31        McpNaming::Claude => match (&r.server, &r.tool) {
32            (McpSegment::Any, McpSegment::Named(_)) => {
33                Err("Claude cannot scope a single MCP tool across all servers")
34            }
35            (McpSegment::Any, McpSegment::Any) => Ok("mcp__*".to_owned()),
36            _ => Ok(format!("mcp__{server}__{tool}")),
37        },
38        McpNaming::Format(format) => Ok(format(&server, &tool)),
39        McpNaming::NoName(reason) => Err(reason),
40        McpNaming::Ungated | McpNaming::ConnectionTools => {
41            unreachable!("`project_rule` lowers these hosts' MCP refs before naming a token")
42        }
43    }
44}
45
46/// Whether Mars can name a rule's tools on a harness.
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum NativeStatus {
49    /// Mars knows the native name(s). A stricter rule on the same native name can leave this
50    /// rule no surviving name.
51    Known,
52    /// The harness has no such tool, so there is nothing to allow or deny.
53    Absent,
54    /// Mars cannot name it on this harness, for the reason given: the harness has no switch
55    /// for it, Mars has no row for it, or the name is not one Mars recognizes (a typo). The
56    /// launch bundle reports the reason in `note` and nowhere else.
57    Unknown(&'static str),
58    /// The rule has a pattern and the host's tools take no scope, so it cannot be applied as
59    /// written. Only a host that does not scope patterns reports it.
60    Unscopable,
61}
62
63impl NativeStatus {
64    /// The projection's `status`. The launch bundle has its own, narrower vocabulary.
65    pub fn as_str(self) -> &'static str {
66        match self {
67            Self::Known => "known",
68            Self::Absent => "absent",
69            Self::Unknown(_) => "unknown",
70            Self::Unscopable => "unscopable",
71        }
72    }
73
74    /// Why Mars could not name the rule, for `unknown` and `unscopable`.
75    pub fn note(self) -> Option<&'static str> {
76        match self {
77            Self::Unknown(note) => Some(note),
78            Self::Unscopable => Some(UNSCOPABLE_NOTE),
79            Self::Known | Self::Absent => None,
80        }
81    }
82}
83
84const UNSCOPABLE_NOTE: &str = "this host's tool takes no pattern, so the rule cannot be scoped";
85const FLOW_MCP_DENY_NOTE: &str = "Flow's connection tools are not scoped to one server or tool, so this rule disallows all of them, for every server";
86const FLOW_MCP_ASK_NOTE: &str = "Flow's connection tools are not scoped to one server or tool, so this rule asks before every connection tool, for every server";
87const FLOW_MCP_GRANT_NOTE: &str = "Flow cannot scope a connection tool to one server or tool, so granting them would give every connection; none is given";
88const AGY_MCP_RESTRICTION: &str = "agy gives every agent every MCP server, so this rule cannot restrict them; the restriction is lost";
89const NO_NATIVE_NAME: &str = "no native name known for this tool on this harness; left out";
90
91/// The stricter rule that wins a covered rule's calls, as its author wrote it.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93pub struct CoveredBy {
94    pub action: ToolAction,
95    pub key: String,
96}
97
98impl CoveredBy {
99    fn new(rule: &ToolRule) -> Self {
100        Self {
101            action: rule.action,
102            key: rule.render(),
103        }
104    }
105}
106
107impl std::fmt::Display for CoveredBy {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        write!(f, "{} {}", self.action.as_str(), self.key)
110    }
111}
112
113/// One permission spelling and the unscoped harness tool names the canonical rule concerns.
114///
115/// Keeping the relationship intact lets conflict resolution remove availability tools with
116/// the permission they belong to. Claude scoped rules are the non-trivial case: one
117/// `Edit(path)` permission can concern `Edit`, `Write` and `NotebookEdit`.
118///
119/// A binding is never removed. `beaten_by` marks one a stricter rule wins, so it is still
120/// something the rule makes available but no longer something it tells the permission engine.
121#[derive(Debug, Clone, PartialEq, Eq)]
122struct NativeBinding {
123    native: String,
124    native_tools: Vec<String>,
125    /// The stricter rule (`deny bash`) that wins this name.
126    beaten_by: Option<CoveredBy>,
127}
128
129impl NativeBinding {
130    fn direct(name: &str, pattern: Option<&str>) -> Self {
131        Self {
132            native: render_scoped(name, pattern),
133            native_tools: vec![name.to_string()],
134            beaten_by: None,
135        }
136    }
137
138    fn scoped(name: &str, pattern: &str, native_tools: &[&str]) -> Self {
139        Self {
140            native: render_scoped(name, Some(pattern)),
141            native_tools: native_tools
142                .iter()
143                .map(|name| (*name).to_string())
144                .collect(),
145            beaten_by: None,
146        }
147    }
148}
149
150/// A rule as one harness spells it.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct ProjectedRule {
153    /// Every name the rule makes available. The ones not `beaten_by` are what it tells the
154    /// permission engine ([`Self::native`]); a covered rule tells it nothing, so a reader that
155    /// ignores `covered_by` cannot let through a call the covering rule refuses.
156    bindings: Vec<NativeBinding>,
157    /// `None` for `*`, which names no tool.
158    pub status: Option<NativeStatus>,
159    /// A harness-specific consequence of this projection that callers must surface even when
160    /// the native name is known.
161    note: Option<&'static str>,
162    /// The stricter rule (`deny bash`) that covers this one, so that it never applies: another
163    /// rule wins every call it would match, or every name it has on this harness.
164    pub covered_by: Option<CoveredBy>,
165}
166
167impl ProjectedRule {
168    fn known(bindings: Vec<NativeBinding>, note: Option<&'static str>) -> Self {
169        Self {
170            bindings,
171            status: Some(NativeStatus::Known),
172            note,
173            covered_by: None,
174        }
175    }
176
177    fn with_status(status: NativeStatus) -> Self {
178        Self {
179            bindings: Vec::new(),
180            status: Some(status),
181            note: None,
182            covered_by: None,
183        }
184    }
185
186    fn winning(&self) -> impl Iterator<Item = &NativeBinding> {
187        self.bindings
188            .iter()
189            .filter(|binding| binding.beaten_by.is_none())
190    }
191
192    /// Permission-rule spellings after conflict resolution.
193    pub fn native(&self) -> Vec<String> {
194        self.native_names().cloned().collect()
195    }
196
197    /// Unscoped harness tool names concerned by the surviving permission rules, each once.
198    pub fn native_tools(&self) -> Vec<String> {
199        let mut tools = Vec::new();
200        for binding in self.winning() {
201            for tool in &binding.native_tools {
202                if !tools.contains(tool) {
203                    tools.push(tool.clone());
204                }
205            }
206        }
207        tools
208    }
209
210    fn native_names(&self) -> impl Iterator<Item = &String> {
211        self.winning().map(|binding| &binding.native)
212    }
213
214    /// Every name the rule makes available, whether or not a stricter rule wins it.
215    fn available_names(&self) -> impl Iterator<Item = &String> {
216        self.bindings.iter().map(|binding| &binding.native)
217    }
218
219    fn beat(&mut self, by: CoveredBy) {
220        for binding in &mut self.bindings {
221            binding.beaten_by.get_or_insert_with(|| by.clone());
222        }
223        self.covered_by = Some(by);
224    }
225
226    /// The stricter rule that wins at least one native name this rule makes available.
227    pub fn overridden_by(&self) -> Option<&CoveredBy> {
228        self.bindings
229            .iter()
230            .find_map(|binding| binding.beaten_by.as_ref())
231    }
232
233    /// Why Mars could not name this rule on the harness, when it could not.
234    pub fn gap(&self) -> Option<&'static str> {
235        self.status.and_then(NativeStatus::note)
236    }
237
238    /// A known projection's semantic note, or an unknown projection's gap reason.
239    pub fn note(&self) -> Option<&'static str> {
240        self.note.or_else(|| self.gap())
241    }
242}
243
244/// Project `rule` onto `harness`. The one place a capability becomes native permission names
245/// and unscoped harness tool names.
246///
247/// `restricted` is whether the policy has a `*` rule that is not `allow`: the Agent lists the
248/// tools it has, so an `allow` or `ask` is what would grant a tool.
249fn project_rule(rule: &ToolRule, host: Host, restricted: bool) -> ProjectedRule {
250    let mcp = host.spec().mcp;
251    match &rule.capability {
252        Capability::Any => ProjectedRule {
253            bindings: Vec::new(),
254            status: None,
255            note: None,
256            covered_by: None,
257        },
258        capability if capability.names_mcp() && matches!(mcp, McpNaming::ConnectionTools) => {
259            project_flow_connection_tools(rule.action, restricted)
260        }
261        capability if capability.names_mcp() && matches!(mcp, McpNaming::Ungated) => {
262            project_agy_mcp(rule.action)
263        }
264        Capability::Mcp(mcp_ref) => match mcp_token(mcp, mcp_ref) {
265            Ok(token) => ProjectedRule::known(vec![NativeBinding::direct(&token, None)], None),
266            Err(reason) => ProjectedRule::with_status(NativeStatus::Unknown(reason)),
267        },
268        Capability::Unknown(name) if is_mcp_wire_token(name) => ProjectedRule::known(
269            vec![NativeBinding::direct(name, rule.pattern.as_deref())],
270            None,
271        ),
272        Capability::Unknown(_) => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
273        Capability::Builtin(name) => {
274            project_builtin_capability(name, rule.pattern.as_deref(), host)
275        }
276    }
277}
278
279/// Flow has no per-server MCP tools, only the connection tools in
280/// [`tool_natives::FLOW_CONNECTION_TOOLS`], which take the server as an argument and cannot be
281/// scoped to one. A deny or an ask therefore lands on all of them, whatever it names. A grant
282/// under an allow-list would give every connection and not the one named, so it gives none: the
283/// rule stays `known` with the note, because Flow refuses `unscopable` but shows a note as a warning.
284/// Without an allow-list the tools are available anyway, so an allow loses nothing.
285fn project_flow_connection_tools(action: ToolAction, restricted: bool) -> ProjectedRule {
286    if restricted && action != ToolAction::Deny {
287        return ProjectedRule::known(Vec::new(), Some(FLOW_MCP_GRANT_NOTE));
288    }
289    let note = match action {
290        ToolAction::Deny => Some(FLOW_MCP_DENY_NOTE),
291        ToolAction::Ask => Some(FLOW_MCP_ASK_NOTE),
292        ToolAction::Allow => None,
293    };
294    let bindings = tool_natives::FLOW_CONNECTION_TOOLS
295        .iter()
296        .map(|name| NativeBinding::direct(name, None))
297        .collect();
298    ProjectedRule::known(bindings, note)
299}
300
301/// `agy` gives every agent every MCP server and no `tools` entry names them, so an allow loses
302/// nothing and a deny or an ask cannot be applied.
303fn project_agy_mcp(action: ToolAction) -> ProjectedRule {
304    match action {
305        ToolAction::Allow => ProjectedRule::known(Vec::new(), None),
306        ToolAction::Deny | ToolAction::Ask => {
307            ProjectedRule::with_status(NativeStatus::Unknown(AGY_MCP_RESTRICTION))
308        }
309    }
310}
311
312/// Project one canonical builtin capability through the same table and status semantics as a
313/// profile rule. Launch-bundle platform rules use this without inventing a second native-name
314/// projection path.
315pub fn project_platform_capability(capability: &'static str, host: Host) -> ProjectedRule {
316    project_builtin_capability(capability, None, host)
317}
318
319fn project_builtin_capability(
320    capability: &str,
321    pattern: Option<&str>,
322    host: Host,
323) -> ProjectedRule {
324    let row = tool_natives::lookup(capability, host);
325    if pattern.is_some()
326        && !host.spec().scopes_patterns
327        && matches!(row, Some(Native::Tools(_) | Native::ScopedTools { .. }))
328    {
329        return ProjectedRule::with_status(NativeStatus::Unscopable);
330    }
331    match row {
332        Some(Native::Tools(names)) => ProjectedRule::known(
333            names
334                .iter()
335                .map(|name| NativeBinding::direct(name, pattern))
336                .collect(),
337            None,
338        ),
339        Some(
340            native @ Native::ScopedTools {
341                unscoped,
342                scoped: scoped_names,
343                note,
344            },
345        ) => {
346            let (bindings, note) = match pattern {
347                Some(pattern) => (
348                    scoped_names
349                        .iter()
350                        .map(|name| NativeBinding::scoped(name, pattern, native.native_tools()))
351                        .collect(),
352                    Some(note),
353                ),
354                None => (
355                    unscoped
356                        .iter()
357                        .map(|name| NativeBinding::direct(name, None))
358                        .collect(),
359                    None,
360                ),
361            };
362            ProjectedRule::known(bindings, note)
363        }
364        Some(Native::Absent) => ProjectedRule::with_status(NativeStatus::Absent),
365        Some(Native::NoSwitch(note)) => ProjectedRule::with_status(NativeStatus::Unknown(note)),
366        None => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
367    }
368}
369
370/// Lower `policy` onto `host`. The one place a rule list becomes native names, gaps and
371/// coverage; pure over the rules, the host and the published native tables.
372pub fn project(policy: &EffectiveToolPolicy, host: impl Into<Host>) -> PolicyProjection<'_> {
373    let host = host.into();
374    let restricted = policy
375        .rules
376        .iter()
377        .any(|rule| rule.is_wildcard() && rule.action != ToolAction::Allow);
378    let mut rules: Vec<(&ToolRule, ProjectedRule)> = policy
379        .rules
380        .iter()
381        .map(|rule| (rule, project_rule(rule, host, restricted)))
382        .collect();
383    keep_strictest_per_native(&mut rules);
384    for (index, by) in covered(policy) {
385        rules[index].1.beat(CoveredBy::new(by));
386    }
387    PolicyProjection { host, rules }
388}
389
390/// Which rules that name tools a query covers. `*` names none, so no kind covers it.
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392pub enum RuleKind {
393    /// Built-in tools: everything but MCP refs.
394    Builtin,
395    Mcp,
396    All,
397}
398
399impl RuleKind {
400    fn covers(self, rule: &ToolRule) -> bool {
401        match self {
402            Self::Builtin => !rule.is_mcp() && !rule.is_wildcard(),
403            Self::Mcp => rule.is_mcp(),
404            Self::All => !rule.is_wildcard(),
405        }
406    }
407}
408
409/// The `note` on a rule that lost a native name to a stricter rule on the same name.
410const STRICTER_RULE_NOTE: &str = "a stricter rule controls the same native tool and wins (deny, then ask, then allow); this rule is left out";
411
412/// A policy's rules spelled for one harness, in profile order.
413pub struct PolicyProjection<'a> {
414    host: Host,
415    rules: Vec<(&'a ToolRule, ProjectedRule)>,
416}
417
418impl<'a> PolicyProjection<'a> {
419    pub fn rules(&self) -> &[(&'a ToolRule, ProjectedRule)] {
420        &self.rules
421    }
422
423    /// What a tool no rule names gets: the strictest `*` rule's action, or `None` without one.
424    pub fn default_action(&self) -> Option<ToolAction> {
425        self.rules
426            .iter()
427            .filter(|(rule, _)| rule.is_wildcard())
428            .map(|(rule, _)| rule.action)
429            .max_by_key(|action| action.strictness())
430    }
431
432    /// The projected `kind` rules with `action`: built-in tools first, then MCP refs.
433    fn select(&self, action: ToolAction, kind: RuleKind) -> Vec<&ProjectedRule> {
434        let mut picked: Vec<_> = self
435            .rules
436            .iter()
437            .filter(|(rule, _)| rule.action == action && kind.covers(rule))
438            .collect();
439        picked.sort_by_key(|(rule, _)| rule.is_mcp());
440        picked.into_iter().map(|(_, projected)| projected).collect()
441    }
442
443    /// Native names of the `kind` rules with `action`, built-in tools first, each name once.
444    pub fn natives(&self, action: ToolAction, kind: RuleKind) -> Vec<String> {
445        let mut names: Vec<String> = Vec::new();
446        for projected in self.select(action, kind) {
447            for native in projected.native_names() {
448                if !names.contains(native) {
449                    names.push(native.clone());
450                }
451            }
452        }
453        names
454    }
455
456    /// Names of every allow and ask rule, taken before coverage and conflict resolution cleared
457    /// any: the tools an allowlist must keep available. A deny that beats one of them is
458    /// written beside the list, never by emptying it.
459    pub fn available(&self) -> Vec<String> {
460        let mut names: Vec<String> = Vec::new();
461        let mut rules: Vec<_> = self
462            .rules
463            .iter()
464            .filter(|(rule, _)| rule.action != ToolAction::Deny && !rule.is_wildcard())
465            .collect();
466        rules.sort_by_key(|(rule, _)| rule.is_mcp());
467        for (_, projected) in rules {
468            for name in projected.available_names() {
469                if !names.contains(name) {
470                    names.push(name.clone());
471                }
472            }
473        }
474        names
475    }
476
477    /// Each `kind` rule with `action` that Mars could not name, as the author wrote it, with why.
478    pub fn gaps(&self, action: ToolAction, kind: RuleKind) -> Vec<(String, &'static str)> {
479        self.rules
480            .iter()
481            .filter(|(rule, _)| rule.action == action && kind.covers(rule))
482            .filter_map(|(rule, projected)| Some((rule.render(), projected.gap()?)))
483            .collect()
484    }
485}
486
487/// The published shape of a projection (`project` in the WASM package): per rule, then the
488/// native names each action ends with. A consumer decides from these what to warn about: a
489/// `status` other than `known`, a `covered_by` or a `note` is something the author may not
490/// have meant.
491impl Serialize for PolicyProjection<'_> {
492    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
493        struct Rule<'r>(&'r ToolRule, &'r ProjectedRule);
494        impl Serialize for Rule<'_> {
495            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
496                let Rule(rule, projected) = self;
497                let mut out = serializer.serialize_struct("ProjectedRule", 6)?;
498                out.serialize_field("rule", rule)?;
499                out.serialize_field("status", &projected.status.map(NativeStatus::as_str))?;
500                out.serialize_field("native", &projected.native())?;
501                out.serialize_field("native_tools", &projected.native_tools())?;
502                out.serialize_field("note", &projected.note())?;
503                out.serialize_field("covered_by", &projected.covered_by)?;
504                out.end()
505            }
506        }
507        let rules: Vec<Rule> = self.rules.iter().map(|(r, p)| Rule(r, p)).collect();
508        let mut out = serializer.serialize_struct("ToolProjection", 7)?;
509        out.serialize_field("host", &self.host)?;
510        out.serialize_field("default", &self.default_action().map(ToolAction::as_str))?;
511        out.serialize_field("rules", &rules)?;
512        out.serialize_field("allow", &self.natives(ToolAction::Allow, RuleKind::All))?;
513        out.serialize_field("deny", &self.natives(ToolAction::Deny, RuleKind::All))?;
514        out.serialize_field("ask", &self.natives(ToolAction::Ask, RuleKind::All))?;
515        out.serialize_field("available", &self.available())?;
516        out.end()
517    }
518}
519
520/// Of the rules that name one native permission, the strictest action keeps it (deny, then ask,
521/// then allow), as Claude's own lists do. `edit: deny` beside `write: allow` leaves the allow
522/// no `Write` on Claude and no `write` on Pi; capabilities a harness cannot tell apart
523/// (`write` and `edit` on Codex) resolve the same way. A rule that loses a name gets a note.
524fn keep_strictest_per_native(rules: &mut [(&ToolRule, ProjectedRule)]) {
525    let named: Vec<(&ToolRule, Vec<String>)> = rules
526        .iter()
527        .map(|(rule, projected)| (*rule, projected.native()))
528        .collect();
529    for (rule, projected) in rules.iter_mut() {
530        let mut beaten = 0;
531        for binding in &mut projected.bindings {
532            let by = named.iter().find(|(stricter, names)| {
533                stricter.action.strictness() > rule.action.strictness()
534                    && names.contains(&binding.native)
535            });
536            if let Some((stricter, _)) = by {
537                binding.beaten_by = Some(CoveredBy::new(stricter));
538                beaten += 1;
539            }
540        }
541        if beaten > 0 {
542            projected.note = Some(STRICTER_RULE_NOTE);
543        }
544        if beaten > 0 && beaten == projected.bindings.len() {
545            projected.covered_by = projected.bindings[0].beaten_by.clone();
546        }
547    }
548}
549
550#[cfg(test)]
551mod tests {
552    use super::*;
553    use crate::HarnessId;
554    use crate::frontmatter::Frontmatter;
555    use crate::tool_names::parse_mars_tool_name;
556    use crate::tool_policy::append_mcp_server_entries_to_tools;
557    use serde_yaml::Value;
558
559    fn agent_policy(yaml: &str) -> EffectiveToolPolicy {
560        let reading = crate::agent::read(yaml);
561        assert!(
562            reading.diagnostics.is_empty(),
563            "agent diags: {:?}",
564            reading.diagnostics
565        );
566        reading.fields.unwrap().tools
567    }
568
569    /// Native names and status of a raw tool entry on a harness, via parse then table.
570    fn natives(raw: &str, harness: &str) -> (Vec<String>, &'static str) {
571        let kind = Host::parse(harness).expect("test host exists");
572        let parsed = parse_mars_tool_name(raw).unwrap();
573        let projected = project_rule(
574            &ToolRule::from_parsed(parsed, ToolAction::Deny),
575            kind,
576            false,
577        );
578        (
579            projected.native(),
580            projected.status.map_or("none", NativeStatus::as_str),
581        )
582    }
583
584    fn known(names: &[&str]) -> (Vec<String>, &'static str) {
585        (names.iter().map(|n| n.to_string()).collect(), "known")
586    }
587
588    #[test]
589    fn covered_allows_stay_available() {
590        // `deny` covers the allow, so the allow names no permission; the tool it opens stays
591        // on Claude's `tools:` list, and the deny is what takes it back.
592        let policy = agent_policy(
593            "---\nname: a\ndescription: d\ntools:\n  '*': deny\n  write: allow\n  edit: deny\n  'bash(git status *)': allow\n  bash: ask\n---\n",
594        );
595        let projection = project(&policy, HarnessId::Claude);
596        assert_eq!(
597            projection.natives(ToolAction::Allow, RuleKind::All),
598            Vec::<String>::new()
599        );
600        assert_eq!(
601            projection.available(),
602            ["Write", "Bash(git status *)", "Bash"]
603        );
604    }
605
606    #[test]
607    fn append_mcp_server_entries_to_tools_preserves_map_form() {
608        let mut fm = Frontmatter::parse("---\ntools:\n  Bash: allow\n  Read: deny\n---\n").unwrap();
609        assert!(append_mcp_server_entries_to_tools(
610            &mut fm,
611            &["context7".to_string(), "github".to_string()]
612        ));
613        let tools = fm.get("tools").unwrap();
614        let Value::Mapping(mapping) = tools else {
615            panic!("expected map-form tools, got {tools:?}");
616        };
617        assert_eq!(
618            mapping.get(Value::String("Bash".into())),
619            Some(&Value::String("allow".into()))
620        );
621        assert_eq!(
622            mapping.get(Value::String("Read".into())),
623            Some(&Value::String("deny".into()))
624        );
625        assert_eq!(
626            mapping.get(Value::String("mcp(context7)".into())),
627            Some(&Value::String("allow".into()))
628        );
629        assert_eq!(
630            mapping.get(Value::String("mcp(github)".into())),
631            Some(&Value::String("allow".into()))
632        );
633    }
634
635    #[test]
636    fn map_form_allows_are_grants_not_an_allowlist() {
637        let policy = agent_policy(
638            "---\nname: a\ndescription: d\ntools:\n  read: allow\n  edit: deny\n---\n",
639        );
640        assert_eq!(policy.describe(), vec!["allow:read", "deny:edit"]);
641        assert!(!policy.is_allowlist());
642    }
643
644    #[test]
645    fn explicit_wildcard_deny_makes_a_map_an_allowlist() {
646        let policy = agent_policy(
647            "---\nname: a\ndescription: d\ntools:\n  '*': deny\n  'bash(rg *)': allow\n---\n",
648        );
649        assert_eq!(policy.describe(), vec!["deny:*", "allow:bash(rg *)"]);
650        assert!(policy.is_allowlist());
651    }
652
653    #[test]
654    fn the_strictest_action_keeps_each_native_name_on_every_harness() {
655        // (rules, harness, the allow rule's surviving names, the deny rule's)
656        type Row = (
657            &'static str,
658            &'static str,
659            HarnessId,
660            &'static [&'static str],
661            &'static [&'static str],
662        );
663        let rows: &[Row] = &[
664            (
665                "edit",
666                "write",
667                HarnessId::Claude,
668                &[],
669                &["Edit", "Write", "NotebookEdit"],
670            ),
671            (
672                "edit",
673                "notebook",
674                HarnessId::Claude,
675                &[],
676                &["Edit", "Write", "NotebookEdit"],
677            ),
678            ("edit", "write", HarnessId::Pi, &[], &["edit", "write"]),
679            ("edit", "write", HarnessId::Codex, &[], &["apply_patch"]),
680            ("edit", "write", HarnessId::OpenCode, &[], &["edit"]),
681            (
682                "web",
683                "web_fetch",
684                HarnessId::Claude,
685                &[],
686                &["WebSearch", "WebFetch"],
687            ),
688            (
689                "web",
690                "web_search",
691                HarnessId::Claude,
692                &[],
693                &["WebSearch", "WebFetch"],
694            ),
695        ];
696        for (deny, allow, harness, allowed, denied) in rows {
697            let policy = agent_policy(&format!(
698                "---\nname: a\ndescription: d\ntools:\n  {deny}: deny\n  {allow}: allow\n---\n"
699            ));
700            let projection = project(&policy, *harness);
701            assert_eq!(
702                projection.rules()[1].1.native(),
703                *allowed,
704                "{deny}/{allow} {harness:?}"
705            );
706            assert!(projection.rules()[1].1.note().is_some());
707            assert_eq!(
708                projection.rules()[0].1.native(),
709                *denied,
710                "{deny}/{allow} {harness:?}"
711            );
712        }
713    }
714
715    #[test]
716    fn a_scoped_rule_does_not_narrow_an_unscoped_one() {
717        let policy = agent_policy(
718            "---\nname: a\ndescription: d\ntools:\n  bash: allow\n  'bash(git push *)': deny\n---\n",
719        );
720        let projection = project(&policy, HarnessId::Claude);
721        assert_eq!(projection.rules()[0].1.native(), ["Bash"]);
722        assert_eq!(projection.rules()[1].1.native(), ["Bash(git push *)"]);
723    }
724
725    #[test]
726    fn mcp_server_entries_appended_to_absent_tools_do_not_create_an_allowlist() {
727        // A Claude agent with `mcpServers` and no `tools:` inherits every tool. The
728        // synthesized `mcp(server)` grant must not turn that into "MCP only".
729        let mut fm = Frontmatter::parse("---\nname: a\n---\n").unwrap();
730        assert!(append_mcp_server_entries_to_tools(
731            &mut fm,
732            &["context7".to_string()]
733        ));
734        let policy = crate::agent::read(&fm.render()).fields.unwrap().tools;
735        assert_eq!(policy.describe(), vec!["allow:mcp(context7/*)"]);
736        assert!(!policy.is_allowlist());
737    }
738
739    #[test]
740    fn aliases_and_native_spellings_reach_the_same_native_tools() {
741        assert_eq!(natives("Bash", "codex"), known(&["exec_command"]));
742        assert_eq!(natives("shell", "claude"), known(&["Bash"]));
743        assert_eq!(natives("exec_command", "claude"), known(&["Bash"]));
744        assert_eq!(natives("WebSearch", "opencode"), known(&["websearch"]));
745        assert_eq!(
746            natives("web", "opencode"),
747            known(&["websearch", "webfetch"])
748        );
749        assert_eq!(
750            natives("AskUserQuestion", "claude"),
751            known(&["AskUserQuestion"])
752        );
753        assert_eq!(natives("askuser", "opencode"), known(&["question"]));
754        assert_eq!(
755            natives("edit", "claude"),
756            known(&["Edit", "Write", "NotebookEdit"])
757        );
758        assert_eq!(natives("todowrite", "claude").0.len(), 7);
759    }
760
761    #[test]
762    fn claude_scoped_file_rules_separate_permissions_from_callable_tools() {
763        assert_eq!(
764            natives("bash(git push *)", "codex"),
765            known(&["exec_command(git push *)"])
766        );
767        for (rule, native, native_tools) in [
768            ("read(src/**)", "Read(src/**)", &["Read"][..]),
769            ("write(src/**)", "Edit(src/**)", &["Write"][..]),
770            (
771                "edit(src/**)",
772                "Edit(src/**)",
773                &["Edit", "Write", "NotebookEdit"][..],
774            ),
775            ("notebook(src/**)", "Edit(src/**)", &["NotebookEdit"][..]),
776            ("glob(src/**)", "Read(src/**)", &["Glob"][..]),
777            ("grep(src/**)", "Read(src/**)", &["Grep"][..]),
778            (
779                "web_fetch(domain:example.com)",
780                "WebFetch(domain:example.com)",
781                &["WebFetch"][..],
782            ),
783        ] {
784            assert_eq!(natives(rule, "claude"), known(&[native]), "{rule}");
785            let parsed = parse_mars_tool_name(rule).unwrap();
786            let projected = project_rule(
787                &ToolRule::from_parsed(parsed, ToolAction::Deny),
788                Host::Harness(HarnessId::Claude),
789                false,
790            );
791            assert_eq!(projected.native_tools(), native_tools, "{rule}");
792        }
793
794        let write = project_rule(
795            &ToolRule::from_parsed(
796                parse_mars_tool_name("write(src/**)").unwrap(),
797                ToolAction::Allow,
798            ),
799            Host::Harness(HarnessId::Claude),
800            false,
801        );
802        assert!(
803            write
804                .note()
805                .is_some_and(|note| note.contains("deny also refuses other built-in file edits")),
806            "{:?}",
807            write.note()
808        );
809    }
810
811    #[test]
812    fn claude_strictest_action_wins_when_scoped_capabilities_share_a_permission() {
813        let policy = agent_policy(
814            "---\nname: a\ndescription: d\ntools:\n  'write(src/**)': allow\n  'edit(src/**)': ask\n  'notebook(src/**)': deny\n---\n",
815        );
816        let projection = project(&policy, HarnessId::Claude);
817        assert!(projection.rules()[0].1.native().is_empty(), "allow loses");
818        assert!(
819            projection.rules()[0].1.native_tools().is_empty(),
820            "shadowed rules name no availability tools"
821        );
822        assert!(projection.rules()[1].1.native().is_empty(), "ask loses");
823        assert!(projection.rules()[1].1.native_tools().is_empty());
824        assert_eq!(projection.rules()[2].1.native(), ["Edit(src/**)"]);
825        assert_eq!(projection.rules()[2].1.native_tools(), ["NotebookEdit"]);
826        assert_eq!(
827            projection.natives(ToolAction::Deny, RuleKind::Builtin),
828            ["Edit(src/**)"]
829        );
830        assert!(
831            projection.rules()[0]
832                .1
833                .note()
834                .is_some_and(|note| note.contains("deny, then ask, then allow"))
835        );
836    }
837
838    #[test]
839    fn a_tool_the_harness_lacks_is_absent_not_guessed() {
840        assert_eq!(natives("notebook", "codex"), (vec![], "absent"));
841        assert_eq!(natives("ask_user", "pi"), (vec![], "absent"));
842    }
843
844    #[test]
845    fn a_thing_the_harness_can_do_without_a_tool_to_switch_is_unknown_not_absent() {
846        // Codex fetches pages through `web_search` and reads, globs and greps through its shell;
847        // Codex and Pi load skills by reading files.
848        for (capability, harness) in [
849            ("web_fetch", "codex"),
850            ("skill", "codex"),
851            ("skill", "pi"),
852            ("read", "codex"),
853            ("glob", "codex"),
854            ("grep", "codex"),
855        ] {
856            assert_eq!(
857                natives(capability, harness),
858                (vec![], "unknown"),
859                "{harness} {capability}"
860            );
861        }
862    }
863
864    #[test]
865    fn a_name_without_a_table_row_is_unknown_with_no_native_name() {
866        // Not a capability at all, including one that merely looks like the `mcp` capability.
867        for harness in ["claude", "codex", "opencode", "pi"] {
868            assert_eq!(
869                natives("my_custom_tool", harness),
870                (vec![], "unknown"),
871                "{harness}"
872            );
873        }
874        for raw in ["café_tool", "🚀tool"] {
875            assert_eq!(natives(raw, "claude"), (vec![], "unknown"));
876        }
877    }
878
879    #[test]
880    fn mcp_wire_tokens_are_verbatim_on_every_harness() {
881        for raw in [
882            "mcp__github__CreateIssue",
883            "MCP__Server__Tool",
884            "mcp__github__create_issue",
885        ] {
886            for harness in ["claude", "codex", "opencode", "pi"] {
887                assert_eq!(natives(raw, harness), known(&[raw]), "{raw} on {harness}");
888                let kind = Host::parse(harness).expect("test host exists");
889                let projected = project_rule(
890                    &ToolRule::from_parsed(parse_mars_tool_name(raw).unwrap(), ToolAction::Deny),
891                    kind,
892                    false,
893                );
894                assert_eq!(projected.native_tools(), [raw], "{raw} on {harness}");
895            }
896        }
897    }
898
899    #[test]
900    fn the_any_capability_names_no_tool_and_has_no_status() {
901        assert_eq!(natives("*", "claude"), (vec![], "none"));
902    }
903}