redisctl-mcp 0.10.1

MCP (Model Context Protocol) server for Redis Cloud and Enterprise
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
//! MCP server policy configuration for granular tool access control.
//!
//! Provides a TOML-based policy system with three safety tiers, per-toolset
//! overrides, and explicit allow/deny lists. Replaces the binary `--read-only`
//! flag with fine-grained control over which tools are available.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use tower_mcp::{CallToolResult, Error as McpError, Tool, ToolBuilder};

use crate::audit::AuditConfig;
use crate::presets::ToolsConfig;

/// Safety tier determining which categories of tools are allowed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SafetyTier {
    /// Only read-only tools (`read_only_hint = true`)
    #[default]
    ReadOnly,
    /// Reads + non-destructive writes (`destructive_hint = false`)
    ReadWrite,
    /// All operations including destructive
    Full,
}

impl fmt::Display for SafetyTier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SafetyTier::ReadOnly => write!(f, "read-only"),
            SafetyTier::ReadWrite => write!(f, "read-write"),
            SafetyTier::Full => write!(f, "full"),
        }
    }
}

/// Per-toolset policy override.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ToolsetPolicy {
    /// Whether this toolset is enabled. `None` or `Some(true)` = enabled,
    /// `Some(false)` = disabled (tools are never registered).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Safety tier for this toolset (overrides the global tier)
    pub tier: Option<SafetyTier>,
    /// Explicit tool names to allow (evaluated after tier)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allow: Vec<String>,
    /// Explicit tool names to deny (wins over allow and tier)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub deny: Vec<String>,
}

/// TOML-deserializable policy configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct PolicyConfig {
    /// Global default safety tier
    pub tier: SafetyTier,
    /// Deny entire categories globally (e.g., "destructive")
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub deny_categories: Vec<String>,
    /// Global explicit allow list (tool names)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allow: Vec<String>,
    /// Global explicit deny list (tool names, wins over allow)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub deny: Vec<String>,
    /// Cloud toolset overrides
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cloud: Option<ToolsetPolicy>,
    /// Enterprise toolset overrides
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enterprise: Option<ToolsetPolicy>,
    /// Database toolset overrides
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database: Option<ToolsetPolicy>,
    /// App/profile toolset overrides
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app: Option<ToolsetPolicy>,
    /// Audit logging configuration
    #[serde(default)]
    pub audit: AuditConfig,
    /// Tool visibility presets
    #[serde(default)]
    pub tools: ToolsConfig,
}

impl Default for PolicyConfig {
    fn default() -> Self {
        Self {
            tier: SafetyTier::ReadOnly,
            deny_categories: vec![],
            allow: vec![],
            deny: vec![],
            cloud: None,
            enterprise: None,
            database: None,
            app: None,
            audit: AuditConfig::default(),
            tools: ToolsConfig::default(),
        }
    }
}

/// Raw API passthrough tool names that are denied by default when no policy
/// file is loaded. Custom policy files use serde defaults (`deny = []`), so
/// raw tools become available through normal tier/allow mechanisms.
pub const RAW_TOOL_DENY_DEFAULTS: &[&str] =
    &["cloud_raw_api", "enterprise_raw_api", "redis_command"];

impl PolicyConfig {
    /// Return the set of toolsets explicitly disabled via `enabled = false`.
    pub fn disabled_toolsets(&self) -> HashSet<ToolsetKind> {
        let mut disabled = HashSet::new();
        for (kind, policy) in [
            (ToolsetKind::Cloud, &self.cloud),
            (ToolsetKind::Enterprise, &self.enterprise),
            (ToolsetKind::Database, &self.database),
            (ToolsetKind::App, &self.app),
        ] {
            if let Some(tp) = policy
                && tp.enabled == Some(false)
            {
                disabled.insert(kind);
            }
        }
        disabled
    }

    /// Build the synthesized default policy (used when no config file exists).
    /// This adds raw API passthrough tools to the deny list.
    pub fn synthesized_default() -> Self {
        Self {
            deny: RAW_TOOL_DENY_DEFAULTS
                .iter()
                .map(|s| (*s).to_string())
                .collect(),
            ..Default::default()
        }
    }

