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
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
//! Key-level Redis tools (keys, scan, get, key_type, ttl, exists, memory_usage, object_encoding,
//! object_freq, object_idletime, object_help, set, del, expire, rename)

use std::sync::Arc;

use schemars::JsonSchema;
use serde::Deserialize;
use tower_mcp::extract::{Json, State};
use tower_mcp::{CallToolResult, Error as McpError, McpRouter, ResultExt, Tool, ToolBuilder};

use crate::state::AppState;

/// Build a sub-router containing all key-level Redis tools
pub fn router(state: Arc<AppState>) -> McpRouter {
    McpRouter::new()
        .tool(keys(state.clone()))
        .tool(scan(state.clone()))
        .tool(get(state.clone()))
        .tool(key_type(state.clone()))
        .tool(ttl(state.clone()))
        .tool(exists(state.clone()))
        .tool(memory_usage(state.clone()))
        .tool(object_encoding(state.clone()))
        .tool(object_freq(state.clone()))
        .tool(object_idletime(state.clone()))
        .tool(object_help(state.clone()))
        .tool(set(state.clone()))
        .tool(del(state.clone()))
        .tool(expire(state.clone()))
        .tool(rename(state))
}

/// Input for keys command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct KeysInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key pattern to match (default: "*")
    #[serde(default = "default_pattern")]
    pub pattern: String,
    /// Maximum number of keys to return (default: 100)
    #[serde(default = "default_limit")]
    pub limit: usize,
}

fn default_pattern() -> String {
    "*".to_string()
}

fn default_limit() -> usize {
    100
}

/// Build the keys tool
pub fn keys(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_keys")
        .description(
            "List keys matching a pattern using SCAN (production-safe, non-blocking). \
             Returns up to 'limit' keys.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, KeysInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<KeysInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                // Use SCAN to safely iterate keys
                let mut cursor: u64 = 0;
                let mut all_keys: Vec<String> = Vec::new();

                loop {
                    let (new_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
                        .arg(cursor)
                        .arg("MATCH")
                        .arg(&input.pattern)
                        .arg("COUNT")
                        .arg(100)
                        .query_async(&mut conn)
                        .await
                        .tool_context("SCAN failed")?;

                    all_keys.extend(keys);
                    cursor = new_cursor;

                    if cursor == 0 || all_keys.len() >= input.limit {
                        break;
                    }
                }

                // Truncate to limit
                all_keys.truncate(input.limit);

                let output = if all_keys.is_empty() {
                    format!("No keys found matching pattern '{}'", input.pattern)
                } else {
                    format!(
                        "Found {} key(s) matching '{}'\n\n{}",
                        all_keys.len(),
                        input.pattern,
                        all_keys.join("\n")
                    )
                };

                Ok(CallToolResult::text(output))
            },
        )
        .build()
}

/// Input for GET command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to get
    pub key: String,
}

/// Build the get tool
pub fn get(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_get")
        .description("Get the value of a key from Redis")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<GetInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let value: Option<String> = redis::cmd("GET")
                    .arg(&input.key)
                    .query_async(&mut conn)
                    .await
                    .tool_context("GET failed")?;

                match value {
                    Some(v) => Ok(CallToolResult::text(v)),
                    None => Ok(CallToolResult::text(format!(
                        "(nil) - key '{}' not found",
                        input.key
                    ))),
                }
            },
        )
        .build()
}

/// Input for TYPE command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TypeInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to check type
    pub key: String,
}

/// Build the type tool
pub fn key_type(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_type")
        .description("Get the type of a key (string, list, set, zset, hash, stream)")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, TypeInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<TypeInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let key_type: String = redis::cmd("TYPE")
                    .arg(&input.key)
                    .query_async(&mut conn)
                    .await
                    .tool_context("TYPE failed")?;

                Ok(CallToolResult::text(format!("{}: {}", input.key, key_type)))
            },
        )
        .build()
}

/// Input for TTL command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TtlInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to check TTL
    pub key: String,
}

