redisctl-mcp 0.4.0

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
//! redisctl-mcp: MCP server for Redis Cloud and Enterprise
//!
//! A standalone MCP server that exposes Redis management operations
//! as tools for AI systems.

use std::collections::HashSet;
use std::sync::Arc;

use anyhow::Result;
use clap::{Parser, ValueEnum};
use redisctl_core::Config;
#[cfg(any(feature = "cloud", feature = "enterprise", feature = "database"))]
use redisctl_core::DeploymentType;
use tower_mcp::{CapabilityFilter, DenialBehavior, McpRouter, Tool, transport::StdioTransport};
use tracing::info;
use tracing_subscriber::{EnvFilter, fmt, prelude::*};

mod error;
mod prompts;
mod resources;
mod state;
mod tools;

use state::{AppState, CredentialSource};

/// Transport mode for the MCP server
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
enum Transport {
    /// Standard input/output (for CLI integrations)
    #[default]
    Stdio,
    /// HTTP with Server-Sent Events (for shared deployments)
    Http,
}

/// Toolsets that can be enabled or disabled at runtime
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ValueEnum)]
enum Toolset {
    /// Redis Cloud management tools
    #[cfg(feature = "cloud")]
    Cloud,
    /// Redis Enterprise management tools
    #[cfg(feature = "enterprise")]
    Enterprise,
    /// Direct Redis database tools
    #[cfg(feature = "database")]
    Database,
    /// App-level tools: profile management, resources, and prompts
    App,
}

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

/// MCP server for Redis Cloud and Enterprise management
#[derive(Parser, Debug)]
#[command(name = "redisctl-mcp")]
#[command(version, about, long_about = None)]
struct Args {
    /// Transport mode
    #[arg(short, long, value_enum, default_value = "stdio")]
    transport: Transport,

    /// Profile name(s) for local credential resolution. Can be specified multiple times.
    #[arg(short, long, env = "REDISCTL_PROFILE")]
    profile: Vec<String>,

    /// Read-only mode (enabled by default; use --read-only=false to allow writes)
    #[arg(long, default_value = "true")]
    read_only: bool,

    /// Redis database URL for direct connections
    #[arg(long, env = "REDIS_URL")]
    database_url: Option<String>,

    /// Toolsets to enable (default: all compiled-in). Options: cloud, enterprise, database, app.
    #[arg(long, value_delimiter = ',', value_enum)]
    tools: Option<Vec<Toolset>>,

    // --- HTTP transport options ---
    /// Host to bind HTTP server
    #[arg(long, default_value = "127.0.0.1")]
    host: String,

    /// Port to bind HTTP server
    #[arg(long, default_value = "8080")]
    port: u16,

    // --- OAuth options (HTTP mode) ---
    /// Enable OAuth authentication for HTTP transport
    #[arg(long)]
    oauth: bool,

    /// OAuth issuer URL (e.g., https://accounts.google.com)
    #[arg(long, env = "OAUTH_ISSUER")]
    oauth_issuer: Option<String>,

    /// OAuth audience (client ID or API identifier)
    #[arg(long, env = "OAUTH_AUDIENCE")]
    oauth_audience: Option<String>,

    /// JWKS URI for token validation (auto-discovered from issuer if not set)
    #[arg(long, env = "OAUTH_JWKS_URI")]
    jwks_uri: Option<String>,

    // --- Rate limiting ---
    /// Maximum concurrent requests
    #[arg(long, default_value = "10")]
    max_concurrent: usize,

    /// Rate limit interval in milliseconds
    #[arg(long, default_value = "100")]
    rate_limit_ms: u64,

    /// Request timeout in seconds (HTTP mode)
    #[arg(long, default_value = "30")]
    request_timeout_secs: u64,

    // --- Logging ---
    /// Log level
    #[arg(long, default_value = "info", env = "RUST_LOG")]
    log_level: String,
}

