1use std::collections::HashSet;
9
10use crate::mcp::classify::{classify, Class, ToolMeta, ALL_GROUPS};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Profile {
14 All,
15 Read,
16 Safe,
17}
18
19impl Profile {
20 fn parse(s: &str) -> Option<Self> {
21 match s {
22 "all" => Some(Profile::All),
23 "read" => Some(Profile::Read),
24 "safe" => Some(Profile::Safe),
25 _ => None,
26 }
27 }
28
29 fn allows_class(self, class: Class) -> bool {
30 match (self, class) {
31 (Profile::All, _) => true,
32 (Profile::Read, Class::Read) => true,
33 (Profile::Read, _) => false,
34 (Profile::Safe, Class::Destructive) => false,
35 (Profile::Safe, _) => true,
36 }
37 }
38
39 pub fn as_str(self) -> &'static str {
40 match self {
41 Profile::All => "all",
42 Profile::Read => "read",
43 Profile::Safe => "safe",
44 }
45 }
46}
47
48#[derive(Debug, Default, Clone)]
50pub struct RawFilter {
51 pub profile: Option<String>,
52 pub read_only: bool,
53 pub groups: Option<Vec<String>>,
54 pub exclude_groups: Option<Vec<String>>,
55 pub tools: Option<Vec<String>>,
56 pub exclude_tools: Option<Vec<String>>,
57}
58
59#[derive(Debug)]
60pub enum FilterError {
61 UnknownProfile { name: String },
62 UnknownGroup { name: String, valid: Vec<&'static str> },
63 UnknownTool { name: String, suggestion: Option<String> },
64 ConflictingProfile { profile: String },
65 ToolExcludedByProfile { tool: String, profile: String },
66 EmptyFilter,
67}
68
69impl std::fmt::Display for FilterError {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 match self {
72 FilterError::UnknownProfile { name } => {
73 write!(f, "unknown --profile: {} (valid: all, read, safe)", name)
74 }
75 FilterError::UnknownGroup { name, valid } => {
76 write!(f, "unknown group: {} (valid: {})", name, valid.join(", "))
77 }
78 FilterError::UnknownTool { name, suggestion } => match suggestion {
79 Some(s) => write!(f, "unknown tool: {} (did you mean {}?)", name, s),
80 None => write!(f, "unknown tool: {}", name),
81 },
82 FilterError::ConflictingProfile { profile } => {
83 write!(f, "conflicting profile flags: --read-only and --profile {}", profile)
84 }
85 FilterError::ToolExcludedByProfile { tool, profile } => write!(
86 f,
87 "tool {} is excluded by profile={}; drop --profile or remove {} from --tools",
88 tool, profile, tool
89 ),
90 FilterError::EmptyFilter => {
91 write!(f, "filter pipeline produced an empty tool set; nothing to expose")
92 }
93 }
94 }
95}
96
97impl std::error::Error for FilterError {}
98
99#[derive(Debug)]
100pub struct Filter {
101 pub profile: Profile,
102 pub groups: Option<Vec<String>>,
103 pub exclude_groups: Option<Vec<String>>,
104 allowed: HashSet<String>,
105}
106
107impl Filter {
108 pub fn allows(&self, tool_name: &str) -> bool {
109 self.allowed.contains(tool_name)
110 }
111
112 pub fn allowed_count(&self) -> usize {
113 self.allowed.len()
114 }
115
116 pub fn resolve(raw: RawFilter) -> Result<Self, FilterError> {
117 let profile = match (raw.profile.as_deref(), raw.read_only) {
119 (None, false) => Profile::All,
120 (None, true) => Profile::Read,
121 (Some(p), false) => {
122 Profile::parse(p).ok_or_else(|| FilterError::UnknownProfile { name: p.into() })?
123 }
124 (Some("read"), true) => Profile::Read,
125 (Some(p), true) => return Err(FilterError::ConflictingProfile { profile: p.into() }),
126 };
127 let profile_label = profile.as_str();
128
129 for list in [&raw.groups, &raw.exclude_groups] {
131 if let Some(groups) = list {
132 for g in groups {
133 if !ALL_GROUPS.contains(&g.as_str()) {
134 return Err(FilterError::UnknownGroup {
135 name: g.clone(),
136 valid: ALL_GROUPS.to_vec(),
137 });
138 }
139 }
140 }
141 }
142
143 let all_names: Vec<(String, ToolMeta)> = crate::mcp::tool_list()
145 .as_array()
146 .expect("tool_list returns array")
147 .iter()
148 .filter_map(|t| {
149 t.get("name")
150 .and_then(|v| v.as_str())
151 .and_then(|n| classify(n).map(|m| (n.to_string(), m)))
152 })
153 .collect();
154 let known_names: HashSet<&str> =
155 all_names.iter().map(|(n, _)| n.as_str()).collect();
156
157 for list in [&raw.tools, &raw.exclude_tools] {
159 if let Some(tools) = list {
160 for t in tools {
161 if !known_names.contains(t.as_str()) {
162 return Err(FilterError::UnknownTool {
163 name: t.clone(),
164 suggestion: closest_name(t, &known_names),
165 });
166 }
167 }
168 }
169 }
170
171 if let Some(tools) = &raw.tools {
173 for t in tools {
174 if let Some(meta) = all_names.iter().find(|(n, _)| n == t).map(|(_, m)| m) {
175 if !profile.allows_class(meta.class) {
176 return Err(FilterError::ToolExcludedByProfile {
177 tool: t.clone(),
178 profile: profile_label.into(),
179 });
180 }
181 }
182 }
183 }
184
185 let mut allowed: HashSet<String> = all_names
187 .iter()
188 .filter(|(_, m)| profile.allows_class(m.class))
189 .map(|(n, _)| n.clone())
190 .collect();
191
192 if let Some(groups) = &raw.groups {
193 allowed.retain(|n| {
194 let g = all_names
195 .iter()
196 .find(|(name, _)| name == n)
197 .map(|(_, m)| m.group)
198 .unwrap_or("");
199 groups.iter().any(|wanted| wanted == g)
200 });
201 }
202
203 if let Some(excl) = &raw.exclude_groups {
204 allowed.retain(|n| {
205 let g = all_names
206 .iter()
207 .find(|(name, _)| name == n)
208 .map(|(_, m)| m.group)
209 .unwrap_or("");
210 !excl.iter().any(|bad| bad == g)
211 });
212 }
213
214 if let Some(tools) = &raw.tools {
215 let wanted: HashSet<&str> = tools.iter().map(String::as_str).collect();
216 allowed.retain(|n| wanted.contains(n.as_str()));
217 }
218
219 if let Some(excl) = &raw.exclude_tools {
220 for t in excl {
221 allowed.remove(t);
222 }
223 }
224
225 if allowed.is_empty() {
226 return Err(FilterError::EmptyFilter);
227 }
228
229 Ok(Filter {
230 profile,
231 groups: raw.groups,
232 exclude_groups: raw.exclude_groups,
233 allowed,
234 })
235 }
236}
237
238fn closest_name(needle: &str, haystack: &HashSet<&str>) -> Option<String> {
239 haystack
240 .iter()
241 .map(|c| (c, levenshtein(needle, c)))
242 .min_by_key(|&(_, d)| d)
243 .filter(|&(_, d)| d <= 3)
244 .map(|(s, _)| s.to_string())
245}
246
247fn levenshtein(a: &str, b: &str) -> usize {
248 let (a, b) = (a.as_bytes(), b.as_bytes());
249 let (n, m) = (a.len(), b.len());
250 if n == 0 {
251 return m;
252 }
253 if m == 0 {
254 return n;
255 }
256 let mut prev: Vec<usize> = (0..=m).collect();
257 let mut curr = vec![0usize; m + 1];
258 for i in 1..=n {
259 curr[0] = i;
260 for j in 1..=m {
261 let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
262 curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
263 }
264 std::mem::swap(&mut prev, &mut curr);
265 }
266 prev[m]
267}