-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
1747 lines (1556 loc) · 58.7 KB
/
Copy pathmain.rs
File metadata and controls
1747 lines (1556 loc) · 58.7 KB
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
//! 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::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{Result, bail};
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, DynamicPromptRegistry, McpRouter, PromptBuilder, Tool,
transport::StdioTransport,
};
use tracing::info;
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
mod audit;
mod error;
mod policy;
mod presets;
mod prompts;
mod resources;
mod serde_helpers;
mod state;
mod tools;
use audit::AuditLayer;
use policy::{Policy, PolicyConfig, SafetyTier, ToolsetKind};
use presets::{ToolVisibility, ToolsConfig};
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)]
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 Toolset {
/// Parse a toolset name string into a `Toolset` variant.
fn from_str(s: &str) -> Option<Self> {
match s {
#[cfg(feature = "cloud")]
"cloud" => Some(Toolset::Cloud),
#[cfg(feature = "enterprise")]
"enterprise" => Some(Toolset::Enterprise),
#[cfg(feature = "database")]
"database" => Some(Toolset::Database),
"app" => Some(Toolset::App),
_ => None,
}
}
/// All compiled-in toolset names (for error messages).
#[allow(clippy::vec_init_then_push)]
fn all_names() -> Vec<&'static str> {
let mut names = Vec::new();
#[cfg(feature = "cloud")]
names.push("cloud");
#[cfg(feature = "enterprise")]
names.push("enterprise");
#[cfg(feature = "database")]
names.push("database");
names.push("app");
names
}
}
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"),
}
}
}
/// Whether a toolset loads all sub-modules or a selected subset.
#[derive(Debug, Clone)]
enum SubModuleSelection {
/// Load all sub-modules in this toolset.
All,
/// Load only the named sub-modules.
Selected(HashSet<String>),
}
/// Resolved set of enabled toolsets with optional sub-module selection.
#[derive(Debug, Clone)]
struct EnabledToolsets {
selections: HashMap<Toolset, SubModuleSelection>,
}
impl EnabledToolsets {
/// Create an `EnabledToolsets` with all sub-modules for each given toolset.
fn all_of(toolsets: impl IntoIterator<Item = Toolset>) -> Self {
Self {
selections: toolsets
.into_iter()
.map(|t| (t, SubModuleSelection::All))
.collect(),
}
}
/// Check whether a toolset is enabled (with any selection).
#[allow(dead_code)]
fn contains(&self, toolset: &Toolset) -> bool {
self.selections.contains_key(toolset)
}
/// Get the sub-module selection for a toolset.
#[allow(dead_code)]
fn selection(&self, toolset: &Toolset) -> Option<&SubModuleSelection> {
self.selections.get(toolset)
}
/// Remove toolsets that match a predicate.
fn retain(&mut self, f: impl Fn(&Toolset) -> bool) {
self.selections.retain(|t, _| f(t));
}
/// Iterate over enabled toolsets.
fn iter(&self) -> impl Iterator<Item = &Toolset> {
self.selections.keys()
}
}
/// 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).
/// Ignored when a policy file is active.
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
read_only: bool,
/// Path to MCP policy file for granular tool access control.
/// Overrides --read-only when set.
#[arg(long, env = "REDISCTL_MCP_POLICY")]
policy: Option<PathBuf>,
/// Redis database URL for direct connections
#[arg(long, env = "REDIS_URL")]
database_url: Option<String>,
/// Enable Redis Cluster mode (handles MOVED/ASK redirections)
#[arg(long, env = "REDIS_CLUSTER")]
cluster: bool,
/// Client name for CLIENT SETNAME (identifies MCP connections in CLIENT LIST)
#[arg(long, env = "REDIS_CLIENT_NAME", default_value = "redisctl-mcp")]
client_name: Option<String>,
/// Toolsets to enable (default: all compiled-in).
/// Use bare names for all sub-modules: cloud,enterprise,database,app.
/// Use colon syntax for specific sub-modules: cloud:subscriptions,cloud:networking.
#[arg(long, value_delimiter = ',')]
tools: Option<Vec<String>>,
// --- 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,
/// Request timeout in seconds (HTTP mode)
#[arg(long, default_value = "30")]
request_timeout_secs: u64,
// --- Skills ---
/// Directory containing SKILL.md files to load as MCP prompts.
/// Each subdirectory should contain a SKILL.md with YAML frontmatter.
#[arg(long, env = "REDISCTL_MCP_SKILLS_DIR")]
skills_dir: Option<PathBuf>,
// --- Logging ---
/// Log level
#[arg(long, default_value = "info", env = "RUST_LOG")]
log_level: String,
}
/// Parse `--tools` specs like `["cloud:subscriptions", "cloud:networking", "enterprise", "app"]`
/// into an `EnabledToolsets`.
///
/// Rules:
/// - Bare name (e.g. `cloud`) selects all sub-modules for that toolset.
/// - Colon syntax (e.g. `cloud:subscriptions`) selects a single sub-module.
/// - If both bare and colon forms appear for the same toolset, bare wins (all sub-modules).
/// - `app` has no sub-modules; `app:anything` is an error.
fn parse_tool_specs(specs: &[String]) -> Result<EnabledToolsets> {
let mut selections: HashMap<Toolset, SubModuleSelection> = HashMap::new();
for spec in specs {
if let Some((toolset_name, sub_name)) = spec.split_once(':') {
let toolset = Toolset::from_str(toolset_name).ok_or_else(|| {
anyhow::anyhow!(
"Unknown toolset '{}'. Valid toolsets: {}",
toolset_name,
Toolset::all_names().join(", ")
)
})?;
// app has no sub-modules
if matches!(toolset, Toolset::App) {
bail!("'app' has no sub-modules (got 'app:{}')", sub_name);
}
// Validate sub-module name
if !is_valid_sub_module(&toolset, sub_name) {
bail!(
"Unknown sub-module '{}' for toolset '{}'. Valid sub-modules: {}",
sub_name,
toolset,
valid_sub_module_names(&toolset).join(", ")
);
}
match selections.get_mut(&toolset) {
Some(SubModuleSelection::All) => {
// Bare already seen, keep All
}
Some(SubModuleSelection::Selected(set)) => {
set.insert(sub_name.to_string());
}
None => {
let mut set = HashSet::new();
set.insert(sub_name.to_string());
selections.insert(toolset, SubModuleSelection::Selected(set));
}
}
} else {
let toolset = Toolset::from_str(spec).ok_or_else(|| {
anyhow::anyhow!(
"Unknown toolset '{}'. Valid toolsets: {}",
spec,
Toolset::all_names().join(", ")
)
})?;
// Bare name: select all sub-modules (overrides any previous selective)
selections.insert(toolset, SubModuleSelection::All);
}
}
Ok(EnabledToolsets { selections })
}
/// Check whether a sub-module name is valid for a given toolset.
#[allow(unused_variables)]
fn is_valid_sub_module(toolset: &Toolset, name: &str) -> bool {
match toolset {
#[cfg(feature = "cloud")]
Toolset::Cloud => tools::cloud::sub_tool_names(name).is_some(),
#[cfg(feature = "enterprise")]
Toolset::Enterprise => tools::enterprise::sub_tool_names(name).is_some(),
#[cfg(feature = "database")]
Toolset::Database => tools::redis::sub_tool_names(name).is_some(),
Toolset::App => false,
}
}
/// Return valid sub-module names for a toolset (for error messages).
fn valid_sub_module_names(toolset: &Toolset) -> Vec<&'static str> {
match toolset {
#[cfg(feature = "cloud")]
Toolset::Cloud => tools::cloud::SUB_MODULES.iter().map(|sm| sm.name).collect(),
#[cfg(feature = "enterprise")]
Toolset::Enterprise => tools::enterprise::SUB_MODULES
.iter()
.map(|sm| sm.name)
.collect(),
#[cfg(feature = "database")]
Toolset::Database => tools::redis::SUB_MODULES.iter().map(|sm| sm.name).collect(),
Toolset::App => vec![],
}
}
/// Get tool names for a toolset according to its sub-module selection.
fn selected_tool_names(toolset: &Toolset, selection: &SubModuleSelection) -> Vec<String> {
match selection {
SubModuleSelection::All => match toolset {
#[cfg(feature = "cloud")]
Toolset::Cloud => tools::cloud::tool_names(),
#[cfg(feature = "enterprise")]
Toolset::Enterprise => tools::enterprise::tool_names(),
#[cfg(feature = "database")]
Toolset::Database => tools::redis::tool_names(),
Toolset::App => tools::profile::tool_names(),
},
SubModuleSelection::Selected(sub_modules) => {
let mut names = Vec::new();
for _sub in sub_modules {
let sub_names: Option<&[&str]> = match toolset {
#[cfg(feature = "cloud")]
Toolset::Cloud => tools::cloud::sub_tool_names(_sub),
#[cfg(feature = "enterprise")]
Toolset::Enterprise => tools::enterprise::sub_tool_names(_sub),
#[cfg(feature = "database")]
Toolset::Database => tools::redis::sub_tool_names(_sub),
Toolset::App => None,
};
if let Some(tool_names) = sub_names {
names.extend(tool_names.iter().map(|s| (*s).to_string()));
}
}
names
}
}
}
/// 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<EnabledToolsets> {
if config.profiles.is_empty() {
return None;
}
#[allow(unused_mut)]
let mut toolsets = vec![Toolset::App];
#[cfg(feature = "cloud")]
if !config
.get_profiles_of_type(DeploymentType::Cloud)
.is_empty()
{
toolsets.push(Toolset::Cloud);
}
#[cfg(feature = "enterprise")]
if !config
.get_profiles_of_type(DeploymentType::Enterprise)
.is_empty()
{
toolsets.push(Toolset::Enterprise);
}
#[cfg(feature = "database")]
if !config
.get_profiles_of_type(DeploymentType::Database)
.is_empty()
{
toolsets.push(Toolset::Database);
}
Some(EnabledToolsets::all_of(toolsets))
}
/// 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<EnabledToolsets> {
let config = Config::load().ok()?;
let result = toolsets_from_config(&config);
if let Some(ref enabled) = result {
let names: Vec<String> = enabled.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 resolve_enabled_toolsets(args: &Args) -> Result<EnabledToolsets> {
// 1. Explicit --tools flag always wins
if let Some(ref tools) = args.tools {
return parse_tool_specs(tools);
}
// 2. Auto-detect from config profiles
if let Some(toolsets) = detect_toolsets_from_config() {
return Ok(toolsets);
}
// 3. Fallback: all compiled-in features
#[allow(unused_mut)]
let mut all = vec![Toolset::App];
#[cfg(feature = "cloud")]
all.push(Toolset::Cloud);
#[cfg(feature = "enterprise")]
all.push(Toolset::Enterprise);
#[cfg(feature = "database")]
all.push(Toolset::Database);
Ok(EnabledToolsets::all_of(all))
}
/// Map a CLI `Toolset` to its corresponding `ToolsetKind` for policy lookup.
fn toolset_to_kind(t: &Toolset) -> ToolsetKind {
match t {
#[cfg(feature = "cloud")]
Toolset::Cloud => ToolsetKind::Cloud,
#[cfg(feature = "enterprise")]
Toolset::Enterprise => ToolsetKind::Enterprise,
#[cfg(feature = "database")]
Toolset::Database => ToolsetKind::Database,
Toolset::App => ToolsetKind::App,
}
}
/// Resolve the policy configuration.
///
/// If a policy file is found (via `--policy`, env var, or default path), it takes precedence
/// and `--read-only` is ignored. Otherwise, synthesize a policy from the `--read-only` flag.
fn resolve_policy(args: &Args) -> Result<(PolicyConfig, String)> {
let has_explicit_policy = args.policy.is_some();
let has_env_policy = std::env::var("REDISCTL_MCP_POLICY").is_ok() && args.policy.is_none();
let has_default_policy = PolicyConfig::default_path_exists();
resolve_policy_with_source_flags(
args,
has_explicit_policy || has_env_policy,
has_default_policy,
)
}
fn resolve_policy_with_source_flags(
args: &Args,
has_explicit_or_env_policy: bool,
has_default_policy: bool,
) -> Result<(PolicyConfig, String)> {
if has_explicit_or_env_policy || has_default_policy {
let (config, source) = PolicyConfig::load(args.policy.as_deref())?;
if !args.read_only {
tracing::warn!(
"--read-only=false is ignored when a policy file is active (source: {})",
source
);
}
return Ok((config, source));
}
// No policy file: synthesize from --read-only flag
let tier = if args.read_only {
SafetyTier::ReadOnly
} else {
SafetyTier::Full
};
let source = if args.read_only {
"cli: --read-only=true (default)".to_string()
} else {
"cli: --read-only=false".to_string()
};
let mut config = PolicyConfig::synthesized_default();
config.tier = tier;
Ok((config, source))
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
let mut enabled = resolve_enabled_toolsets(&args)?;
// Resolve policy configuration (includes audit config)
let (policy_config, policy_source) = resolve_policy(&args)?;
// Apply policy-based toolset disabling (only when --tools was not explicit)
if args.tools.is_none() {
let disabled = policy_config.disabled_toolsets();
if !disabled.is_empty() {
enabled.retain(|t| !disabled.contains(&toolset_to_kind(t)));
}
}
let enabled_names: Vec<String> = enabled.iter().map(|t| t.to_string()).collect();
let audit_config = Arc::new(policy_config.audit.clone());
// Initialize tracing with optional audit layer
// App logs: human-readable text to stderr (excludes audit target)
// Audit logs: JSON to stderr (only audit target, when enabled)
init_tracing(&args.log_level, audit_config.enabled);
info!(
transport = ?args.transport,
profiles = ?args.profile,
policy_tier = %policy_config.tier,
policy_source = %policy_source,
audit_enabled = audit_config.enabled,
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 tool-to-toolset mapping for policy evaluation
let tool_toolset = build_tool_toolset_mapping(&enabled);
// Extract tools visibility config before consuming policy_config
let tools_config = policy_config.tools.clone();
// Build resolved policy (consumes a clone of the mapping)
let policy = Arc::new(Policy::new(
policy_config,
tool_toolset.clone(),
policy_source,
));
// Build application state
let state = Arc::new(AppState::new(
credential_source,
policy.clone(),
args.database_url.clone(),
args.cluster,
args.client_name.clone(),
)?);
// Resolve skills directory
let skills_dir = resolve_skills_dir(&args);
// Build router with tools and policy-based filter
let router = build_router(
state.clone(),
policy,
&enabled,
tools_config,
&tool_toolset,
skills_dir.as_deref(),
)?;
// Wrap mapping in Arc for shared use (after last borrow)
let tool_toolset_arc = Arc::new(tool_toolset);
match args.transport {
Transport::Stdio => {
info!("Running with stdio transport");
if audit_config.enabled {
info!("Audit logging enabled (level: {:?})", audit_config.level);
StdioTransport::new(router)
.layer(AuditLayer::new(audit_config, tool_toolset_arc))
.run()
.await?;
} else {
StdioTransport::new(router).run().await?;
}
}
Transport::Http => {
info!(host = %args.host, port = args.port, "Running with HTTP transport");
run_http_server(router, &args, audit_config, tool_toolset_arc).await?;
}
}
Ok(())
}
/// Initialize the tracing subscriber with optional audit logging layer.
///
/// When audit is enabled, adds a second JSON-formatted layer that captures only
/// events with `target = "audit"`. The app layer excludes audit events to avoid
/// double-logging.
fn init_tracing(log_level: &str, audit_enabled: bool) {
use tracing_subscriber::filter;
if audit_enabled {
// Dual-layer: app (text, no audit) + audit (JSON, only audit)
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| log_level.to_string().into());
let app_layer = fmt::layer().with_writer(std::io::stderr).with_filter(
filter::Targets::new()
.with_default(tracing::Level::TRACE)
.with_target("audit", filter::LevelFilter::OFF),
);
let audit_layer = fmt::layer()
.json()
.with_writer(std::io::stderr)
.with_target(true)
.with_filter(filter::Targets::new().with_target("audit", tracing::Level::INFO));
tracing_subscriber::registry()
.with(env_filter)
.with(app_layer)
.with(audit_layer)
.init();
} else {
// Single layer: standard app logs
tracing_subscriber::registry()
.with(fmt::layer().with_writer(std::io::stderr))
.with(
EnvFilter::try_from_default_env().unwrap_or_else(|_| log_level.to_string().into()),
)
.init();
}
}
/// A parsed skill from a SKILL.md file.
struct Skill {
name: String,
description: String,
body: String,
}
/// Strip surrounding quotes (single or double) from a YAML value.
fn strip_yaml_quotes(s: &str) -> &str {
let s = s.trim();
if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
&s[1..s.len() - 1]
} else {
s
}
}
/// Parse a SKILL.md file with YAML frontmatter.
fn parse_skill(content: &str) -> Option<Skill> {
let content = content.trim();
if !content.starts_with("---") {
tracing::debug!("skill parse failed: missing opening frontmatter delimiter");
return None;
}
let after_first = &content[3..];
// Match `---` only at the start of a line to avoid matching inside YAML values
let end = after_first.find("\n---").map(|i| i + 1)?;
if end == 0 {
tracing::debug!("skill parse failed: empty frontmatter");
return None;
}
let frontmatter = &after_first[..end];
let body = after_first[end + 3..].trim().to_string();
let mut name = None;
let mut description = None;
for line in frontmatter.lines() {
let line = line.trim();
if let Some(val) = line.strip_prefix("name:") {
name = Some(strip_yaml_quotes(val).to_string());
} else if let Some(val) = line.strip_prefix("description:") {
description = Some(strip_yaml_quotes(val).to_string());
}
}
if name.is_none() || description.is_none() {
tracing::debug!(
"skill parse failed: missing {} field(s)",
match (name.is_none(), description.is_none()) {
(true, true) => "name and description",
(true, false) => "name",
_ => "description",
}
);
}
Some(Skill {
name: name?,
description: description?,
body,
})
}
/// Load skills from a directory and register them as dynamic prompts.
fn load_skills(dir: &std::path::Path, registry: &DynamicPromptRegistry) -> usize {
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) => {
tracing::warn!("Failed to read skills directory {}: {e}", dir.display());
return 0;
}
};
let mut count = 0;
for entry in entries.flatten() {
if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
continue;
}
let skill_file = entry.path().join("SKILL.md");
if let Ok(content) = std::fs::read_to_string(&skill_file)
&& let Some(skill) = parse_skill(&content)
{
info!(skill = %skill.name, "Loaded skill prompt");
let body = skill.body.clone();
let description = skill.description.clone();
let prompt = PromptBuilder::new(&skill.name)
.description(&skill.description)
.handler(move |_args| {
let body = body.clone();
let description = description.clone();
async move {
Ok(tower_mcp::GetPromptResult::user_message_with_description(
body,
description,
))
}
})
.build();
registry.register(prompt);
count += 1;
}
}
count
}
/// Resolve the skills directory: explicit flag > bundled skills.
fn resolve_skills_dir(args: &Args) -> Option<PathBuf> {
if let Some(ref dir) = args.skills_dir {
if dir.is_dir() {
return Some(dir.clone());
}
tracing::warn!("Skills directory not found: {}", dir.display());
return None;
}
// Fall back to bundled skills next to the binary
if let Ok(exe) = std::env::current_exe() {
let bundled = exe
.parent()
.unwrap_or(std::path::Path::new("."))
.join("skills");
if bundled.is_dir() {
return Some(bundled);
}
}
None
}
/// Build the tool name -> toolset kind mapping for policy evaluation.
fn build_tool_toolset_mapping(enabled: &EnabledToolsets) -> HashMap<String, ToolsetKind> {
let mut mapping = HashMap::new();
for (toolset, selection) in &enabled.selections {
let kind = toolset_to_kind(toolset);
for name in selected_tool_names(toolset, selection) {
mapping.insert(name, kind);
}
}
mapping
}
/// Merge a single toolset's router(s) into the main router, respecting sub-module selection.
fn merge_toolset_router(
router: McpRouter,
toolset: &Toolset,
selection: &SubModuleSelection,
state: Arc<AppState>,
) -> McpRouter {
match selection {
SubModuleSelection::All => match toolset {
#[cfg(feature = "cloud")]
Toolset::Cloud => router.merge(tools::cloud::router(state)),
#[cfg(feature = "enterprise")]
Toolset::Enterprise => router.merge(tools::enterprise::router(state)),
#[cfg(feature = "database")]
Toolset::Database => router.merge(tools::redis::router(state)),
Toolset::App => router.merge(tools::profile::router(state)),
},
SubModuleSelection::Selected(sub_modules) => {
let mut r = router;
for _sub in sub_modules {
let sub_router: Option<McpRouter> = match toolset {
#[cfg(feature = "cloud")]
Toolset::Cloud => tools::cloud::sub_router(_sub, state.clone()),
#[cfg(feature = "enterprise")]
Toolset::Enterprise => tools::enterprise::sub_router(_sub, state.clone()),
#[cfg(feature = "database")]
Toolset::Database => tools::redis::sub_router(_sub, state.clone()),
Toolset::App => None,
};
if let Some(sr) = sub_router {
r = r.merge(sr);
}
}
r
}
}
}
/// Build the MCP router with modular sub-routers based on enabled toolsets
fn build_router(
state: Arc<AppState>,
policy: Arc<Policy>,
enabled: &EnabledToolsets,
tools_config: ToolsConfig,
tool_toolset: &HashMap<String, ToolsetKind>,
skills_dir: Option<&std::path::Path>,
) -> Result<McpRouter> {
let router = McpRouter::new().server_info("redisctl-mcp", env!("CARGO_PKG_VERSION"));
// Enable dynamic prompts for skill loading
let (mut router, prompt_registry) = router.with_dynamic_prompts();
// Merge toolsets, respecting sub-module selection
for (toolset, selection) in &enabled.selections {
router = merge_toolset_router(router, toolset, selection, state.clone());
}
// Register built-in prompts
prompt_registry.register(crate::prompts::troubleshoot_database_prompt());
prompt_registry.register(crate::prompts::analyze_performance_prompt());
prompt_registry.register(crate::prompts::capacity_planning_prompt());
prompt_registry.register(crate::prompts::migration_planning_prompt());
// Load skills as dynamic prompts
if let Some(dir) = skills_dir {
let count = load_skills(dir, &prompt_registry);
if count > 0 {
info!(count, dir = %dir.display(), "Loaded skill prompts");
}
}
// Register the show_policy tool (always available, bypasses visibility)
router = router.tool(policy::show_policy_tool(policy.clone()));
// Resolve tool visibility from preset config
let all_tools: HashSet<String> = tool_toolset.keys().cloned().collect();
let visible_set = presets::resolve_visible_tools(&tools_config, &all_tools, tool_toolset);
let is_preset_active = !tools_config.is_all();
if is_preset_active {
info!(
preset = %tools_config.preset,
active = visible_set.len(),
total = all_tools.len(),
"Tool visibility preset active"
);
}
// Register list_available_tools tool (always available, bypasses visibility)
let visibility = Arc::new(ToolVisibility {
visible: visible_set.clone(),
all_tools: tool_toolset.clone(),
config: tools_config,
});
router = router.tool(presets::list_available_tools_tool(visibility));
// Build instructions with policy description
let mut prefix = format!(
"# Redis Cloud and Enterprise MCP Server\n\n## Safety Model\n\n{}\n",
policy.describe()
);
if is_preset_active {
prefix.push_str(&format!(
"\n## Tool Visibility\n\n\
A visibility preset is active: {active}/{total} tools are loaded. \
Use the `list_available_tools` tool to see all tools grouped by toolset, \
including hidden tools that can be enabled via the `include` list in the \
policy config.\n",
active = visible_set.len(),
total = all_tools.len(),
));
}
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 combined visibility + policy filter
// System tools (show_policy, list_available_tools) bypass visibility.
// All other tools must pass both visibility and policy checks.
let policy_for_filter = policy.clone();
let visible_for_filter = Arc::new(visible_set);
info!(tier = %policy.global_tier(), "Applying policy filter");
let router = router.tool_filter(
CapabilityFilter::<Tool>::new(move |_session, tool: &Tool| {
let name = tool.name.as_str();
let is_system = presets::SYSTEM_TOOLS.contains(&name);
let is_visible = is_system || visible_for_filter.contains(name);
is_visible && policy_for_filter.is_tool_allowed(tool)
})
.denial_behavior(DenialBehavior::Unauthorized),
);
Ok(router)
}
/// Run the HTTP server with middleware
#[cfg(feature = "http")]
async fn run_http_server(
router: McpRouter,
args: &Args,
audit_config: Arc<audit::AuditConfig>,
tool_toolset: Arc<HashMap<String, ToolsetKind>>,
) -> 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 mut transport = HttpTransport::new(router)
.layer(TimeoutLayer::new(Duration::from_secs(
args.request_timeout_secs,
)))
.layer(ConcurrencyLimitLayer::new(args.max_concurrent));
if audit_config.enabled {
info!(
"Audit logging enabled for HTTP transport (level: {:?})",
audit_config.level
);
transport = transport.layer(AuditLayer::new(audit_config, tool_toolset));
}
if args.oauth {
// OAuth-enabled HTTP transport
bail!(
"OAuth support is not yet implemented. Remove --oauth to start the server without authentication."
);
}
transport.serve(&addr).await?;
Ok(())
}
#[cfg(not(feature = "http"))]
async fn run_http_server(
_router: McpRouter,
_args: &Args,
_audit_config: Arc<audit::AuditConfig>,
_tool_toolset: Arc<HashMap<String, ToolsetKind>>,
) -> 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,