    /// Load policy with resolution chain:
    /// 1. Explicit path (from `--policy` CLI flag)
    /// 2. `REDISCTL_MCP_POLICY` env var
    /// 3. `~/.config/redisctl/mcp-policy.toml`
    /// 4. Built-in default (read-only)
    ///
    /// Returns `(config, source_description)`.
    pub fn load(explicit_path: Option<&Path>) -> Result<(Self, String)> {
        // 1. Explicit path
        if let Some(path) = explicit_path {
            let config = Self::load_from_path(path)?;
            return Ok((config, format!("file: {}", path.display())));
        }

        // 2. Environment variable
        if let Ok(env_path) = std::env::var("REDISCTL_MCP_POLICY") {
            let path = PathBuf::from(&env_path);
            if path.exists() {
                let config = Self::load_from_path(&path)?;
                return Ok((config, format!("env: {}", path.display())));
            }
            tracing::warn!(
                path = %path.display(),
                "REDISCTL_MCP_POLICY path does not exist, using defaults"
            );
        }

        // 3. Standard config location
        if let Some(path) = Self::default_path()
            && path.exists()
        {
            let config = Self::load_from_path(&path)?;
            return Ok((config, format!("file: {}", path.display())));
        }

        // 4. Built-in default (includes raw tool deny list)
        Ok((Self::synthesized_default(), "default".to_string()))
    }

    fn load_from_path(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read policy file: {}", path.display()))?;
        let config: PolicyConfig = toml::from_str(&content)
            .with_context(|| format!("Failed to parse policy file: {}", path.display()))?;
        tracing::info!(path = %path.display(), tier = %config.tier, "Loaded MCP policy");
        Ok(config)
    }

    /// Check if a policy file exists at the default path.
    pub fn default_path_exists() -> bool {
        Self::default_path().is_some_and(|p| p.exists())
    }

    /// Get the default policy file path following redisctl-core conventions.
    pub fn default_path() -> Option<PathBuf> {
        // On macOS, prefer Linux-style ~/.config/redisctl/ for cross-platform consistency
        // (matches redisctl-core Config::config_path())
        #[cfg(target_os = "macos")]
        {
            if let Some(base_dirs) = directories::BaseDirs::new() {
                let linux_style = base_dirs
                    .home_dir()
                    .join(".config")
                    .join("redisctl")
                    .join("mcp-policy.toml");
                if linux_style.exists() || linux_style.parent().is_some_and(|p| p.exists()) {
                    return Some(linux_style);
                }
            }
        }

        let proj_dirs = directories::ProjectDirs::from("com", "redis", "redisctl")?;
        Some(proj_dirs.config_dir().join("mcp-policy.toml"))
    }
}

/// Which toolset a tool belongs to (for per-toolset policy lookup).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ToolsetKind {
    Cloud,
    Enterprise,
    Database,
    App,
}

impl fmt::Display for ToolsetKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ToolsetKind::Cloud => write!(f, "cloud"),
            ToolsetKind::Enterprise => write!(f, "enterprise"),
            ToolsetKind::Database => write!(f, "database"),
            ToolsetKind::App => write!(f, "app"),
        }
    }
}

/// Resolved policy ready for tool evaluation.
///
/// Contains the raw config plus precomputed lookup sets for O(1) evaluation.
pub struct Policy {
    config: PolicyConfig,
    /// Maps tool name -> toolset for per-toolset override lookup
    tool_toolset: HashMap<String, ToolsetKind>,
    /// Precomputed global deny set
    global_deny: HashSet<String>,
    /// Precomputed global allow set
    global_allow: HashSet<String>,
    /// Precomputed per-toolset deny sets
    toolset_deny: HashMap<ToolsetKind, HashSet<String>>,
    /// Precomputed per-toolset allow sets
    toolset_allow: HashMap<ToolsetKind, HashSet<String>>,
    /// Whether "destructive" is in deny_categories
    deny_destructive: bool,
    /// Description of policy source (for instructions and show_policy)
    source: String,
}

impl fmt::Debug for Policy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Policy")
            .field("tier", &self.config.tier)
            .field("source", &self.source)
            .finish_non_exhaustive()
    }
}

impl Policy {
    /// Build a resolved policy from config and tool-to-toolset mapping.
    pub fn new(
        config: PolicyConfig,
        tool_toolset: HashMap<String, ToolsetKind>,
        source: String,
    ) -> Self {
        let global_deny: HashSet<String> = config.deny.iter().cloned().collect();
        let global_allow: HashSet<String> = config.allow.iter().cloned().collect();
        let deny_destructive = config.deny_categories.iter().any(|c| c == "destructive");

        let mut toolset_deny = HashMap::new();
        let mut toolset_allow = HashMap::new();

        for (kind, policy) in [
            (ToolsetKind::Cloud, &config.cloud),
            (ToolsetKind::Enterprise, &config.enterprise),
            (ToolsetKind::Database, &config.database),
            (ToolsetKind::App, &config.app),
        ] {
            if let Some(tp) = policy {
                toolset_deny.insert(kind, tp.deny.iter().cloned().collect());
                toolset_allow.insert(kind, tp.allow.iter().cloned().collect());
            }
        }

        Self {
            config,
            tool_toolset,
            global_deny,
            global_allow,
            toolset_deny,
            toolset_allow,
            deny_destructive,
            source,
        }
    }