/// Derive which toolsets to enable based on profile types in the config.
/// Returns `None` if config has no profiles (caller should fall back to all compiled-in).
fn toolsets_from_config(config: &Config) -> Option<HashSet<Toolset>> {
    if config.profiles.is_empty() {
        return None;
    }

    let mut set = HashSet::new();
    set.insert(Toolset::App); // always include profile management

    #[cfg(feature = "cloud")]
    if !config
        .get_profiles_of_type(DeploymentType::Cloud)
        .is_empty()
    {
        set.insert(Toolset::Cloud);
    }
    #[cfg(feature = "enterprise")]
    if !config
        .get_profiles_of_type(DeploymentType::Enterprise)
        .is_empty()
    {
        set.insert(Toolset::Enterprise);
    }
    #[cfg(feature = "database")]
    if !config
        .get_profiles_of_type(DeploymentType::Database)
        .is_empty()
    {
        set.insert(Toolset::Database);
    }

    Some(set)
}

/// Try to auto-detect toolsets from the config file on disk.
/// Returns `None` if config cannot be loaded or has no profiles.
fn detect_toolsets_from_config() -> Option<HashSet<Toolset>> {
    let config = Config::load().ok()?;
    let result = toolsets_from_config(&config);
    if let Some(ref toolsets) = result {
        let names: Vec<String> = toolsets.iter().map(|t| t.to_string()).collect();
        info!(toolsets = ?names, "Auto-detected toolsets from config profiles");
    }
    result
}

/// Resolve which toolsets are enabled based on CLI args, config profiles, and compiled features.
///
/// Priority: explicit `--tools` flag > config-based auto-detection > all compiled-in features.
fn enabled_toolsets(args: &Args) -> HashSet<Toolset> {
    // 1. Explicit --tools flag always wins
    if let Some(ref tools) = args.tools {
        return tools.iter().copied().collect();
    }

    // 2. Auto-detect from config profiles
    if let Some(toolsets) = detect_toolsets_from_config() {
        return toolsets;
    }

    // 3. Fallback: all compiled-in features
    let mut set = HashSet::new();
    #[cfg(feature = "cloud")]
    set.insert(Toolset::Cloud);
    #[cfg(feature = "enterprise")]
    set.insert(Toolset::Enterprise);
    #[cfg(feature = "database")]
    set.insert(Toolset::Database);
    set.insert(Toolset::App);
    set
}

#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();

    // Initialize tracing
    tracing_subscriber::registry()
        .with(fmt::layer().with_writer(std::io::stderr))
        .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| args.log_level.clone().into()))
        .init();

    let enabled = enabled_toolsets(&args);
    let enabled_names: Vec<String> = enabled.iter().map(|t| t.to_string()).collect();

    info!(
        transport = ?args.transport,
        profiles = ?args.profile,
        read_only = args.read_only,
        toolsets = ?enabled_names,
        "Starting redisctl-mcp server"
    );

    // Determine credential source
    let credential_source = if args.oauth {
        CredentialSource::OAuth {
            issuer: args.oauth_issuer.clone(),
            audience: args.oauth_audience.clone(),
        }
    } else {
        CredentialSource::Profiles(args.profile.clone())
    };

    // Build application state
    let state = Arc::new(AppState::new(
        credential_source,
        args.read_only,
        args.database_url.clone(),
    )?);

    // Build router with tools and optional read-only filter
    let router = build_router(state.clone(), args.read_only, &enabled)?;

    match args.transport {
        Transport::Stdio => {
            info!("Running with stdio transport");
            StdioTransport::new(router).run().await?;
        }
        Transport::Http => {
            info!(host = %args.host, port = args.port, "Running with HTTP transport");
            run_http_server(router, &args).await?;
        }
    }

    Ok(())
}

