mcp-rtk 1.1.0

Token-optimizing MCP proxy - sits between Claude and upstream MCP servers, compressing tool responses by 60-90%
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Configuration loading with preset auto-detection.
//!
//! mcp-rtk uses a layered configuration approach:
//!
//! 1. **Generic defaults** (`config/default.toml`) — sensible rules for any MCP.
//! 2. **Presets** (`config/presets/*.toml`) — community-contributed, tool-specific
//!    filter rules for known MCP servers. Auto-detected from the upstream command.
//! 3. **User config** (optional `--config`) — power-user overrides.
//!
//! All layers are merged: presets add tool rules on top of defaults, and user
//! config overrides everything.

use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;

/// Generic default filter rules (no tool-specific entries).
static DEFAULT_FILTERS: &str = include_str!("../config/default.toml");

/// Known presets, embedded at compile time.
static PRESETS: &[(&str, &[&str], &str)] = &[
    (
        "gitlab",
        &["gitlab-mcp", "gitlab"],
        include_str!("../config/presets/gitlab.toml"),
    ),
    (
        "grafana",
        &["mcp-grafana", "grafana"],
        include_str!("../config/presets/grafana.toml"),
    ),
    // To add a new preset:
    // ("github", &["github-mcp", "github"], include_str!("../config/presets/github.toml")),
];

/// Top-level configuration for mcp-rtk.
///
/// # Examples
///
/// ```no_run
/// # use mcp_rtk::config::Config;
/// # fn example() -> anyhow::Result<()> {
/// let config = Config::from_upstream(&["npx", "@nicepkg/gitlab-mcp"], None)?;
/// let rules = config.get_tool_rules("list_merge_requests");
/// assert!(!rules.keep_fields.is_empty());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Config {
    /// Upstream MCP server command and environment.
    pub upstream: UpstreamConfig,
    /// Filter rules (default + preset + user overrides).
    pub filters: FilterConfig,
    /// Token-savings tracking configuration.
    pub tracking: TrackingConfig,
    /// Name of the detected/selected preset, if any.
    pub preset: Option<String>,
}

/// How to spawn the upstream MCP server.
#[derive(Debug, Clone, Deserialize)]
pub struct UpstreamConfig {
    /// The executable to run (e.g. `"node"`).
    pub command: String,
    /// Arguments passed to the command.
    #[serde(default)]
    pub args: Vec<String>,
    /// Extra environment variables. Values starting with `$` are resolved from
    /// the current process environment.
    #[serde(default)]
    pub env: HashMap<String, String>,
}

/// Container for the default filter rules and per-tool overrides.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct FilterConfig {
    /// Rules applied to every tool unless overridden.
    #[serde(default)]
    pub default: ToolFilterRules,
    /// Per-tool overrides, keyed by MCP tool name.
    #[serde(default, alias = "tools")]
    pub tools: HashMap<String, ToolFilterRules>,
}

/// Declarative filter rules for a single tool (or the default).
///
/// All fields are optional so that tool-specific sections only need to
/// specify what they override.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ToolFilterRules {
    /// Whitelist of JSON field names to keep (applied first).
    #[serde(default)]
    pub keep_fields: Vec<String>,
    /// Blacklist of JSON field names to strip recursively.
    #[serde(default)]
    pub strip_fields: Vec<String>,
    /// Replace user objects (`{id, name, username, …}`) with just `"username"`.
    #[serde(default)]
    pub condense_users: Option<bool>,
    /// Maximum character length for any string value.
    #[serde(default)]
    pub truncate_strings_at: Option<usize>,
    /// Maximum number of items in any JSON array.
    #[serde(default)]
    pub max_array_items: Option<usize>,
    /// Remove all `null` and empty-string fields.
    #[serde(default)]
    pub strip_nulls: Option<bool>,
    /// Unwrap single-key wrapper objects (`{"data": [...]}` → `[...]`).
    #[serde(default)]
    pub flatten: Option<bool>,
    /// Regex-based string replacements applied last.
    #[serde(default)]
    pub custom_transforms: Vec<CustomTransform>,
}

/// A single regex-based string replacement.
#[derive(Debug, Clone, Deserialize)]
pub struct CustomTransform {
    /// The regex pattern to match.
    pub pattern: String,
    /// The replacement string (supports `$1`-style capture groups).
    pub replacement: String,
}