    /// Determine if a tool is allowed by the policy.
    ///
    /// Evaluation order:
    /// 1. Global deny list -> DENY
    /// 2. Per-toolset deny list -> DENY
    /// 3. `deny_categories` (e.g., "destructive") -> DENY
    /// 4. Global allow list -> ALLOW
    /// 5. Per-toolset allow list -> ALLOW
    /// 6. Per-toolset tier (if set) -> evaluate against annotations
    /// 7. Global tier -> evaluate against annotations
    pub fn is_tool_allowed(&self, tool: &Tool) -> bool {
        let name = &tool.name;
        let annotations = tool.annotations.as_ref();
        let is_read_only = annotations.is_some_and(|a| a.read_only_hint);
        let is_destructive = annotations.is_some_and(|a| a.destructive_hint);

        // 1. Global deny always wins
        if self.global_deny.contains(name.as_str()) {
            return false;
        }

        // 2. Per-toolset deny
        let toolset = self.tool_toolset.get(name.as_str()).copied();
        if let Some(kind) = toolset
            && let Some(deny_set) = self.toolset_deny.get(&kind)
            && deny_set.contains(name.as_str())
        {
            return false;
        }

        // 3. Category deny
        if is_destructive && self.deny_destructive {
            return false;
        }

        // 4. Global allow overrides tier
        if self.global_allow.contains(name.as_str()) {
            return true;
        }

        // 5. Per-toolset allow overrides tier
        if let Some(kind) = toolset
            && let Some(allow_set) = self.toolset_allow.get(&kind)
            && allow_set.contains(name.as_str())
        {
            return true;
        }

        // 6 & 7. Effective tier (per-toolset overrides global)
        let effective_tier = toolset
            .and_then(|kind| self.toolset_config(kind).and_then(|tp| tp.tier))
            .unwrap_or(self.config.tier);

        Self::tier_allows(effective_tier, is_read_only, is_destructive)
    }

    /// Check if a tier allows a tool based on its annotations.
    fn tier_allows(tier: SafetyTier, is_read_only: bool, is_destructive: bool) -> bool {
        match tier {
            SafetyTier::ReadOnly => is_read_only,
            SafetyTier::ReadWrite => !is_destructive,
            SafetyTier::Full => true,
        }
    }

    fn toolset_config(&self, kind: ToolsetKind) -> Option<&ToolsetPolicy> {
        match kind {
            ToolsetKind::Cloud => self.config.cloud.as_ref(),
            ToolsetKind::Enterprise => self.config.enterprise.as_ref(),
            ToolsetKind::Database => self.config.database.as_ref(),
            ToolsetKind::App => self.config.app.as_ref(),
        }
    }

    /// Get the global safety tier.
    pub fn global_tier(&self) -> SafetyTier {
        self.config.tier
    }

    /// Generate a human-readable description for router instructions.
    pub fn describe(&self) -> String {
        let mut desc = String::new();

        desc.push_str(
            "Every tool carries MCP annotation hints that describe its safety characteristics:\n",
        );
        desc.push_str("- `readOnlyHint = true` -- reads data, never modifies state\n");
        desc.push_str("- `destructiveHint = false` -- writes data but is non-destructive (create, update, backup)\n");
        desc.push_str("- `destructiveHint = true` -- irreversible operation (delete, flush)\n\n");

        let tier_desc = match self.config.tier {
            SafetyTier::ReadOnly => {
                "**Active safety tier: READ-ONLY** -- only read-only tools are available. \
                 Write and destructive tools are hidden and will return unauthorized if called directly."
            }
            SafetyTier::ReadWrite => {
                "**Active safety tier: READ-WRITE** -- read-only and non-destructive write tools are available. \
                 Destructive tools (delete, flush) are hidden and will return unauthorized if called directly."
            }
            SafetyTier::Full => {
                "**Active safety tier: FULL** -- all tools including writes and destructive operations are available. \
                 Exercise caution with destructive tools."
            }
        };
        desc.push_str(tier_desc);

        // Note per-toolset overrides
        let overrides: Vec<String> = [
            ("cloud", self.config.cloud.as_ref()),
            ("enterprise", self.config.enterprise.as_ref()),
            ("database", self.config.database.as_ref()),
            ("app", self.config.app.as_ref()),
        ]
        .iter()
        .filter_map(|(name, tp)| tp.and_then(|p| p.tier).map(|t| format!("{}: {}", name, t)))
        .collect();

        if !overrides.is_empty() {
            desc.push_str(&format!(
                "\n\nPer-toolset overrides: {}",
                overrides.join(", ")
            ));
        }

        let disabled = self.config.disabled_toolsets();
        if !disabled.is_empty() {
            let mut names: Vec<String> = disabled.iter().map(|k| k.to_string()).collect();
            names.sort();
            desc.push_str(&format!(
                "\n\nDisabled toolsets (tools not registered): {}",
                names.join(", ")
            ));
        }

        if !self.config.deny.is_empty() {
            desc.push_str(&format!(
                "\n\nExplicitly denied tools: {}",
                self.config.deny.join(", ")
            ));
        }

        if self.deny_destructive {
            desc.push_str("\n\nAll destructive operations are denied by category.");
        }

        desc.push_str(
            "\n\nRaw API passthrough tools (`cloud_raw_api`, `enterprise_raw_api`, `redis_command`) \
             are available but denied by default. They can be enabled via a custom policy file.",
        );

        desc.push_str(
            "\n\nUse the `show_policy` tool to see the full active policy configuration.",
        );

        desc
    }