/// Build the ttl tool
pub fn ttl(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_ttl")
        .description("Get the time-to-live (TTL) of a key in seconds. Returns -1 if no expiry, -2 if key doesn't exist.")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, TtlInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<TtlInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str())
                    .tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let ttl: i64 = redis::cmd("TTL")
                    .arg(&input.key)
                    .query_async(&mut conn)
                    .await
                    .tool_context("TTL failed")?;

                let message = match ttl {
                    -2 => format!("{}: key does not exist", input.key),
                    -1 => format!("{}: no expiry set", input.key),
                    _ => format!("{}: {} seconds remaining", input.key, ttl),
                };

                Ok(CallToolResult::text(message))
            },
        )
        .build()
}

/// Input for EXISTS command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ExistsInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Keys to check existence
    pub keys: Vec<String>,
}

/// Build the exists tool
pub fn exists(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_exists")
        .description("Check if one or more keys exist. Returns the count of keys that exist.")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ExistsInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ExistsInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let mut cmd = redis::cmd("EXISTS");
                for key in &input.keys {
                    cmd.arg(key);
                }

                let count: i64 = cmd
                    .query_async(&mut conn)
                    .await
                    .tool_context("EXISTS failed")?;

                Ok(CallToolResult::text(format!(
                    "{} of {} key(s) exist",
                    count,
                    input.keys.len()
                )))
            },
        )
        .build()
}

/// Input for MEMORY USAGE command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct MemoryUsageInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to check memory usage
    pub key: String,
}

/// Build the memory_usage tool
pub fn memory_usage(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_memory_usage")
        .description("Get the memory usage of a key in bytes")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, MemoryUsageInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<MemoryUsageInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let bytes: Option<i64> = redis::cmd("MEMORY")
                    .arg("USAGE")
                    .arg(&input.key)
                    .query_async(&mut conn)
                    .await
                    .tool_context("MEMORY USAGE failed")?;

                match bytes {
                    Some(b) => Ok(CallToolResult::text(format!("{}: {} bytes", input.key, b))),
                    None => Ok(CallToolResult::text(format!(
                        "{}: key does not exist",
                        input.key
                    ))),
                }
            },
        )
        .build()
}

/// Input for SCAN with type filter
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ScanInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key pattern to match (default: "*")
    #[serde(default = "default_pattern")]
    pub pattern: String,
    /// Filter by key type (e.g., "string", "list", "set", "zset", "hash", "stream")
    #[serde(default)]
    pub key_type: Option<String>,
    /// Maximum number of keys to return (default: 100)
    #[serde(default = "default_limit")]
    pub limit: usize,
}

/// Build the scan tool with type filter
pub fn scan(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_scan")
        .description(
            "Scan keys with optional type filter. More efficient than redis_keys when filtering \
             by type (string, list, set, zset, hash, stream).",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ScanInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ScanInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let mut cursor: u64 = 0;
                let mut all_keys: Vec<String> = Vec::new();

                loop {
                    let mut cmd = redis::cmd("SCAN");
                    cmd.arg(cursor)
                        .arg("MATCH")
                        .arg(&input.pattern)
                        .arg("COUNT")
                        .arg(100);

                    // Add TYPE filter if specified
                    if let Some(ref key_type) = input.key_type {
                        cmd.arg("TYPE").arg(key_type);
                    }

                    let (new_cursor, keys): (u64, Vec<String>) = cmd
                        .query_async(&mut conn)
                        .await
                        .tool_context("SCAN failed")?;

                    all_keys.extend(keys);
                    cursor = new_cursor;

                    if cursor == 0 || all_keys.len() >= input.limit {
                        break;
                    }
                }

                all_keys.truncate(input.limit);

                let type_info = input
                    .key_type
                    .as_ref()
                    .map(|t| format!(" of type '{}'", t))
                    .unwrap_or_default();

                let output = if all_keys.is_empty() {
                    format!(
                        "No keys{} found matching pattern '{}'",
                        type_info, input.pattern
                    )
                } else {
                    format!(
                        "Found {} key(s){} matching '{}'\n\n{}",
                        all_keys.len(),
                        type_info,
                        input.pattern,
                        all_keys.join("\n")
                    )
                };

                Ok(CallToolResult::text(output))
            },
        )
        .build()
}