/// SQLite tracking configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct TrackingConfig {
    /// Whether to record per-call metrics.
    #[serde(default = "default_tracking_enabled")]
    pub enabled: bool,
    /// Path to the SQLite database. Supports `~/` expansion.
    #[serde(default = "default_db_path")]
    pub db_path: String,
}

impl Default for TrackingConfig {
    fn default() -> Self {
        Self {
            enabled: default_tracking_enabled(),
            db_path: default_db_path(),
        }
    }
}

fn default_tracking_enabled() -> bool {
    true
}

fn default_db_path() -> String {
    "~/.local/share/mcp-rtk/metrics.db".to_string()
}

/// Preset filter rules (no upstream section — just `[tools.*]`).
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct PresetConfig {
    #[serde(default)]
    pub(crate) tools: HashMap<String, ToolFilterRules>,
}

/// User-supplied configuration file. All sections are optional.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct UserConfig {
    /// Optional upstream override (env vars from config are merged).
    #[serde(default)]
    pub upstream: Option<UpstreamConfig>,
    #[serde(default)]
    pub(crate) filters: Option<FilterConfig>,
    #[serde(default)]
    tracking: Option<TrackingConfig>,
    /// Explicitly select a preset (overrides auto-detection).
    #[serde(default)]
    preset: Option<String>,
}

/// Simple glob matching: `*` matches any sequence of characters, `?` matches
/// exactly one character. No other special syntax is supported.
fn glob_match(pattern: &str, text: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let t: Vec<char> = text.chars().collect();
    let mut pi = 0;
    let mut ti = 0;
    let mut star_pi = usize::MAX;
    let mut star_ti = 0;

    while ti < t.len() {
        if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
            pi += 1;
            ti += 1;
        } else if pi < p.len() && p[pi] == '*' {
            star_pi = pi;
            star_ti = ti;
            pi += 1;
        } else if star_pi != usize::MAX {
            pi = star_pi + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }

    while pi < p.len() && p[pi] == '*' {
        pi += 1;
    }

    pi == p.len()
}

impl Config {
    /// Build configuration from upstream command args with optional user config.
    ///
    /// This is the primary entry point. The upstream command is taken from
    /// `upstream_args` (e.g. `["npx", "@nicepkg/gitlab-mcp"]`). A preset is
    /// auto-detected from the command, and an optional user config file
    /// provides overrides.
    ///
    /// # Errors
    ///
    /// Returns an error if the user config file cannot be read or parsed.
    pub fn from_upstream(upstream_args: &[&str], config_path: Option<&Path>) -> Result<Self> {
        let defaults = Self::load_defaults()?;

        // Build upstream from args
        let mut upstream = if let Some((cmd, args)) = upstream_args.split_first() {
            UpstreamConfig {
                command: cmd.to_string(),
                args: args.iter().map(|s| s.to_string()).collect(),
                env: HashMap::new(),
            }
        } else {
            anyhow::bail!("No upstream command provided. Usage: mcp-rtk -- <command> [args...]");
        };

        // Load user config if provided
        let user_config = if let Some(path) = config_path {
            let content = std::fs::read_to_string(path).context("Failed to read config file")?;
            Some(toml::from_str::<UserConfig>(&content).context("Failed to parse config file")?)
        } else {
            None
        };

        // Determine preset: user explicit > auto-detect from command
        let preset_name = user_config
            .as_ref()
            .and_then(|u| u.preset.clone())
            .or_else(|| Self::detect_preset(upstream_args));

        // Layer: defaults → preset → user config
        let mut filters = defaults;
        if let Some(ref name) = preset_name {
            if let Some(preset) = Self::load_preset(name) {
                for (k, v) in preset.tools {
                    filters.tools.insert(k, v);
                }
            }
        }

        let mut tracking = TrackingConfig::default();

        // Apply user overrides
        if let Some(user) = user_config {
            // Merge env vars from user config upstream (if any)
            if let Some(user_upstream) = user.upstream {
                for (k, v) in user_upstream.env {
                    upstream.env.insert(k, v);
                }
            }
            if let Some(user_filters) = user.filters {
                // User default rules merge on top
                filters.default = merge_tool_rules(&filters.default, &user_filters.default);
                // User tool rules override
                for (k, v) in user_filters.tools {
                    filters.tools.insert(k, v);
                }
            }
            if let Some(t) = user.tracking {
                tracking = t;
            }
        }

        // Resolve upstream env: inherit from parent process env
        let upstream = Self::resolve_env(upstream);

        Ok(Config {
            upstream,
            filters,
            tracking,
            preset: preset_name,
        })
    }