    /// Build a serializable summary of the policy for the show_policy tool.
    fn to_summary(&self) -> PolicySummary {
        PolicySummary {
            global_tier: self.config.tier.to_string(),
            deny_categories: self.config.deny_categories.clone(),
            global_allow: self.config.allow.clone(),
            global_deny: self.config.deny.clone(),
            cloud: self.config.cloud.as_ref().map(ToolsetPolicySummary::from),
            enterprise: self
                .config
                .enterprise
                .as_ref()
                .map(ToolsetPolicySummary::from),
            database: self
                .config
                .database
                .as_ref()
                .map(ToolsetPolicySummary::from),
            app: self.config.app.as_ref().map(ToolsetPolicySummary::from),
            source: self.source.clone(),
        }
    }
}

/// Serializable summary of the active policy.
#[derive(Debug, Serialize)]
pub struct PolicySummary {
    pub global_tier: String,
    pub deny_categories: Vec<String>,
    pub global_allow: Vec<String>,
    pub global_deny: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cloud: Option<ToolsetPolicySummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enterprise: Option<ToolsetPolicySummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database: Option<ToolsetPolicySummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app: Option<ToolsetPolicySummary>,
    pub source: String,
}

/// Serializable summary of a per-toolset policy.
#[derive(Debug, Serialize)]
pub struct ToolsetPolicySummary {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allow: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub deny: Vec<String>,
}

impl From<&ToolsetPolicy> for ToolsetPolicySummary {
    fn from(tp: &ToolsetPolicy) -> Self {
        Self {
            enabled: tp.enabled,
            tier: tp.tier.map(|t| t.to_string()),
            allow: tp.allow.clone(),
            deny: tp.deny.clone(),
        }
    }
}