/// Build the MCP router with modular sub-routers based on enabled toolsets
fn build_router(
    state: Arc<AppState>,
    read_only: bool,
    enabled: &HashSet<Toolset>,
) -> Result<McpRouter> {
    let mut router = McpRouter::new().server_info("redisctl-mcp", env!("CARGO_PKG_VERSION"));

    // Conditionally merge each toolset
    #[cfg(feature = "cloud")]
    if enabled.contains(&Toolset::Cloud) {
        router = router.merge(tools::cloud::router(state.clone()));
    }

    #[cfg(feature = "enterprise")]
    if enabled.contains(&Toolset::Enterprise) {
        router = router.merge(tools::enterprise::router(state.clone()));
    }

    #[cfg(feature = "database")]
    if enabled.contains(&Toolset::Database) {
        router = router.merge(tools::redis::router(state.clone()));
    }

    // App toolset includes profile tools, resources, and prompts
    if enabled.contains(&Toolset::App) {
        router = router.merge(tools::profile::router(state.clone()));
    }

    // Build prefix: safety model + active safety tier
    let safety_tier = if read_only {
        "**Active safety tier: READ-ONLY** -- only read-only tools are available. \
         Write and destructive tools are hidden and will return unauthorized if called directly."
    } else {
        "**Active safety tier: WRITE-ENABLED** -- all tools including writes are available. \
         Destructive tools (delete, flush) are enabled. Exercise caution with destructive tools."
    };

    let prefix = format!(
        "# Redis Cloud and Enterprise MCP Server\n\n\
         ## Safety Model\n\n\
         Every tool carries MCP annotation hints that describe its safety characteristics:\n\
         - `readOnlyHint = true` -- reads data, never modifies state\n\
         - `destructiveHint = false` -- writes data but is non-destructive (create, update, backup)\n\
         - `destructiveHint = true` -- irreversible operation (delete, flush)\n\n\
         {safety_tier}\n",
    );

    let suffix = "\n## Authentication\n\n\
         In stdio mode, credentials are resolved from redisctl profiles.\n\
         In HTTP mode with OAuth, credentials can be passed via JWT claims.";

    router = router.auto_instructions_with(Some(prefix), Some(suffix));

    // Apply read-only filter if enabled
    // This hides write tools entirely from tools/list and returns "unauthorized"
    // if they're called directly, providing defense in depth beyond handler-level checks
    let router = if read_only {
        info!("Applying read-only filter - write tools will be hidden");
        router.tool_filter(
            CapabilityFilter::<Tool>::write_guard(|_session| false)
                .denial_behavior(DenialBehavior::Unauthorized),
        )
    } else {
        router
    };

    Ok(router)
}

/// Run the HTTP server with middleware
#[cfg(feature = "http")]
async fn run_http_server(router: McpRouter, args: &Args) -> Result<()> {
    use std::time::Duration;
    use tower::limit::ConcurrencyLimitLayer;
    use tower::timeout::TimeoutLayer;
    use tower_mcp::HttpTransport;

    let addr = format!("{}:{}", args.host, args.port);

    let transport = HttpTransport::new(router)
        .layer(TimeoutLayer::new(Duration::from_secs(
            args.request_timeout_secs,
        )))
        .layer(ConcurrencyLimitLayer::new(args.max_concurrent));

    if args.oauth {
        // OAuth-enabled HTTP transport
        let _issuer = args
            .oauth_issuer
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("--oauth-issuer required when OAuth is enabled"))?;

        info!(issuer = %_issuer, "OAuth authentication enabled");

        // TODO: Configure OAuth with ProtectedResourceMetadata
        // transport = transport.oauth(metadata);
    }

    transport.serve(&addr).await?;

    Ok(())
}

#[cfg(not(feature = "http"))]
async fn run_http_server(_router: McpRouter, _args: &Args) -> Result<()> {
    anyhow::bail!("HTTP transport requires the 'http' feature")
}

#[cfg(test)]
mod tests {
    use super::*;
    use redisctl_core::{Profile, ProfileCredentials};

    fn cloud_profile() -> Profile {
        Profile {
            deployment_type: DeploymentType::Cloud,
            credentials: ProfileCredentials::Cloud {
                api_key: "key".to_string(),
                api_secret: "secret".to_string(),
                api_url: "https://api.redislabs.com/v1".to_string(),
            },
            files_api_key: None,
            resilience: None,
            tags: vec![],
        }
    }

    fn enterprise_profile() -> Profile {
        Profile {
            deployment_type: DeploymentType::Enterprise,
            credentials: ProfileCredentials::Enterprise {
                url: "https://localhost:9443".to_string(),
                username: "admin".to_string(),
                password: Some("password".to_string()),
                insecure: false,
                ca_cert: None,
            },
            files_api_key: None,
            resilience: None,
            tags: vec![],
        }
    }

    fn database_profile() -> Profile {
        Profile {
            deployment_type: DeploymentType::Database,
            credentials: ProfileCredentials::Database {
                host: "localhost".to_string(),
                port: 6379,
                password: None,
                tls: false,
                username: "default".to_string(),
                database: 0,
            },
            files_api_key: None,
            resilience: None,
            tags: vec![],
        }
    }

    #[test]
    fn empty_config_returns_none() {
        let config = Config::default();
        assert!(toolsets_from_config(&config).is_none());
    }