    /// Load configuration for the `gain` subcommand (no upstream needed).
    ///
    /// # Errors
    ///
    /// Returns an error if the user config file cannot be read or parsed.
    pub fn load_for_gain(config_path: Option<&Path>) -> Result<Self> {
        let defaults = Self::load_defaults()?;
        let mut tracking = TrackingConfig::default();

        if let Some(path) = config_path {
            let content = std::fs::read_to_string(path).context("Failed to read config file")?;
            let user: UserConfig =
                toml::from_str(&content).context("Failed to parse config file")?;
            if let Some(t) = user.tracking {
                tracking = t;
            }
        }

        Ok(Config {
            upstream: UpstreamConfig {
                command: String::new(),
                args: vec![],
                env: HashMap::new(),
            },
            filters: defaults,
            tracking,
            preset: None,
        })
    }

    /// Load the generic default filter rules.
    fn load_defaults() -> Result<FilterConfig> {
        toml::from_str(DEFAULT_FILTERS).context("Failed to parse built-in defaults")
    }

    /// Auto-detect a preset name from the upstream command args.
    ///
    /// Checks if any arg contains a known keyword (e.g. "gitlab-mcp" or "gitlab").
    fn detect_preset(args: &[&str]) -> Option<String> {
        let joined = args.join(" ").to_lowercase();
        for (name, keywords, _) in PRESETS {
            for keyword in *keywords {
                if joined.contains(keyword) {
                    return Some(name.to_string());
                }
            }
        }
        None
    }

    /// Load a preset's tool rules by name.
    ///
    /// Returns the tool-specific filter rules from the preset, or `None` if
    /// the preset name is unknown.
    pub fn load_preset_by_name(name: &str) -> Option<HashMap<String, ToolFilterRules>> {
        Self::load_preset(name).map(|p| p.tools)
    }

    /// Load a preset by name from the embedded presets.
    fn load_preset(name: &str) -> Option<PresetConfig> {
        for (preset_name, _, toml_content) in PRESETS {
            if *preset_name == name {
                return toml::from_str(toml_content).ok();
            }
        }
        None
    }

    /// Resolve env vars: values starting with `$` are read from the process env.
    ///
    /// Env vars from the parent process are also inherited automatically by the
    /// child process, so most env vars don't need to be in the config at all.
    ///
    /// # Security
    ///
    /// Only config values explicitly prefixed with `$` are resolved. The config
    /// file itself must be trusted — anyone who can write to it can control which
    /// env vars are forwarded and which command is spawned.
    fn resolve_env(mut upstream: UpstreamConfig) -> UpstreamConfig {
        let resolved: HashMap<String, String> = upstream
            .env
            .iter()
            .map(|(k, v)| {
                let resolved = if let Some(var_name) = v.strip_prefix('$') {
                    std::env::var(var_name).unwrap_or_default()
                } else {
                    v.clone()
                };
                (k.clone(), resolved)
            })
            .collect();
        upstream.env = resolved;
        upstream
    }

    /// Return the merged filter rules for a given tool name.
    ///
    /// Tool-specific rules override the defaults. Lists (`strip_fields`,
    /// `custom_transforms`) are concatenated; scalars use the tool value
    /// if present, otherwise the default.
    ///
    /// Lookup order:
    /// 1. Exact match by tool name (fast path).
    /// 2. Glob pattern match — keys containing `*` or `?` are tested against
    ///    the tool name using [`glob_match`].
    pub fn get_tool_rules(&self, tool_name: &str) -> MergedRules {
        let defaults = &self.filters.default;

        // Exact match first
        if let Some(specific) = self.filters.tools.get(tool_name) {
            return MergedRules::merge(defaults, Some(specific));
        }

        // Glob pattern match
        for (pattern, rules) in &self.filters.tools {
            if (pattern.contains('*') || pattern.contains('?')) && glob_match(pattern, tool_name) {
                return MergedRules::merge(defaults, Some(rules));
            }
        }

        MergedRules::merge(defaults, None)
    }

    /// List all available preset names.
    pub fn available_presets() -> Vec<&'static str> {
        PRESETS.iter().map(|(name, _, _)| *name).collect()
    }
}

