Skip to main content

poly_mcp/
config.rs

1use serde::{Deserialize, Serialize};
2use std::path::Path;
3
4/// Runtime configuration for enabling/disabling modules and individual tools.
5///
6/// Tools are gated at two levels:
7/// 1. **Compile-time** - Cargo feature flags (e.g., `--no-default-features --features "filesystem,git"`)
8/// 2. **Runtime** - This config, via CLI flags or a JSON config file
9///
10/// A tool is available only if its module is both compiled in AND runtime-enabled.
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct ToolConfig {
13    /// Per-module enable/disable toggles
14    #[serde(default)]
15    pub modules: ModuleConfig,
16
17    /// Tool-level filtering (applied after module filtering)
18    #[serde(default)]
19    pub tools: ToolFilterConfig,
20}
21
22/// Per-module enable/disable toggles. All default to `true`.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct ModuleConfig {
25    #[serde(default = "yes")]
26    pub filesystem: bool,
27    #[serde(default = "yes")]
28    pub diagnostics: bool,
29    #[serde(default = "yes")]
30    pub silent: bool,
31    #[serde(default = "yes")]
32    pub time: bool,
33    #[serde(default = "yes")]
34    pub network: bool,
35    #[serde(default = "yes")]
36    pub context: bool,
37    #[serde(default = "yes")]
38    pub git: bool,
39    #[serde(default = "yes")]
40    pub input: bool,
41    #[serde(default = "yes")]
42    pub gitent: bool,
43    #[serde(default = "yes")]
44    pub clipboard: bool,
45    #[serde(default = "yes")]
46    pub transform: bool,
47    #[serde(default = "yes")]
48    pub screen: bool,
49    #[serde(default = "yes")]
50    pub browser: bool,
51}
52
53/// Tool-level whitelist/blacklist filtering.
54#[derive(Debug, Clone, Serialize, Deserialize, Default)]
55pub struct ToolFilterConfig {
56    /// Whitelist: if non-empty, ONLY these tools are available (takes precedence)
57    #[serde(default)]
58    pub enabled: Vec<String>,
59    /// Blacklist: these specific tools are disabled
60    #[serde(default)]
61    pub disabled: Vec<String>,
62}
63
64fn yes() -> bool {
65    true
66}
67
68impl Default for ToolConfig {
69    fn default() -> Self {
70        Self {
71            modules: ModuleConfig::default(),
72            tools: ToolFilterConfig::default(),
73        }
74    }
75}
76
77impl Default for ModuleConfig {
78    fn default() -> Self {
79        Self {
80            filesystem: true,
81            diagnostics: true,
82            silent: true,
83            time: true,
84            network: true,
85            context: true,
86            git: true,
87            input: true,
88            gitent: true,
89            clipboard: true,
90            transform: true,
91            screen: true,
92            browser: true,
93        }
94    }
95}
96
97impl ModuleConfig {
98    /// Create a config with all modules disabled.
99    pub fn all_disabled() -> Self {
100        Self {
101            filesystem: false,
102            diagnostics: false,
103            silent: false,
104            time: false,
105            network: false,
106            context: false,
107            git: false,
108            input: false,
109            gitent: false,
110            clipboard: false,
111            transform: false,
112            screen: false,
113            browser: false,
114        }
115    }
116
117    /// Set a module by name. Supports short aliases (fs, diag, net, ctx, clip).
118    pub fn set(&mut self, name: &str, enabled: bool) {
119        match name {
120            "filesystem" | "fs" => self.filesystem = enabled,
121            "diagnostics" | "diag" => self.diagnostics = enabled,
122            "silent" => self.silent = enabled,
123            "time" => self.time = enabled,
124            "network" | "net" => self.network = enabled,
125            "context" | "ctx" => self.context = enabled,
126            "git" => self.git = enabled,
127            "input" => self.input = enabled,
128            "gitent" => self.gitent = enabled,
129            "clipboard" | "clip" => self.clipboard = enabled,
130            "transform" => self.transform = enabled,
131            "screen" => self.screen = enabled,
132            "browser" => self.browser = enabled,
133            _ => eprintln!("Warning: unknown module '{}', ignoring", name),
134        }
135    }
136
137    /// Check if a module is enabled by name.
138    pub fn is_enabled(&self, name: &str) -> bool {
139        match name {
140            "filesystem" => self.filesystem,
141            "diagnostics" => self.diagnostics,
142            "silent" => self.silent,
143            "time" => self.time,
144            "network" => self.network,
145            "context" => self.context,
146            "git" => self.git,
147            "input" => self.input,
148            "gitent" => self.gitent,
149            "clipboard" => self.clipboard,
150            "transform" => self.transform,
151            "screen" => self.screen,
152            "browser" => self.browser,
153            _ => false,
154        }
155    }
156
157    /// List of all enabled module names.
158    #[allow(dead_code)]
159    pub fn enabled_list(&self) -> Vec<&'static str> {
160        let mut v = Vec::new();
161        if self.filesystem {
162            v.push("filesystem");
163        }
164        if self.diagnostics {
165            v.push("diagnostics");
166        }
167        if self.silent {
168            v.push("silent");
169        }
170        if self.time {
171            v.push("time");
172        }
173        if self.network {
174            v.push("network");
175        }
176        if self.context {
177            v.push("context");
178        }
179        if self.git {
180            v.push("git");
181        }
182        if self.input {
183            v.push("input");
184        }
185        if self.gitent {
186            v.push("gitent");
187        }
188        if self.clipboard {
189            v.push("clipboard");
190        }
191        if self.transform {
192            v.push("transform");
193        }
194        if self.screen {
195            v.push("screen");
196        }
197        if self.browser {
198            v.push("browser");
199        }
200        v
201    }
202}
203
204impl ToolConfig {
205    // ── Constructors ────────────────────────────────────────────────
206
207    /// Config with only the specified modules enabled (all others disabled).
208    ///
209    /// Accepts full names or aliases: `fs`, `diag`, `net`, `ctx`, `clip`.
210    ///
211    /// ```
212    /// use poly_mcp::ToolConfig;
213    /// let cfg = ToolConfig::only(&["fs", "git"]);
214    /// assert!(cfg.modules.filesystem);
215    /// assert!(cfg.modules.git);
216    /// assert!(!cfg.modules.network);
217    /// ```
218    pub fn only(modules: &[&str]) -> Self {
219        let mut config = Self {
220            modules: ModuleConfig::all_disabled(),
221            tools: ToolFilterConfig::default(),
222        };
223        for m in modules {
224            config.modules.set(m, true);
225        }
226        config
227    }
228
229    /// Config with all modules enabled except the specified ones.
230    ///
231    /// ```
232    /// use poly_mcp::ToolConfig;
233    /// let cfg = ToolConfig::without(&["silent", "input"]);
234    /// assert!(cfg.modules.filesystem);
235    /// assert!(!cfg.modules.silent);
236    /// ```
237    pub fn without(modules: &[&str]) -> Self {
238        let mut config = Self::default();
239        for m in modules {
240            config.modules.set(m, false);
241        }
242        config
243    }
244
245    // ── Chainable modifiers ─────────────────────────────────────────
246
247    /// Enable a module by name. Chainable.
248    pub fn enable_module(mut self, name: &str) -> Self {
249        self.modules.set(name, true);
250        self
251    }
252
253    /// Disable a module by name. Chainable.
254    pub fn disable_module(mut self, name: &str) -> Self {
255        self.modules.set(name, false);
256        self
257    }
258
259    /// Add a tool to the blacklist. Chainable.
260    ///
261    /// ```
262    /// use poly_mcp::ToolConfig;
263    /// let cfg = ToolConfig::only(&["fs", "git"])
264    ///     .disable_tool("fs_delete")
265    ///     .disable_tool("git_tag");
266    /// assert!(!cfg.is_tool_enabled("fs_delete"));
267    /// assert!(cfg.is_tool_enabled("fs_read"));
268    /// ```
269    pub fn disable_tool(mut self, name: impl Into<String>) -> Self {
270        let name = name.into();
271        if !self.tools.disabled.contains(&name) {
272            self.tools.disabled.push(name);
273        }
274        self
275    }
276
277    /// Set the tool whitelist: only these specific tools will be available
278    /// (from their respective enabled modules). Chainable.
279    ///
280    /// ```
281    /// use poly_mcp::ToolConfig;
282    /// let cfg = ToolConfig::default()
283    ///     .enable_only_tools(&["fs_read", "git_status"]);
284    /// assert!(cfg.is_tool_enabled("fs_read"));
285    /// assert!(!cfg.is_tool_enabled("fs_write"));
286    /// ```
287    pub fn enable_only_tools(mut self, names: &[&str]) -> Self {
288        self.tools.enabled = names.iter().map(|s| s.to_string()).collect();
289        self
290    }
291
292    // ── Loading ─────────────────────────────────────────────────────
293
294    /// Load config from a JSON file.
295    pub fn from_file(path: &Path) -> anyhow::Result<Self> {
296        let content = std::fs::read_to_string(path)?;
297        let config: Self = serde_json::from_str(&content)?;
298        Ok(config)
299    }
300
301    /// Apply CLI-style overrides on top of the current config.
302    ///
303    /// - `enable_modules`: comma-separated whitelist (disables all others)
304    /// - `disable_modules`: comma-separated blacklist
305    /// - `disable_tools`: comma-separated tool blacklist
306    pub fn apply_cli(
307        &mut self,
308        enable_modules: Option<&str>,
309        disable_modules: Option<&str>,
310        disable_tools: Option<&str>,
311    ) {
312        // Whitelist mode: disable all, then enable specified
313        if let Some(modules) = enable_modules {
314            self.modules = ModuleConfig::all_disabled();
315            for m in modules.split(',').map(str::trim).filter(|s| !s.is_empty()) {
316                self.modules.set(m, true);
317            }
318        }
319
320        // Blacklist mode
321        if let Some(modules) = disable_modules {
322            for m in modules.split(',').map(str::trim).filter(|s| !s.is_empty()) {
323                self.modules.set(m, false);
324            }
325        }
326
327        // Tool blacklist
328        if let Some(tools) = disable_tools {
329            for t in tools.split(',').map(str::trim).filter(|s| !s.is_empty()) {
330                if !self.tools.disabled.contains(&t.to_string()) {
331                    self.tools.disabled.push(t.to_string());
332                }
333            }
334        }
335    }
336
337    // ── Queries ─────────────────────────────────────────────────────
338
339    /// Check if a tool is available given both module and tool-level filters.
340    pub fn is_tool_enabled(&self, tool_name: &str) -> bool {
341        // Module-level check
342        let module = tool_module(tool_name);
343        if !self.modules.is_enabled(module) {
344            return false;
345        }
346
347        // Tool whitelist check
348        if !self.tools.enabled.is_empty()
349            && !self.tools.enabled.iter().any(|t| t == tool_name)
350        {
351            return false;
352        }
353
354        // Tool blacklist check
355        if self.tools.disabled.iter().any(|t| t == tool_name) {
356            return false;
357        }
358
359        true
360    }
361
362    /// Pretty-print the default config as JSON.
363    pub fn generate_default() -> String {
364        serde_json::to_string_pretty(&Self::default()).unwrap()
365    }
366}
367
368/// Check whether a module is compiled in (via Cargo feature flags).
369pub fn is_module_compiled(name: &str) -> bool {
370    match name {
371        "filesystem" => cfg!(feature = "filesystem"),
372        "diagnostics" => cfg!(feature = "diagnostics"),
373        "silent" => cfg!(feature = "silent"),
374        "time" => cfg!(feature = "time"),
375        "network" => cfg!(feature = "network"),
376        "context" => cfg!(feature = "context"),
377        "git" => cfg!(feature = "git"),
378        "input" => cfg!(feature = "input"),
379        "gitent" => cfg!(feature = "gitent"),
380        "clipboard" => cfg!(feature = "clipboard"),
381        "transform" => cfg!(feature = "transform"),
382        "screen" => cfg!(feature = "screen"),
383        "browser" => cfg!(feature = "browser"),
384        _ => false,
385    }
386}
387
388/// Map a tool name prefix to its module name.
389pub fn tool_module(name: &str) -> &str {
390    if name.starts_with("fs_") {
391        "filesystem"
392    } else if name.starts_with("diagnostics_") {
393        "diagnostics"
394    } else if name.starts_with("silent_") {
395        "silent"
396    } else if name.starts_with("time_") {
397        "time"
398    } else if name.starts_with("net_") {
399        "network"
400    } else if name.starts_with("ctx_") {
401        "context"
402    } else if name.starts_with("git_") {
403        "git"
404    } else if name.starts_with("input_") {
405        "input"
406    } else if name.starts_with("gitent_") {
407        "gitent"
408    } else if name.starts_with("clip_") {
409        "clipboard"
410    } else if name.starts_with("transform_") {
411        "transform"
412    } else if name.starts_with("screen_") {
413        "screen"
414    } else if name.starts_with("browser_") {
415        "browser"
416    } else {
417        "unknown"
418    }
419}
420
421/// All known module names (compile-time constant).
422#[allow(dead_code)]
423pub const ALL_MODULE_NAMES: &[&str] = &[
424    "filesystem",
425    "diagnostics",
426    "silent",
427    "time",
428    "network",
429    "context",
430    "git",
431    "input",
432    "gitent",
433    "clipboard",
434    "transform",
435    "screen",
436    "browser",
437];
438
439/// Module metadata for display.
440pub struct ModuleInfo {
441    pub name: &'static str,
442    pub description: &'static str,
443    pub tool_count: usize,
444    pub tools: &'static [&'static str],
445}
446
447/// Get metadata for all modules (regardless of compile/runtime state).
448pub fn all_module_info() -> Vec<ModuleInfo> {
449    vec![
450        ModuleInfo {
451            name: "filesystem",
452            description: "File and directory operations",
453            tool_count: 17,
454            tools: &[
455                "fs_read", "fs_write", "fs_move", "fs_copy", "fs_create", "fs_delete",
456                "fs_move_desktop", "fs_find", "fs_ld", "fs_stat", "fs_permissions",
457                "fs_watch", "fs_snapshot", "fs_tree", "fs_grep", "fs_tail", "fs_replace",
458            ],
459        },
460        ModuleInfo {
461            name: "diagnostics",
462            description: "Language-agnostic error detection",
463            tool_count: 1,
464            tools: &["diagnostics_get"],
465        },
466        ModuleInfo {
467            name: "silent",
468            description: "Bash scripting and resource monitoring",
469            tool_count: 2,
470            tools: &["silent_script", "silent_resources"],
471        },
472        ModuleInfo {
473            name: "time",
474            description: "Time management, scheduling & timekeeping",
475            tool_count: 7,
476            tools: &[
477                "time_now", "time_sleep", "time_schedule",
478                "time_timezone", "time_stopwatch", "time_timer", "time_alarm",
479            ],
480        },
481        ModuleInfo {
482            name: "network",
483            description: "HTTP requests and package queries",
484            tool_count: 6,
485            tools: &["net_fetch", "net_cargo", "net_node", "net_python", "net_apt", "net_ping"],
486        },
487        ModuleInfo {
488            name: "context",
489            description: "Token counting and cost estimation",
490            tool_count: 7,
491            tools: &[
492                "ctx_context", "ctx_compact", "ctx_remove", "ctx_token_count",
493                "ctx_memory_store", "ctx_memory_recall", "ctx_estimate_cost",
494            ],
495        },
496        ModuleInfo {
497            name: "git",
498            description: "Complete git operations",
499            tool_count: 8,
500            tools: &[
501                "git_status", "git_diff", "git_commit", "git_branch",
502                "git_checkout", "git_blame", "git_log", "git_tag",
503            ],
504        },
505        ModuleInfo {
506            name: "input",
507            description: "User interaction and notifications",
508            tool_count: 6,
509            tools: &[
510                "input_notify", "input_prompt", "input_select", "input_progress",
511                "input_clipboard_read", "input_clipboard_write",
512            ],
513        },
514        ModuleInfo {
515            name: "gitent",
516            description: "Agent-centric version control tracking",
517            tool_count: 7,
518            tools: &[
519                "gitent_init", "gitent_status", "gitent_track", "gitent_commit",
520                "gitent_log", "gitent_diff", "gitent_rollback",
521            ],
522        },
523        ModuleInfo {
524            name: "clipboard",
525            description: "Session copy/paste with tags",
526            tool_count: 5,
527            tools: &["clip_copy_file", "clip_copy", "clip_paste_file", "clip_paste", "clip_clear"],
528        },
529        ModuleInfo {
530            name: "transform",
531            description: "Text & data processing",
532            tool_count: 7,
533            tools: &[
534                "transform_diff", "transform_encode", "transform_hash", "transform_regex",
535                "transform_json", "transform_text", "transform_archive",
536            ],
537        },
538        ModuleInfo {
539            name: "screen",
540            description: "Screen capture, input simulation, window & element control",
541            tool_count: 18,
542            tools: &[
543                "screen_capture", "screen_click", "screen_type", "screen_key",
544                "screen_move", "screen_scroll", "screen_drag", "screen_info",
545                "screen_windows", "screen_focus", "screen_wait",
546                "screen_ocr", "screen_find", "screen_elements",
547                "screen_clipboard", "screen_pixel", "screen_diff", "screen_process",
548            ],
549        },
550        ModuleInfo {
551            name: "browser",
552            description: "Headless browser control via Chrome DevTools Protocol",
553            tool_count: 14,
554            tools: &[
555                "browser_launch", "browser_navigate", "browser_screenshot",
556                "browser_content", "browser_query", "browser_click",
557                "browser_fill", "browser_eval", "browser_tabs", "browser_close",
558                "browser_wait", "browser_scroll", "browser_hover", "browser_select",
559            ],
560        },
561    ]
562}