    #[test]
    fn cloud_only_profiles() {
        let mut config = Config::default();
        config.set_profile("mycloud".to_string(), cloud_profile());

        let toolsets = toolsets_from_config(&config).unwrap();
        assert!(toolsets.contains(&Toolset::App));
        #[cfg(feature = "cloud")]
        assert!(toolsets.contains(&Toolset::Cloud));
        #[cfg(feature = "enterprise")]
        assert!(!toolsets.contains(&Toolset::Enterprise));
        #[cfg(feature = "database")]
        assert!(!toolsets.contains(&Toolset::Database));
    }

    #[test]
    fn enterprise_only_profiles() {
        let mut config = Config::default();
        config.set_profile("myent".to_string(), enterprise_profile());

        let toolsets = toolsets_from_config(&config).unwrap();
        assert!(toolsets.contains(&Toolset::App));
        #[cfg(feature = "cloud")]
        assert!(!toolsets.contains(&Toolset::Cloud));
        #[cfg(feature = "enterprise")]
        assert!(toolsets.contains(&Toolset::Enterprise));
        #[cfg(feature = "database")]
        assert!(!toolsets.contains(&Toolset::Database));
    }

    #[test]
    fn cloud_and_enterprise_profiles() {
        let mut config = Config::default();
        config.set_profile("mycloud".to_string(), cloud_profile());
        config.set_profile("myent".to_string(), enterprise_profile());

        let toolsets = toolsets_from_config(&config).unwrap();
        assert!(toolsets.contains(&Toolset::App));
        #[cfg(feature = "cloud")]
        assert!(toolsets.contains(&Toolset::Cloud));
        #[cfg(feature = "enterprise")]
        assert!(toolsets.contains(&Toolset::Enterprise));
        #[cfg(feature = "database")]
        assert!(!toolsets.contains(&Toolset::Database));
    }

    #[test]
    fn database_only_profiles() {
        let mut config = Config::default();
        config.set_profile("mydb".to_string(), database_profile());

        let toolsets = toolsets_from_config(&config).unwrap();
        assert!(toolsets.contains(&Toolset::App));
        #[cfg(feature = "cloud")]
        assert!(!toolsets.contains(&Toolset::Cloud));
        #[cfg(feature = "enterprise")]
        assert!(!toolsets.contains(&Toolset::Enterprise));
        #[cfg(feature = "database")]
        assert!(toolsets.contains(&Toolset::Database));
    }

    #[test]
    fn all_three_profile_types() {
        let mut config = Config::default();
        config.set_profile("mycloud".to_string(), cloud_profile());
        config.set_profile("myent".to_string(), enterprise_profile());
        config.set_profile("mydb".to_string(), database_profile());

        let toolsets = toolsets_from_config(&config).unwrap();
        assert!(toolsets.contains(&Toolset::App));
        #[cfg(feature = "cloud")]
        assert!(toolsets.contains(&Toolset::Cloud));
        #[cfg(feature = "enterprise")]
        assert!(toolsets.contains(&Toolset::Enterprise));
        #[cfg(feature = "database")]
        assert!(toolsets.contains(&Toolset::Database));
    }

    // ========================================================================
    // Safety annotation tests
    // ========================================================================

    /// Helper: assert a tool has read-only, idempotent, non-destructive annotations
    fn assert_read_only(tool: &Tool, name: &str) {
        let ann = tool
            .annotations
            .as_ref()
            .unwrap_or_else(|| panic!("{name}: missing annotations"));
        assert!(ann.read_only_hint, "{name}: should be read_only");
        assert!(ann.idempotent_hint, "{name}: should be idempotent");
        assert!(
            !ann.destructive_hint,
            "{name}: should be non-destructive (destructive_hint=false)"
        );
    }

    /// Helper: assert a tool is a non-destructive write (not read-only, destructive_hint=false)
    fn assert_non_destructive_write(tool: &Tool, name: &str) {
        let ann = tool
            .annotations
            .as_ref()
            .unwrap_or_else(|| panic!("{name}: missing annotations"));
        assert!(!ann.read_only_hint, "{name}: should NOT be read_only");
        assert!(
            !ann.destructive_hint,
            "{name}: should be non-destructive (destructive_hint=false)"
        );
    }

