1use std::fmt;
4
5use regex::Regex;
6
7use super::mcp_tool::McpTool;
8
9crate::callback::callback! {
10 pub struct McpToolFilterCallback(Fn(&McpTool) -> bool);
13}
14
15#[derive(Clone)]
17#[non_exhaustive]
18pub enum McpToolMatcher {
19 Name(String),
21 Regex(Regex),
23 Callback(McpToolFilterCallback),
25}
26
27impl McpToolMatcher {
28 pub fn callback(callback: impl Fn(&McpTool) -> bool + Send + Sync + 'static) -> Self {
30 Self::Callback(McpToolFilterCallback::new(callback))
31 }
32
33 fn matches(&self, tool: &McpTool, server_tool_name: &str) -> bool {
34 match self {
35 Self::Name(name) => name == server_tool_name,
36 Self::Regex(regex) => regex.find(server_tool_name).is_some_and(|found| found.start() == 0),
37 Self::Callback(callback) => callback(tool),
38 }
39 }
40}
41
42impl From<&str> for McpToolMatcher {
43 fn from(name: &str) -> Self {
44 Self::Name(name.to_owned())
45 }
46}
47
48impl From<String> for McpToolMatcher {
49 fn from(name: String) -> Self {
50 Self::Name(name)
51 }
52}
53
54impl From<Regex> for McpToolMatcher {
55 fn from(regex: Regex) -> Self {
56 Self::Regex(regex)
57 }
58}
59
60impl fmt::Debug for McpToolMatcher {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 Self::Name(name) => f.debug_tuple("Name").field(name).finish(),
64 Self::Regex(regex) => f.debug_tuple("Regex").field(®ex.as_str()).finish(),
65 Self::Callback(_) => f.write_str("Callback"),
66 }
67 }
68}
69
70#[derive(Debug, Clone, Default, bon::Builder)]
74pub struct McpToolFilters {
75 pub allowed: Option<Vec<McpToolMatcher>>,
78 pub rejected: Option<Vec<McpToolMatcher>>,
80}
81
82impl McpToolFilters {
83 pub(crate) fn includes(&self, tool: &McpTool, server_tool_name: &str) -> bool {
85 let any = |matchers: &[McpToolMatcher]| matchers.iter().any(|matcher| matcher.matches(tool, server_tool_name));
86 if self.allowed.as_deref().is_some_and(|allowed| !any(allowed)) {
87 return false;
88 }
89 !self.rejected.as_deref().is_some_and(any)
90 }
91}