Skip to main content

base/interface/
tool_selector.rs

1//! Which tools a session may have, as allow and deny lists that only ever
2//! narrow: one matching semantics for a scene's lists, an agent type's and a
3//! caller's. A deny always holds, whether or not an allow list is given, and
4//! an MCP server is named by its configured name and matched on the tool's
5//! origin, never parsed out of the tool's name.
6
7use super::tool::ToolOrigin;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum ToolPattern {
11    Name(String),
12    Prefix(String),
13    McpServer(String),
14    AnyMcp,
15}
16
17impl ToolPattern {
18    /// `mcp__*` is every MCP tool; `mcp__s` and `mcp__s__*` are server `s`'s;
19    /// `mcp__s__t` is that one tool by name; `X*` is every name starting `X`;
20    /// anything else is one name.
21    pub fn parse(pattern: &str) -> Self {
22        if let Some(rest) = pattern.strip_prefix("mcp__") {
23            if rest == "*" {
24                return Self::AnyMcp;
25            }
26            if let Some(server) = rest.strip_suffix("__*") {
27                return Self::McpServer(server.to_string());
28            }
29            if !rest.is_empty() && !rest.contains("__") {
30                return Self::McpServer(rest.to_string());
31            }
32        }
33        match pattern.strip_suffix('*') {
34            Some(prefix) => Self::Prefix(prefix.to_string()),
35            None => Self::Name(pattern.to_string()),
36        }
37    }
38
39    pub fn matches(&self, name: &str, origin: &ToolOrigin) -> bool {
40        match self {
41            Self::Name(n) => name == n,
42            Self::Prefix(p) => name.starts_with(p.as_str()),
43            Self::McpServer(s) => origin.mcp_server() == Some(s.as_str()),
44            Self::AnyMcp => origin.is_mcp(),
45        }
46    }
47
48    /// Every tool `other` matches, this matches too.
49    fn covers(&self, other: &Self) -> bool {
50        match (self, other) {
51            (a, b) if a == b => true,
52            (Self::AnyMcp, Self::McpServer(_)) => true,
53            (Self::Prefix(p), Self::Prefix(q)) => q.starts_with(p.as_str()),
54            (Self::Prefix(p), Self::Name(n)) => n.starts_with(p.as_str()),
55            _ => false,
56        }
57    }
58
59    /// No tool matches both. Unknowable for a name against an origin, so
60    /// those are taken to overlap.
61    fn disjoint(&self, other: &Self) -> bool {
62        match (self, other) {
63            (Self::Name(a), Self::Name(b)) => a != b,
64            (Self::Name(n), Self::Prefix(p)) | (Self::Prefix(p), Self::Name(n)) => {
65                !n.starts_with(p.as_str())
66            }
67            (Self::Prefix(a), Self::Prefix(b)) => {
68                !a.starts_with(b.as_str()) && !b.starts_with(a.as_str())
69            }
70            (Self::McpServer(a), Self::McpServer(b)) => a != b,
71            _ => false,
72        }
73    }
74}
75
76/// The form [`ToolPattern::parse`] reads back to the same pattern; a server
77/// is written `mcp__<server>__*`.
78impl std::fmt::Display for ToolPattern {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        match self {
81            Self::Name(n) => f.write_str(n),
82            Self::Prefix(p) => write!(f, "{p}*"),
83            Self::McpServer(s) => write!(f, "mcp__{s}__*"),
84            Self::AnyMcp => f.write_str("mcp__*"),
85        }
86    }
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
90struct Layer {
91    allow: Option<Vec<ToolPattern>>,
92    deny: Vec<ToolPattern>,
93}
94
95impl Layer {
96    fn admits(&self, name: &str, origin: &ToolOrigin) -> bool {
97        let hit = |patterns: &[ToolPattern]| patterns.iter().any(|p| p.matches(name, origin));
98        !hit(&self.deny) && self.allow.as_deref().is_none_or(hit)
99    }
100
101    fn within(&self, parent: &Layer) -> bool {
102        let allowed_within = match (&self.allow, &parent.allow) {
103            (_, None) => true,
104            (None, Some(_)) => false,
105            (Some(mine), Some(theirs)) => mine.iter().all(|m| theirs.iter().any(|t| t.covers(m))),
106        };
107        let denied_within = parent.deny.iter().all(|d| {
108            self.deny.iter().any(|mine| mine.covers(d))
109                || self
110                    .allow
111                    .as_ref()
112                    .is_some_and(|mine| mine.iter().all(|m| m.disjoint(d)))
113        });
114        allowed_within && denied_within
115    }
116}
117
118/// Layers of allow and deny lists; a tool is admitted when every layer
119/// admits it. No layers admits every tool.
120#[derive(Debug, Clone, Default, PartialEq, Eq)]
121pub struct ToolSelector {
122    layers: Vec<Layer>,
123}
124
125impl ToolSelector {
126    pub fn all() -> Self {
127        Self::default()
128    }
129
130    /// One layer. `allow: None` allows every tool the deny list leaves.
131    pub fn layer(allow: Option<Vec<ToolPattern>>, deny: Vec<ToolPattern>) -> Self {
132        Self {
133            layers: vec![Layer { allow, deny }],
134        }
135    }
136
137    /// One layer from lists as configured, an empty allow list allowing every
138    /// tool.
139    pub fn from_lists(allowed: &[String], disallowed: &[String]) -> Self {
140        let parsed = |list: &[String]| list.iter().map(|p| ToolPattern::parse(p)).collect();
141        if allowed.is_empty() && disallowed.is_empty() {
142            return Self::all();
143        }
144        Self::layer(
145            (!allowed.is_empty()).then(|| parsed(allowed)),
146            parsed(disallowed),
147        )
148    }
149
150    pub fn admits(&self, name: &str, origin: &ToolOrigin) -> bool {
151        self.layers.iter().all(|l| l.admits(name, origin))
152    }
153
154    /// Both selectors' layers: admits only what both admit.
155    pub fn and(mut self, other: ToolSelector) -> Self {
156        self.layers.extend(other.layers);
157        self
158    }
159
160    /// Whether everything this admits, `parent` admits too, as far as the
161    /// patterns alone can show; `false` when they cannot.
162    pub fn within(&self, parent: &ToolSelector) -> bool {
163        parent
164            .layers
165            .iter()
166            .all(|p| self.layers.iter().any(|mine| mine.within(p)))
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    fn lists(allowed: &[&str], disallowed: &[&str]) -> ToolSelector {
175        let owned = |l: &[&str]| l.iter().map(|s| s.to_string()).collect::<Vec<_>>();
176        ToolSelector::from_lists(&owned(allowed), &owned(disallowed))
177    }
178
179    fn builtin() -> ToolOrigin {
180        ToolOrigin::Builtin
181    }
182
183    #[test]
184    fn patterns_parse_by_their_shape() {
185        use ToolPattern::*;
186        assert_eq!(ToolPattern::parse("mcp__*"), AnyMcp);
187        assert_eq!(ToolPattern::parse("mcp__docs"), McpServer("docs".into()));
188        assert_eq!(
189            ToolPattern::parse("mcp__my.docs"),
190            McpServer("my.docs".into())
191        );
192        assert_eq!(ToolPattern::parse("mcp__docs__*"), McpServer("docs".into()));
193        assert_eq!(
194            ToolPattern::parse("mcp__docs__search"),
195            Name("mcp__docs__search".into())
196        );
197        assert_eq!(
198            ToolPattern::parse("mcp__docs__se*"),
199            Prefix("mcp__docs__se".into())
200        );
201        assert_eq!(ToolPattern::parse("Task*"), Prefix("Task".into()));
202        assert_eq!(ToolPattern::parse("Read"), Name("Read".into()));
203        assert_eq!(ToolPattern::parse("mcp__"), Name("mcp__".into()));
204    }
205
206    #[test]
207    fn a_pattern_displays_as_what_parses_back_to_it() {
208        for written in [
209            "mcp__*",
210            "mcp__docs",
211            "mcp__docs__*",
212            "mcp__a__b",
213            "Task*",
214            "Read",
215        ] {
216            let pattern = ToolPattern::parse(written);
217            assert_eq!(
218                ToolPattern::parse(&pattern.to_string()),
219                pattern,
220                "{written}"
221            );
222        }
223        assert_eq!(ToolPattern::parse("mcp__docs").to_string(), "mcp__docs__*");
224    }
225
226    #[test]
227    fn a_server_is_matched_on_the_origin_not_the_tool_name() {
228        let server = ToolPattern::parse("mcp__my.docs");
229        assert!(server.matches("mcp__my_docs__search", &ToolOrigin::mcp("my.docs")));
230        assert!(!server.matches("mcp__my_docs__search", &ToolOrigin::mcp("my_docs")));
231        assert!(!server.matches("mcp__my.docs__search", &builtin()));
232        let any = ToolPattern::AnyMcp;
233        assert!(any.matches("whatever", &ToolOrigin::mcp("s")));
234        assert!(!any.matches("mcp__s__t", &builtin()));
235        assert!(!any.matches("mcp__s__t", &ToolOrigin::plugin("p")));
236    }
237
238    #[test]
239    fn a_deny_holds_with_or_without_an_allow_list() {
240        let denies_bash = lists(&[], &["Bash"]);
241        assert!(denies_bash.admits("Read", &builtin()));
242        assert!(!denies_bash.admits("Bash", &builtin()));
243        let both = lists(&["Bash", "Read"], &["Bash"]);
244        assert!(both.admits("Read", &builtin()));
245        assert!(!both.admits("Bash", &builtin()));
246        assert!(!both.admits("Write", &builtin()));
247    }
248
249    #[test]
250    fn no_lists_admit_everything() {
251        assert!(ToolSelector::all().admits("Anything", &ToolOrigin::mcp("s")));
252        assert_eq!(lists(&[], &[]), ToolSelector::all());
253    }
254
255    #[test]
256    fn layers_only_narrow() {
257        let scene = lists(&["Read", "Grep", "Bash"], &[]);
258        let caller = lists(&[], &["Bash"]);
259        let both = scene.clone().and(caller);
260        assert!(both.admits("Read", &builtin()));
261        assert!(!both.admits("Bash", &builtin()));
262        assert!(!both.admits("Write", &builtin()));
263        assert!(!scene
264            .and(lists(&["Write"], &[]))
265            .admits("Write", &builtin()));
266    }
267
268    #[test]
269    fn a_narrower_list_is_within_a_wider_one() {
270        let parent = lists(&["Read", "Grep", "Bash"], &[]);
271        assert!(lists(&["Read", "Grep"], &[]).within(&parent));
272        assert!(!lists(&["Read", "Write"], &[]).within(&parent));
273        assert!(
274            !lists(&[], &[]).within(&parent),
275            "everything is not within a list"
276        );
277        assert!(lists(&[], &[]).within(&ToolSelector::all()));
278        assert!(lists(&["Read"], &[]).within(&ToolSelector::all()));
279    }
280
281    #[test]
282    fn within_a_deny_list_means_denying_it_or_never_allowing_it() {
283        let parent = lists(&[], &["Bash"]);
284        assert!(lists(&["Read"], &[]).within(&parent));
285        assert!(lists(&[], &["Bash", "Write"]).within(&parent));
286        assert!(!lists(&["Read", "Bash"], &[]).within(&parent));
287        assert!(!lists(&[], &[]).within(&parent));
288        assert!(lists(&[], &["B*"]).within(&parent));
289    }
290
291    #[test]
292    fn prefixes_and_servers_cover_what_they_name() {
293        assert!(lists(&["TaskStop"], &[]).within(&lists(&["Task*"], &[])));
294        assert!(lists(&["TaskS*"], &[]).within(&lists(&["Task*"], &[])));
295        assert!(!lists(&["Ta*"], &[]).within(&lists(&["Task*"], &[])));
296        assert!(lists(&["mcp__docs"], &[]).within(&lists(&["mcp__*"], &[])));
297        assert!(!lists(&["mcp__docs__search"], &[]).within(&lists(&["mcp__docs"], &[])));
298        assert!(lists(&["mcp__a"], &[]).within(&lists(&[], &["mcp__b"])));
299        assert!(!lists(&["Read"], &[]).within(&lists(&[], &["mcp__b"])));
300    }
301
302    #[test]
303    fn within_holds_layer_by_layer() {
304        let parent = lists(&["Read", "Bash"], &[]).and(lists(&[], &["Bash"]));
305        assert!(lists(&["Read"], &[]).within(&parent));
306        assert!(!lists(&["Bash"], &[]).within(&parent));
307        let child = lists(&["Read", "Bash"], &[]).and(lists(&[], &["Bash"]));
308        assert!(child.within(&parent));
309    }
310}