    /// Helper: assert a tool is destructive (explicit annotations with destructive_hint=true)
    fn assert_destructive(tool: &Tool, name: &str) {
        let ann = tool
            .annotations
            .as_ref()
            .unwrap_or_else(|| panic!("{name}: missing annotations"));
        assert!(
            ann.destructive_hint,
            "{name}: should be destructive (destructive_hint=true)"
        );
        assert!(
            !ann.read_only_hint,
            "{name}: destructive tool should NOT be read_only"
        );

        // Description should start with "DANGEROUS:"
        let desc = tool
            .description
            .as_deref()
            .unwrap_or_else(|| panic!("{name}: missing description"));
        assert!(
            desc.starts_with("DANGEROUS:"),
            "{name}: destructive tool description should start with 'DANGEROUS:', got: {desc}"
        );
    }

    fn test_state() -> Arc<AppState> {
        Arc::new(AppState::new(state::CredentialSource::Profiles(vec![]), true, None).unwrap())
    }

    // -- Profile tools --

    #[test]
    fn profile_read_tools_are_read_only() {
        let state = test_state();
        assert_read_only(
            &tools::profile::list_profiles(state.clone()),
            "profile_list",
        );
        assert_read_only(&tools::profile::show_profile(state.clone()), "profile_show");
        assert_read_only(&tools::profile::config_path(state.clone()), "profile_path");
        assert_read_only(
            &tools::profile::validate_config(state.clone()),
            "profile_validate",
        );
    }

    #[test]
    fn profile_write_tools_are_non_destructive() {
        let state = test_state();
        assert_non_destructive_write(
            &tools::profile::create_profile(state.clone()),
            "profile_create",
        );
        assert_non_destructive_write(
            &tools::profile::set_default_cloud(state.clone()),
            "profile_set_default_cloud",
        );
        assert_non_destructive_write(
            &tools::profile::set_default_enterprise(state.clone()),
            "profile_set_default_enterprise",
        );
    }

    #[test]
    fn profile_destructive_tools() {
        let state = test_state();
        assert_destructive(
            &tools::profile::delete_profile(state.clone()),
            "profile_delete",
        );
    }

    // -- Cloud tools (representative samples) --

    #[cfg(feature = "cloud")]
    mod cloud_annotations {
        use super::*;

        #[test]
        fn cloud_read_tools_are_read_only() {
            let state = test_state();
            assert_read_only(
                &tools::cloud::list_subscriptions(state.clone()),
                "list_subscriptions",
            );
            assert_read_only(&tools::cloud::get_account(state.clone()), "get_account");
            assert_read_only(
                &tools::cloud::list_fixed_subscriptions(state.clone()),
                "list_fixed_subscriptions",
            );
            assert_read_only(
                &tools::cloud::get_vpc_peering(state.clone()),
                "get_vpc_peering",
            );
        }

        #[test]
        fn cloud_write_tools_are_non_destructive() {
            let state = test_state();
            assert_non_destructive_write(
                &tools::cloud::create_database(state.clone()),
                "create_database",
            );
            assert_non_destructive_write(
                &tools::cloud::update_database(state.clone()),
                "update_database",
            );
            assert_non_destructive_write(
                &tools::cloud::backup_database(state.clone()),
                "backup_database",
            );
            assert_non_destructive_write(
                &tools::cloud::create_acl_user(state.clone()),
                "create_acl_user",
            );
            assert_non_destructive_write(
                &tools::cloud::create_vpc_peering(state.clone()),
                "create_vpc_peering",
            );
            assert_non_destructive_write(
                &tools::cloud::create_fixed_database(state.clone()),
                "create_fixed_database",
            );
        }

        #[test]
        fn cloud_destructive_tools() {
            let state = test_state();
            assert_destructive(
                &tools::cloud::delete_database(state.clone()),
                "delete_database",
            );
            assert_destructive(
                &tools::cloud::delete_subscription(state.clone()),
                "delete_subscription",
            );
            assert_destructive(
                &tools::cloud::flush_database(state.clone()),
                "flush_database",
            );
            assert_destructive(
                &tools::cloud::delete_acl_user(state.clone()),
                "delete_acl_user",
            );
            assert_destructive(
                &tools::cloud::delete_cloud_account(state.clone()),
                "delete_cloud_account",
            );
            assert_destructive(
                &tools::cloud::delete_vpc_peering(state.clone()),
                "delete_vpc_peering",
            );
            assert_destructive(
                &tools::cloud::delete_private_link(state.clone()),
                "delete_private_link",
            );
            assert_destructive(
                &tools::cloud::delete_fixed_database(state.clone()),
                "delete_fixed_database",
            );
            assert_destructive(
                &tools::cloud::delete_fixed_subscription(state.clone()),
                "delete_fixed_subscription",
            );
        }
    }