/// Print a table of all available presets.
pub fn list_presets() {
    use crate::display::*;

    println!();
    println!("  {BOLD}{GREEN}MCP-RTK{RESET}{DIM} — Available Presets{RESET}");
    println!("  {DIM}{}{RESET}", "".repeat(56));
    println!();

    for (name, keywords, toml_content) in PRESETS {
        let tool_count = toml_content.matches("[tools.").count();
        println!(
            "  {BOLD}{WHITE}{:<12}{RESET}  {DIM}detected from:{RESET} {YELLOW}{}{RESET}  {DIM}({} tools){RESET}",
            name,
            keywords.join(", "),
            tool_count,
        );
    }

    println!();
    println!("  {DIM}Use `mcp-rtk presets show <name>` to see the full TOML.{RESET}");
    println!();
}

/// Print the full TOML content of a named preset.
pub fn show_preset(name: &str) -> Result<()> {
    use crate::display::*;

    for (preset_name, keywords, toml_content) in PRESETS {
        if *preset_name == name {
            println!();
            println!("  {BOLD}{GREEN}{}{RESET}{DIM} preset{RESET}", name);
            println!("  {DIM}Auto-detected from: {}{RESET}", keywords.join(", "));
            println!();
            // Print TOML content with light syntax highlighting
            for line in toml_content.lines() {
                if line.starts_with('#') {
                    println!("  {DIM}{line}{RESET}");
                } else if line.starts_with("[tools.") {
                    println!("  {BOLD}{CYAN}{line}{RESET}");
                } else if line.is_empty() {
                    println!();
                } else {
                    println!("  {line}");
                }
            }
            println!();
            return Ok(());
        }
    }

    anyhow::bail!(
        "Unknown preset: {name}\nAvailable: {}",
        PRESETS
            .iter()
            .map(|(n, _, _)| *n)
            .collect::<Vec<_>>()
            .join(", ")
    );
}

/// Merge two sets of tool filter rules (user on top of base).
fn merge_tool_rules(base: &ToolFilterRules, user: &ToolFilterRules) -> ToolFilterRules {
    ToolFilterRules {
        keep_fields: if user.keep_fields.is_empty() {
            base.keep_fields.clone()
        } else {
            user.keep_fields.clone()
        },
        strip_fields: {
            let mut fields = base.strip_fields.clone();
            fields.extend(user.strip_fields.clone());
            fields
        },
        condense_users: user.condense_users.or(base.condense_users),
        truncate_strings_at: user.truncate_strings_at.or(base.truncate_strings_at),
        max_array_items: user.max_array_items.or(base.max_array_items),
        strip_nulls: user.strip_nulls.or(base.strip_nulls),
        flatten: user.flatten.or(base.flatten),
        custom_transforms: {
            let mut t = base.custom_transforms.clone();
            t.extend(user.custom_transforms.clone());
            t
        },
    }
}

/// Fully resolved filter rules for a single tool call.
///
/// Produced by [`Config::get_tool_rules`] — the result of merging the default
/// rules with any tool-specific overrides.
#[derive(Debug, Clone)]
pub struct MergedRules {
    /// Whitelist of JSON field names to keep.
    pub keep_fields: Vec<String>,
    /// Blacklist of JSON field names to strip recursively.
    pub strip_fields: Vec<String>,
    /// Whether to condense user objects to bare usernames.
    pub condense_users: bool,
    /// Maximum character length for any string value.
    pub truncate_strings_at: usize,
    /// Maximum number of items in any JSON array.
    pub max_array_items: usize,
    /// Whether to remove null and empty-string fields.
    pub strip_nulls: bool,
    /// Whether to unwrap single-key wrapper objects.
    pub flatten: bool,
    /// Compiled regex-based string replacements.
    pub custom_transforms: Vec<CustomTransform>,
}

impl MergedRules {
    fn merge(defaults: &ToolFilterRules, specific: Option<&ToolFilterRules>) -> Self {
        let s = specific.cloned().unwrap_or_default();
        Self {
            keep_fields: if s.keep_fields.is_empty() {
                defaults.keep_fields.clone()
            } else {
                s.keep_fields
            },
            strip_fields: {
                let mut fields = defaults.strip_fields.clone();
                fields.extend(s.strip_fields);
                fields
            },
            condense_users: s
                .condense_users
                .or(defaults.condense_users)
                .unwrap_or(false),
            truncate_strings_at: s
                .truncate_strings_at
                .or(defaults.truncate_strings_at)
                .unwrap_or(usize::MAX),
            max_array_items: s
                .max_array_items
                .or(defaults.max_array_items)
                .unwrap_or(usize::MAX),
            strip_nulls: s.strip_nulls.or(defaults.strip_nulls).unwrap_or(false),
            flatten: s.flatten.or(defaults.flatten).unwrap_or(false),
            custom_transforms: {
                let mut t = defaults.custom_transforms.clone();
                t.extend(s.custom_transforms);
                t
            },
        }
    }
}