/// Input for OBJECT ENCODING command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ObjectEncodingInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to check encoding
    pub key: String,
}

/// Build the object_encoding tool
pub fn object_encoding(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_object_encoding")
        .description(
            "Get the internal encoding of a key (e.g., embstr, int, raw, quicklist, listpack, \
             hashtable, intset, skiplist). Useful for understanding memory usage patterns.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ObjectEncodingInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<ObjectEncodingInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str())
                    .tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let encoding: Option<String> = redis::cmd("OBJECT")
                    .arg("ENCODING")
                    .arg(&input.key)
                    .query_async(&mut conn)
                    .await
                    .tool_context("OBJECT ENCODING failed")?;

                match encoding {
                    Some(enc) => Ok(CallToolResult::text(format!("{}: {}", input.key, enc))),
                    None => Ok(CallToolResult::text(format!(
                        "{}: key does not exist",
                        input.key
                    ))),
                }
            },
        )
        .build()
}

/// Input for OBJECT FREQ command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ObjectFreqInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to get LFU access frequency for
    pub key: String,
}

/// Build the object_freq tool
pub fn object_freq(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_object_freq")
        .description(
            "Get the LFU access frequency counter for a key using OBJECT FREQ. \
             Only works when maxmemory-policy is set to allkeys-lfu or volatile-lfu.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ObjectFreqInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ObjectFreqInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let freq: i64 = redis::cmd("OBJECT")
                    .arg("FREQ")
                    .arg(&input.key)
                    .query_async(&mut conn)
                    .await
                    .tool_context("OBJECT FREQ failed")?;

                Ok(CallToolResult::text(format!(
                    "{}: LFU frequency counter = {}",
                    input.key, freq
                )))
            },
        )
        .build()
}

/// Input for OBJECT IDLETIME command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ObjectIdletimeInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to get idle time for
    pub key: String,
}

/// Build the object_idletime tool
pub fn object_idletime(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_object_idletime")
        .description(
            "Get the idle time of a key in seconds using OBJECT IDLETIME. \
             Shows how long since the key was last accessed.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ObjectIdletimeInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<ObjectIdletimeInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str())
                    .tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let idle: i64 = redis::cmd("OBJECT")
                    .arg("IDLETIME")
                    .arg(&input.key)
                    .query_async(&mut conn)
                    .await
                    .tool_context("OBJECT IDLETIME failed")?;

                Ok(CallToolResult::text(format!(
                    "{}: idle for {} seconds",
                    input.key, idle
                )))
            },
        )
        .build()
}

/// Input for OBJECT HELP command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ObjectHelpInput {
    /// Optional Redis URL (overrides profile, uses configured URL if not provided)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name to resolve connection from (uses default profile if not set)
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the object_help tool
pub fn object_help(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_object_help")
        .description("Get available OBJECT subcommands using OBJECT HELP")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ObjectHelpInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ObjectHelpInput>| async move {
                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let result: Vec<String> = redis::cmd("OBJECT")
                    .arg("HELP")
                    .query_async(&mut conn)
                    .await
                    .tool_context("OBJECT HELP failed")?;

                Ok(CallToolResult::text(format!(
                    "OBJECT subcommands:\n{}",
                    result.join("\n")
                )))
            },
        )
        .build()
}

// --- Write tools ---

/// Input for SET command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SetInput {
    /// Optional Redis URL (overrides profile)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name for connection resolution
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to set
    pub key: String,
    /// Value to set
    pub value: String,
    /// Expire time in seconds
    #[serde(default)]
    pub ex: Option<u64>,
    /// Expire time in milliseconds
    #[serde(default)]
    pub px: Option<u64>,
    /// Only set if key does not already exist
    #[serde(default)]
    pub nx: bool,
    /// Only set if key already exists
    #[serde(default)]
    pub xx: bool,
}