    // -- Enterprise tools (representative samples) --

    #[cfg(feature = "enterprise")]
    mod enterprise_annotations {
        use super::*;

        #[test]
        fn enterprise_read_tools_are_read_only() {
            let state = test_state();
            assert_read_only(
                &tools::enterprise::get_cluster(state.clone()),
                "get_cluster",
            );
            assert_read_only(
                &tools::enterprise::list_databases(state.clone()),
                "list_enterprise_databases",
            );
            assert_read_only(
                &tools::enterprise::list_users(state.clone()),
                "list_enterprise_users",
            );
            assert_read_only(
                &tools::enterprise::list_alerts(state.clone()),
                "list_alerts",
            );
        }

        #[test]
        fn enterprise_write_tools_are_non_destructive() {
            let state = test_state();
            assert_non_destructive_write(
                &tools::enterprise::update_cluster(state.clone()),
                "update_enterprise_cluster",
            );
            assert_non_destructive_write(
                &tools::enterprise::create_enterprise_database(state.clone()),
                "create_enterprise_database",
            );
            assert_non_destructive_write(
                &tools::enterprise::create_enterprise_user(state.clone()),
                "create_enterprise_user",
            );
        }

        #[test]
        fn enterprise_destructive_tools() {
            let state = test_state();
            assert_destructive(
                &tools::enterprise::delete_enterprise_database(state.clone()),
                "delete_enterprise_database",
            );
            assert_destructive(
                &tools::enterprise::flush_enterprise_database(state.clone()),
                "flush_enterprise_database",
            );
            assert_destructive(
                &tools::enterprise::delete_enterprise_user(state.clone()),
                "delete_enterprise_user",
            );
            assert_destructive(
                &tools::enterprise::delete_enterprise_role(state.clone()),
                "delete_enterprise_role",
            );
            assert_destructive(
                &tools::enterprise::delete_enterprise_acl(state.clone()),
                "delete_enterprise_acl",
            );
        }
    }

    // -- Redis database tools (representative samples) --

    #[cfg(feature = "database")]
    mod database_annotations {
        use super::*;

        #[test]
        fn redis_read_tools_are_read_only() {
            let state = test_state();
            assert_read_only(&tools::redis::ping(state.clone()), "redis_ping");
            assert_read_only(&tools::redis::info(state.clone()), "redis_info");
            assert_read_only(&tools::redis::keys(state.clone()), "redis_keys");
            assert_read_only(&tools::redis::get(state.clone()), "redis_get");
            assert_read_only(&tools::redis::hgetall(state.clone()), "redis_hgetall");
            assert_read_only(
                &tools::redis::health_check(state.clone()),
                "redis_health_check",
            );
        }

        #[test]
        fn redis_write_tools_are_non_destructive() {
            let state = test_state();
            assert_non_destructive_write(
                &tools::redis::config_set(state.clone()),
                "redis_config_set",
            );
            assert_non_destructive_write(&tools::redis::set(state.clone()), "redis_set");
            assert_non_destructive_write(&tools::redis::expire(state.clone()), "redis_expire");
            assert_non_destructive_write(&tools::redis::hset(state.clone()), "redis_hset");
            assert_non_destructive_write(&tools::redis::lpush(state.clone()), "redis_lpush");
            assert_non_destructive_write(&tools::redis::xadd(state.clone()), "redis_xadd");
        }

        #[test]
        fn redis_destructive_tools() {
            let state = test_state();
            assert_destructive(&tools::redis::flushdb(state.clone()), "redis_flushdb");
            assert_destructive(&tools::redis::del(state.clone()), "redis_del");
        }
    }

    #[test]
    fn instructions_contain_safety_model() {
        let state = test_state();
        let enabled: HashSet<Toolset> = [Toolset::App].into_iter().collect();

        let _router = build_router(state.clone(), true, &enabled).unwrap();
        // The router instructions are set but not publicly accessible.
        // Verify the build succeeds (no panics) for both modes.
        let _router_write = build_router(state.clone(), false, &enabled).unwrap();
    }
}