/// Validate a preset or user config TOML file and print a diagnostic report.
///
/// Parses the file as either a preset (`[tools.*]` format) or a full user
/// config (`[filters.*]` format). Reports the tools defined, active rules
/// per tool, and any warnings (conflicting options, invalid regex, etc.).
///
/// # Errors
///
/// Returns an error if the file cannot be read or is not valid TOML for
/// either format.
pub fn validate_preset_file(path: &Path) -> Result<()> {
    use crate::display::*;

    let content = std::fs::read_to_string(path)
        .context(format!("Failed to read file: {}", path.display()))?;

    // Try parsing as a preset (tools.* format)
    let preset_result = toml::from_str::<PresetConfig>(&content);
    // Try parsing as a full user config (filters.* format)
    let user_result = toml::from_str::<UserConfig>(&content);

    let (tools, is_preset) = match (preset_result, user_result) {
        (Ok(preset), _) => (preset.tools, true),
        (_, Ok(user)) => {
            let filters = user.filters.unwrap_or_default();
            (filters.tools, false)
        }
        (Err(e1), Err(_)) => {
            anyhow::bail!("Failed to parse TOML:\n{e1}");
        }
    };

    let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");

    println!();
    println!(
        "  {BOLD}{GREEN}{RESET} {BOLD}{file_name}{RESET} is valid {}",
        if is_preset { "preset" } else { "config" }
    );
    println!();

    // Stats
    println!("  {DIM}Tools defined:{RESET}  {BOLD}{}{RESET}", tools.len());

    // List tools with their active rules
    if !tools.is_empty() {
        println!();
        println!("  {DIM}Tool rules:{RESET}");
        for (name, rules) in &tools {
            let mut active = Vec::new();
            if !rules.keep_fields.is_empty() {
                active.push(format!("keep:{}", rules.keep_fields.len()));
            }
            if !rules.strip_fields.is_empty() {
                active.push(format!("strip:{}", rules.strip_fields.len()));
            }
            if rules.condense_users == Some(true) {
                active.push("condense_users".into());
            }
            if let Some(n) = rules.truncate_strings_at {
                active.push(format!("truncate:{n}"));
            }
            if let Some(n) = rules.max_array_items {
                active.push(format!("max_items:{n}"));
            }
            if rules.strip_nulls == Some(true) {
                active.push("strip_nulls".into());
            }
            if rules.flatten == Some(true) {
                active.push("flatten".into());
            }
            if !rules.custom_transforms.is_empty() {
                active.push(format!("transforms:{}", rules.custom_transforms.len()));
            }

            println!(
                "    {BOLD}{WHITE}{:<32}{RESET} {DIM}{}{RESET}",
                name,
                active.join(", ")
            );
        }
    }

    // Warnings
    let mut warnings = Vec::new();
    for (name, rules) in &tools {
        if !rules.keep_fields.is_empty() && !rules.strip_fields.is_empty() {
            warnings.push(format!(
                "{name}: has both keep_fields and strip_fields (keep_fields takes priority, strip_fields may be redundant)"
            ));
        }
        if rules.truncate_strings_at == Some(0) {
            warnings.push(format!(
                "{name}: truncate_strings_at is 0 (all strings will be empty)"
            ));
        }
        if rules.max_array_items == Some(0) {
            warnings.push(format!(
                "{name}: max_array_items is 0 (all arrays will be empty)"
            ));
        }
    }

    // Validate custom_transforms regex patterns
    for (name, rules) in &tools {
        for (i, transform) in rules.custom_transforms.iter().enumerate() {
            if regex::Regex::new(&transform.pattern).is_err() {
                warnings.push(format!(
                    "{name}: custom_transform[{i}] has invalid regex: {}",
                    transform.pattern
                ));
            }
        }
    }

    if !warnings.is_empty() {
        println!();
        println!("  {YELLOW}Warnings:{RESET}");
        for w in &warnings {
            println!("    {YELLOW}{RESET}  {w}");
        }
    }

    println!();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn load_defaults() {
        let filters = Config::load_defaults().unwrap();
        assert!(filters.default.strip_nulls.unwrap_or(false));
        assert!(filters.default.condense_users.unwrap_or(false));
        assert!(filters.default.flatten.unwrap_or(false));
    }

    #[test]
    fn detect_gitlab_preset() {
        assert_eq!(
            Config::detect_preset(&["npx", "@nicepkg/gitlab-mcp"]),
            Some("gitlab".to_string())
        );
        assert_eq!(
            Config::detect_preset(&["node", "/path/to/gitlab-mcp/build/index.js"]),
            Some("gitlab".to_string())
        );
    }

    #[test]
    fn detect_no_preset() {
        assert_eq!(
            Config::detect_preset(&["node", "/path/to/custom-server.js"]),
            None
        );
    }

    #[test]
    fn from_upstream_with_gitlab_preset() {
        let config = Config::from_upstream(&["npx", "@nicepkg/gitlab-mcp"], None).unwrap();
        assert_eq!(config.preset, Some("gitlab".to_string()));
        assert_eq!(config.upstream.command, "npx");
        assert_eq!(config.upstream.args, vec!["@nicepkg/gitlab-mcp"]);
        // GitLab preset should have tool-specific rules
        let rules = config.get_tool_rules("list_merge_requests");
        assert!(!rules.keep_fields.is_empty());
        assert!(rules.condense_users);
    }

    #[test]
    fn from_upstream_without_preset() {
        let config = Config::from_upstream(&["node", "my-custom-server.js"], None).unwrap();
        assert_eq!(config.preset, None);
        // Should still have generic defaults
        let rules = config.get_tool_rules("any_tool");
        assert!(rules.strip_nulls);
        assert!(rules.condense_users);
        assert!(rules.keep_fields.is_empty());
    }

    #[test]
    fn from_upstream_no_args_fails() {
        let result = Config::from_upstream(&[], None);
        assert!(result.is_err());
    }

    #[test]
    fn available_presets_includes_gitlab() {
        let presets = Config::available_presets();
        assert!(presets.contains(&"gitlab"));
    }

    #[test]
    fn get_tool_rules_merges_preset_and_defaults() {
        let config = Config::from_upstream(&["npx", "@nicepkg/gitlab-mcp"], None).unwrap();
        let rules = config.get_tool_rules("list_merge_requests");
        // From preset
        assert!(!rules.keep_fields.is_empty());
        // From defaults
        assert!(rules.strip_nulls);
        assert!(rules.strip_fields.contains(&"avatar_url".to_string()));
    }

    #[test]
    fn glob_match_star() {
        assert!(glob_match("list_*", "list_issues"));
        assert!(glob_match("list_*", "list_merge_requests"));
        assert!(!glob_match("list_*", "get_issue"));
        assert!(glob_match("*_requests", "list_merge_requests"));
        assert!(glob_match("*", "anything"));
    }

    #[test]
    fn glob_match_question() {
        assert!(glob_match("get_issue?", "get_issues"));
        assert!(!glob_match("get_issue?", "get_issue"));
        assert!(glob_match("get_?ssue", "get_issue"));
    }

    #[test]
    fn glob_match_exact() {
        assert!(glob_match("list_issues", "list_issues"));
        assert!(!glob_match("list_issues", "list_merge_requests"));
    }

    #[test]
    fn get_tool_rules_glob_pattern() {
        let mut config = Config::from_upstream(&["echo", "test-server"], None).unwrap();
        config.filters.tools.insert(
            "list_*".to_string(),
            ToolFilterRules {
                keep_fields: vec!["id".to_string(), "name".to_string()],
                max_array_items: Some(5),
                ..Default::default()
            },
        );

        let rules = config.get_tool_rules("list_something");
        assert_eq!(rules.keep_fields, vec!["id", "name"]);
        assert_eq!(rules.max_array_items, 5);
    }

    #[test]
    fn get_tool_rules_exact_match_takes_priority_over_glob() {
        let mut config = Config::from_upstream(&["echo", "test-server"], None).unwrap();
        config.filters.tools.insert(
            "list_*".to_string(),
            ToolFilterRules {
                keep_fields: vec!["id".to_string(), "name".to_string()],
                ..Default::default()
            },
        );
        config.filters.tools.insert(
            "list_special".to_string(),
            ToolFilterRules {
                keep_fields: vec!["special_field".to_string()],
                ..Default::default()
            },
        );

        let rules = config.get_tool_rules("list_special");
        assert_eq!(rules.keep_fields, vec!["special_field"]);
    }
}