/// Build the set tool
pub fn set(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_set")
        .description(
            "Set a key to a string value with optional expiry and conditional flags. \
             Use EX for seconds, PX for milliseconds expiry. Use NX to only set if \
             the key does not exist, XX to only set if it exists.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, SetInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<SetInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let mut cmd = redis::cmd("SET");
                cmd.arg(&input.key).arg(&input.value);

                if let Some(ex) = input.ex {
                    cmd.arg("EX").arg(ex);
                }
                if let Some(px) = input.px {
                    cmd.arg("PX").arg(px);
                }
                if input.nx {
                    cmd.arg("NX");
                }
                if input.xx {
                    cmd.arg("XX");
                }

                let result: Option<String> = cmd
                    .query_async(&mut conn)
                    .await
                    .tool_context("SET failed")?;

                match result {
                    Some(_) => Ok(CallToolResult::text(format!(
                        "OK - set '{}' successfully",
                        input.key
                    ))),
                    None => Ok(CallToolResult::text(format!(
                        "Key '{}' not set (condition not met: {})",
                        input.key,
                        if input.nx {
                            "NX - key already exists"
                        } else {
                            "XX - key does not exist"
                        }
                    ))),
                }
            },
        )
        .build()
}

/// Input for DEL command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DelInput {
    /// Optional Redis URL (overrides profile)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name for connection resolution
    #[serde(default)]
    pub profile: Option<String>,
    /// Keys to delete
    pub keys: Vec<String>,
}

/// Build the del tool
pub fn del(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_del")
        .description(
            "DANGEROUS: Permanently deletes one or more keys and their data. \
             This action cannot be undone. Returns the number of keys removed.",
        )
        .destructive()
        .extractor_handler_typed::<_, _, _, DelInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<DelInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let mut cmd = redis::cmd("DEL");
                for key in &input.keys {
                    cmd.arg(key);
                }

                let count: i64 = cmd
                    .query_async(&mut conn)
                    .await
                    .tool_context("DEL failed")?;

                Ok(CallToolResult::text(format!(
                    "Deleted {} of {} key(s)",
                    count,
                    input.keys.len()
                )))
            },
        )
        .build()
}

/// Input for EXPIRE command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ExpireInput {
    /// Optional Redis URL (overrides profile)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name for connection resolution
    #[serde(default)]
    pub profile: Option<String>,
    /// Key to set expiry on
    pub key: String,
    /// TTL in seconds
    pub seconds: i64,
}

/// Build the expire tool
pub fn expire(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_expire")
        .description(
            "Set a timeout on a key in seconds. The key will be automatically deleted \
             after the timeout expires. Returns whether the timeout was set.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, ExpireInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ExpireInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let result: bool = redis::cmd("EXPIRE")
                    .arg(&input.key)
                    .arg(input.seconds)
                    .query_async(&mut conn)
                    .await
                    .tool_context("EXPIRE failed")?;

                if result {
                    Ok(CallToolResult::text(format!(
                        "OK - TTL set to {} seconds on '{}'",
                        input.seconds, input.key
                    )))
                } else {
                    Ok(CallToolResult::text(format!(
                        "Key '{}' does not exist or timeout could not be set",
                        input.key
                    )))
                }
            },
        )
        .build()
}

/// Input for RENAME command
#[derive(Debug, Deserialize, JsonSchema)]
pub struct RenameInput {
    /// Optional Redis URL (overrides profile)
    #[serde(default)]
    pub url: Option<String>,
    /// Optional profile name for connection resolution
    #[serde(default)]
    pub profile: Option<String>,
    /// Current key name
    pub key: String,
    /// New key name
    pub newkey: String,
}

/// Build the rename tool
pub fn rename(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("redis_rename")
        .description(
            "Rename a key. Returns an error if the source key does not exist. \
             If the destination key already exists, it is overwritten.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, RenameInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<RenameInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let url = super::resolve_redis_url(input.url, input.profile.as_deref(), &state)?;

                let client = redis::Client::open(url.as_str()).tool_context("Invalid URL")?;

                let mut conn = client
                    .get_multiplexed_async_connection()
                    .await
                    .tool_context("Connection failed")?;

                let _: () = redis::cmd("RENAME")
                    .arg(&input.key)
                    .arg(&input.newkey)
                    .query_async(&mut conn)
                    .await
                    .tool_context("RENAME failed")?;

                Ok(CallToolResult::text(format!(
                    "OK - renamed '{}' to '{}'",
                    input.key, input.newkey
                )))
            },
        )
        .build()
}