/// Build the `show_policy` MCP tool.
pub fn show_policy_tool(policy: Arc<Policy>) -> Tool {
    ToolBuilder::new("show_policy")
        .description(
            "Show the active MCP server policy including safety tiers, \
             per-toolset overrides, and allow/deny lists. \
             Use this to understand what operations are permitted.",
        )
        .read_only_safe()
        .handler(move |_: tower_mcp::NoParams| {
            let policy = policy.clone();
            async move {
                let summary = policy.to_summary();
                CallToolResult::from_serialize(&summary)
                    .map_err(|e| McpError::tool(format!("Failed to serialize policy: {}", e)))
            }
        })
        .build()
}

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

    fn make_read_only_tool(name: &str) -> Tool {
        ToolBuilder::new(name)
            .description("Read-only test tool")
            .read_only_safe()
            .handler(|_: serde_json::Value| async { Ok(CallToolResult::text("ok")) })
            .build()
    }

    fn make_write_tool(name: &str) -> Tool {
        ToolBuilder::new(name)
            .description("Write test tool")
            .non_destructive()
            .handler(|_: serde_json::Value| async { Ok(CallToolResult::text("ok")) })
            .build()
    }

    fn make_destructive_tool(name: &str) -> Tool {
        ToolBuilder::new(name)
            .description("DANGEROUS: Destructive test tool")
            .destructive()
            .handler(|_: serde_json::Value| async { Ok(CallToolResult::text("ok")) })
            .build()
    }

    fn empty_mapping() -> HashMap<String, ToolsetKind> {
        HashMap::new()
    }

    fn policy_with_config(config: PolicyConfig) -> Policy {
        Policy::new(config, empty_mapping(), "test".to_string())
    }

    // -- Tier evaluation tests --

    #[test]
    fn default_policy_is_read_only() {
        let config = PolicyConfig::default();
        assert_eq!(config.tier, SafetyTier::ReadOnly);
    }

    #[test]
    fn read_only_allows_read_tools() {
        let policy = policy_with_config(PolicyConfig::default());
        let tool = make_read_only_tool("list_subscriptions");
        assert!(policy.is_tool_allowed(&tool));
    }

    #[test]
    fn read_only_blocks_write_tools() {
        let policy = policy_with_config(PolicyConfig::default());
        let tool = make_write_tool("create_database");
        assert!(!policy.is_tool_allowed(&tool));
    }

    #[test]
    fn read_only_blocks_destructive_tools() {
        let policy = policy_with_config(PolicyConfig::default());
        let tool = make_destructive_tool("delete_database");
        assert!(!policy.is_tool_allowed(&tool));
    }

    #[test]
    fn read_write_allows_non_destructive() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::ReadWrite,
            ..Default::default()
        });
        let read = make_read_only_tool("list_subscriptions");
        let write = make_write_tool("create_database");
        assert!(policy.is_tool_allowed(&read));
        assert!(policy.is_tool_allowed(&write));
    }

    #[test]
    fn read_write_blocks_destructive() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::ReadWrite,
            ..Default::default()
        });
        let tool = make_destructive_tool("delete_database");
        assert!(!policy.is_tool_allowed(&tool));
    }

    #[test]
    fn full_allows_everything() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::Full,
            ..Default::default()
        });
        let read = make_read_only_tool("list_subscriptions");
        let write = make_write_tool("create_database");
        let destructive = make_destructive_tool("delete_database");
        assert!(policy.is_tool_allowed(&read));
        assert!(policy.is_tool_allowed(&write));
        assert!(policy.is_tool_allowed(&destructive));
    }

    // -- Explicit deny/allow tests --

    #[test]
    fn explicit_deny_overrides_full_tier() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::Full,
            deny: vec!["delete_database".to_string()],
            ..Default::default()
        });
        let tool = make_destructive_tool("delete_database");
        assert!(!policy.is_tool_allowed(&tool));
    }

    #[test]
    fn explicit_allow_overrides_read_only_tier() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::ReadOnly,
            allow: vec!["create_database".to_string()],
            ..Default::default()
        });
        let tool = make_write_tool("create_database");
        assert!(policy.is_tool_allowed(&tool));
    }

    #[test]
    fn deny_wins_over_allow() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::Full,
            allow: vec!["delete_database".to_string()],
            deny: vec!["delete_database".to_string()],
            ..Default::default()
        });
        let tool = make_destructive_tool("delete_database");
        assert!(!policy.is_tool_allowed(&tool));
    }

    // -- Category deny tests --

    #[test]
    fn deny_category_destructive_blocks_all_destructive() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::Full,
            deny_categories: vec!["destructive".to_string()],
            ..Default::default()
        });
        let write = make_write_tool("create_database");
        let destructive = make_destructive_tool("delete_database");
        assert!(policy.is_tool_allowed(&write));
        assert!(!policy.is_tool_allowed(&destructive));
    }

    // -- Per-toolset override tests --

    #[test]
    fn per_toolset_tier_overrides_global() {
        let mut mapping = HashMap::new();
        mapping.insert("create_database".to_string(), ToolsetKind::Cloud);
        mapping.insert(
            "create_enterprise_database".to_string(),
            ToolsetKind::Enterprise,
        );

        let policy = Policy::new(
            PolicyConfig {
                tier: SafetyTier::ReadOnly,
                cloud: Some(ToolsetPolicy {
                    tier: Some(SafetyTier::ReadWrite),
                    ..Default::default()
                }),
                ..Default::default()
            },
            mapping,
            "test".to_string(),
        );

        let cloud_write = make_write_tool("create_database");
        let ent_write = make_write_tool("create_enterprise_database");

        assert!(policy.is_tool_allowed(&cloud_write)); // Cloud is read-write
        assert!(!policy.is_tool_allowed(&ent_write)); // Enterprise inherits read-only
    }

    #[test]
    fn per_toolset_deny_overrides_toolset_tier() {
        let mut mapping = HashMap::new();
        mapping.insert("flush_database".to_string(), ToolsetKind::Cloud);

        let policy = Policy::new(
            PolicyConfig {
                tier: SafetyTier::Full,
                cloud: Some(ToolsetPolicy {
                    tier: Some(SafetyTier::Full),
                    deny: vec!["flush_database".to_string()],
                    ..Default::default()
                }),
                ..Default::default()
            },
            mapping,
            "test".to_string(),
        );

        let tool = make_destructive_tool("flush_database");
        assert!(!policy.is_tool_allowed(&tool));
    }

    #[test]
    fn per_toolset_allow_overrides_global_tier() {
        let mut mapping = HashMap::new();
        mapping.insert("redis_set".to_string(), ToolsetKind::Database);

        let policy = Policy::new(
            PolicyConfig {
                tier: SafetyTier::ReadOnly,
                database: Some(ToolsetPolicy {
                    tier: None, // inherits global read-only
                    allow: vec!["redis_set".to_string()],
                    ..Default::default()
                }),
                ..Default::default()
            },
            mapping,
            "test".to_string(),
        );

        let tool = make_write_tool("redis_set");
        assert!(policy.is_tool_allowed(&tool));
    }

    // -- TOML parsing tests --

    #[test]
    fn toml_roundtrip() {
        let config = PolicyConfig {
            tier: SafetyTier::ReadWrite,
            deny_categories: vec!["destructive".to_string()],
            allow: vec!["backup_database".to_string()],
            deny: vec!["flush_database".to_string()],
            cloud: Some(ToolsetPolicy {
                tier: Some(SafetyTier::Full),
                ..Default::default()
            }),
            enterprise: None,
            database: Some(ToolsetPolicy {
                tier: Some(SafetyTier::ReadOnly),
                allow: vec!["redis_set".to_string()],
                ..Default::default()
            }),
            app: None,
            audit: AuditConfig::default(),
            tools: ToolsConfig::default(),
        };

        let toml_str = toml::to_string_pretty(&config).unwrap();
        let parsed: PolicyConfig = toml::from_str(&toml_str).unwrap();

        assert_eq!(parsed.tier, SafetyTier::ReadWrite);
        assert_eq!(parsed.deny_categories, vec!["destructive"]);
        assert_eq!(parsed.allow, vec!["backup_database"]);
        assert_eq!(parsed.deny, vec!["flush_database"]);
        assert_eq!(parsed.cloud.unwrap().tier, Some(SafetyTier::Full));
        assert!(parsed.enterprise.is_none());
        let db = parsed.database.unwrap();
        assert_eq!(db.tier, Some(SafetyTier::ReadOnly));
        assert_eq!(db.allow, vec!["redis_set"]);
    }

    #[test]
    fn toml_minimal_config() {
        let config: PolicyConfig = toml::from_str("tier = \"full\"").unwrap();
        assert_eq!(config.tier, SafetyTier::Full);
        assert!(config.deny.is_empty());
        assert!(config.allow.is_empty());
        assert!(config.cloud.is_none());
    }

    #[test]
    fn toml_empty_is_read_only() {
        let config: PolicyConfig = toml::from_str("").unwrap();
        assert_eq!(config.tier, SafetyTier::ReadOnly);
    }

    #[test]
    fn toml_complex_config() {
        let toml_str = r#"
tier = "read-only"
deny_categories = ["destructive"]
deny = ["flush_database", "delete_subscription"]

[cloud]
tier = "read-write"

[enterprise]
tier = "read-only"

[database]
tier = "read-only"
allow = ["redis_set", "redis_expire"]
"#;
        let config: PolicyConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.tier, SafetyTier::ReadOnly);
        assert_eq!(config.deny_categories, vec!["destructive"]);
        assert_eq!(config.deny, vec!["flush_database", "delete_subscription"]);
        assert_eq!(
            config.cloud.as_ref().unwrap().tier,
            Some(SafetyTier::ReadWrite)
        );
        assert_eq!(
            config.enterprise.as_ref().unwrap().tier,
            Some(SafetyTier::ReadOnly)
        );
        let db = config.database.as_ref().unwrap();
        assert_eq!(db.tier, Some(SafetyTier::ReadOnly));
        assert_eq!(db.allow, vec!["redis_set", "redis_expire"]);
    }

    // -- Backward compatibility tests --

    #[test]
    fn backward_compat_read_only_true() {
        // Synthesized policy from --read-only=true should match old behavior:
        // only read-only tools allowed
        let policy = policy_with_config(PolicyConfig::default());
        let read = make_read_only_tool("list_subscriptions");
        let write = make_write_tool("create_database");
        let destructive = make_destructive_tool("delete_database");

        assert!(policy.is_tool_allowed(&read));
        assert!(!policy.is_tool_allowed(&write));
        assert!(!policy.is_tool_allowed(&destructive));
    }

    #[test]
    fn backward_compat_read_only_false() {
        // Synthesized policy from --read-only=false should match old behavior:
        // all tools allowed
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::Full,
            ..Default::default()
        });
        let read = make_read_only_tool("list_subscriptions");
        let write = make_write_tool("create_database");
        let destructive = make_destructive_tool("delete_database");

        assert!(policy.is_tool_allowed(&read));
        assert!(policy.is_tool_allowed(&write));
        assert!(policy.is_tool_allowed(&destructive));
    }

    // -- Global tier accessor --

    #[test]
    fn global_tier_returns_config_tier() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::ReadWrite,
            ..Default::default()
        });
        assert_eq!(policy.global_tier(), SafetyTier::ReadWrite);
    }

    // -- Describe output --

    #[test]
    fn describe_contains_tier() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::ReadWrite,
            ..Default::default()
        });
        let desc = policy.describe();
        assert!(desc.contains("READ-WRITE"));
    }

    #[test]
    fn describe_notes_overrides() {
        let policy = policy_with_config(PolicyConfig {
            tier: SafetyTier::ReadOnly,
            cloud: Some(ToolsetPolicy {
                tier: Some(SafetyTier::ReadWrite),
                ..Default::default()
            }),
            ..Default::default()
        });
        let desc = policy.describe();
        assert!(desc.contains("cloud: read-write"));
    }

    // -- show_policy tool --

    #[test]
    fn show_policy_tool_is_read_only() {
        let policy = Arc::new(policy_with_config(PolicyConfig::default()));
        let tool = show_policy_tool(policy);
        let ann = tool.annotations.as_ref().unwrap();
        assert!(ann.read_only_hint);
        assert!(!ann.destructive_hint);
    }

    // -- Tools without annotations (edge case) --

    #[test]
    fn tool_without_annotations_treated_as_non_read_only() {
        let tool = ToolBuilder::new("unknown")
            .description("No annotations")
            .handler(|_: serde_json::Value| async { Ok(CallToolResult::text("ok")) })
            .build();

        let policy = policy_with_config(PolicyConfig::default()); // read-only
        // Tool has no read_only_hint=true, so it should be blocked at read-only tier
        assert!(!policy.is_tool_allowed(&tool));
    }

    // -- Raw tool default deny tests --

    #[test]
    fn synthesized_default_denies_raw_tools() {
        let config = PolicyConfig::synthesized_default();
        assert!(config.deny.contains(&"cloud_raw_api".to_string()));
        assert!(config.deny.contains(&"enterprise_raw_api".to_string()));
        assert!(config.deny.contains(&"redis_command".to_string()));

        let policy = policy_with_config(config);
        let cloud_raw = make_destructive_tool("cloud_raw_api");
        let enterprise_raw = make_destructive_tool("enterprise_raw_api");
        let redis_cmd = make_destructive_tool("redis_command");

        assert!(!policy.is_tool_allowed(&cloud_raw));
        assert!(!policy.is_tool_allowed(&enterprise_raw));
        assert!(!policy.is_tool_allowed(&redis_cmd));
    }

    #[test]
    fn synthesized_default_denies_raw_even_at_full_tier() {
        let mut config = PolicyConfig::synthesized_default();
        config.tier = SafetyTier::Full;
        let policy = policy_with_config(config);

        let cloud_raw = make_destructive_tool("cloud_raw_api");
        let enterprise_raw = make_destructive_tool("enterprise_raw_api");
        let redis_cmd = make_destructive_tool("redis_command");

        assert!(!policy.is_tool_allowed(&cloud_raw));
        assert!(!policy.is_tool_allowed(&enterprise_raw));
        assert!(!policy.is_tool_allowed(&redis_cmd));
    }

    #[test]
    fn custom_policy_file_does_not_auto_deny_raw_tools() {
        // A custom TOML policy with tier=full and empty deny list should allow raw tools
        let config: PolicyConfig = toml::from_str("tier = \"full\"").unwrap();
        assert!(config.deny.is_empty());

        let policy = policy_with_config(config);
        let cloud_raw = make_destructive_tool("cloud_raw_api");
        let enterprise_raw = make_destructive_tool("enterprise_raw_api");
        let redis_cmd = make_destructive_tool("redis_command");

        assert!(policy.is_tool_allowed(&cloud_raw));
        assert!(policy.is_tool_allowed(&enterprise_raw));
        assert!(policy.is_tool_allowed(&redis_cmd));
    }

    #[test]
    fn describe_mentions_raw_tools() {
        let policy = policy_with_config(PolicyConfig::synthesized_default());
        let desc = policy.describe();
        assert!(desc.contains("cloud_raw_api"));
        assert!(desc.contains("enterprise_raw_api"));
        assert!(desc.contains("redis_command"));
    }

    // -- [tools] section TOML tests --

    #[test]
    fn toml_no_tools_section_defaults_to_all() {
        let config: PolicyConfig = toml::from_str("tier = \"full\"").unwrap();
        assert!(config.tools.is_all());
        assert!(config.tools.include.is_empty());
        assert!(config.tools.exclude.is_empty());
    }

    #[test]
    fn toml_empty_tools_section_defaults_to_all() {
        let config: PolicyConfig = toml::from_str("[tools]\n").unwrap();
        assert!(config.tools.is_all());
    }

    #[test]
    fn toml_tools_with_preset() {
        let config: PolicyConfig = toml::from_str("[tools]\npreset = \"essentials\"\n").unwrap();
        assert_eq!(config.tools.preset, "essentials");
        assert!(!config.tools.is_all());
    }

    #[test]
    fn toml_tools_with_include_exclude() {
        let toml_str = r#"
tier = "read-only"

[tools]
preset = "essentials"
include = ["enterprise_raw_api", "get_enterprise_crdb"]
exclude = ["flush_database"]
"#;
        let config: PolicyConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.tools.preset, "essentials");
        assert_eq!(
            config.tools.include,
            vec!["enterprise_raw_api", "get_enterprise_crdb"]
        );
        assert_eq!(config.tools.exclude, vec!["flush_database"]);
        // Other fields still parse correctly
        assert_eq!(config.tier, SafetyTier::ReadOnly);
    }

    // -- Toolset enabled/disabled tests --

    #[test]
    fn toml_enabled_false_parses() {
        let toml_str = r#"
tier = "read-only"

[enterprise]
enabled = false

[database]
enabled = false
"#;
        let config: PolicyConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.enterprise.as_ref().unwrap().enabled, Some(false));
        assert_eq!(config.database.as_ref().unwrap().enabled, Some(false));
        // Cloud not mentioned: should be None
        assert!(config.cloud.is_none());
    }

    #[test]
    fn toml_enabled_true_parses() {
        let toml_str = r#"
[cloud]
enabled = true
tier = "read-write"
"#;
        let config: PolicyConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.cloud.as_ref().unwrap().enabled, Some(true));
    }

    #[test]
    fn toml_enabled_omitted_defaults_to_none() {
        let toml_str = r#"
[cloud]
tier = "read-write"
"#;
        let config: PolicyConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.cloud.as_ref().unwrap().enabled, None);
    }

    #[test]
    fn disabled_toolsets_returns_correct_set() {
        let config = PolicyConfig {
            enterprise: Some(ToolsetPolicy {
                enabled: Some(false),
                ..Default::default()
            }),
            database: Some(ToolsetPolicy {
                enabled: Some(false),
                ..Default::default()
            }),
            ..Default::default()
        };
        let disabled = config.disabled_toolsets();
        assert!(disabled.contains(&ToolsetKind::Enterprise));
        assert!(disabled.contains(&ToolsetKind::Database));
        assert!(!disabled.contains(&ToolsetKind::Cloud));
        assert!(!disabled.contains(&ToolsetKind::App));
    }

    #[test]
    fn disabled_toolsets_empty_when_all_enabled() {
        let config = PolicyConfig {
            cloud: Some(ToolsetPolicy {
                enabled: Some(true),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert!(config.disabled_toolsets().is_empty());
    }

    #[test]
    fn disabled_toolsets_empty_when_no_overrides() {
        let config = PolicyConfig::default();
        assert!(config.disabled_toolsets().is_empty());
    }

    #[test]
    fn describe_mentions_disabled_toolsets() {
        let policy = policy_with_config(PolicyConfig {
            enterprise: Some(ToolsetPolicy {
                enabled: Some(false),
                ..Default::default()
            }),
            ..Default::default()
        });
        let desc = policy.describe();
        assert!(desc.contains("Disabled toolsets"));
        assert!(desc.contains("enterprise"));
    }

    #[test]
    fn describe_omits_disabled_when_none() {
        let policy = policy_with_config(PolicyConfig::default());
        let desc = policy.describe();
        assert!(!desc.contains("Disabled toolsets"));
    }

    #[test]
    fn enabled_false_serializes_in_summary() {
        let tp = ToolsetPolicy {
            enabled: Some(false),
            tier: Some(SafetyTier::ReadOnly),
            ..Default::default()
        };
        let summary = ToolsetPolicySummary::from(&tp);
        assert_eq!(summary.enabled, Some(false));
        assert_eq!(summary.tier, Some("read-only".to_string()));
    }
}