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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
//! Account, ACL, task, cloud account (BYOC), and user tools for Redis Cloud

use std::sync::Arc;

use redis_cloud::acl::{
    AclRedisRuleCreateRequest, AclRedisRuleUpdateRequest, AclRoleCreateRequest,
    AclRoleDatabaseSpec, AclRoleRedisRuleSpec, AclRoleUpdateRequest, AclUserCreateRequest,
    AclUserUpdateRequest,
};
use redis_cloud::cloud_accounts::{CloudAccountCreateRequest, CloudAccountUpdateRequest};
use redis_cloud::{
    AccountHandler, AclHandler, CloudAccountHandler, CostReportCreateRequest, CostReportHandler,
    TaskHandler, UserHandler,
};
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;
use crate::tools::wrap_list;

// ============================================================================
// Account tools
// ============================================================================

/// Input for getting current account
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetAccountInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_account tool
pub fn get_account(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_account")
        .description("Get information about the current Redis Cloud account including name, ID, and settings.")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetAccountInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<GetAccountInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AccountHandler::new(client);
                let account = handler
                    .get_current_account()
                    .await
                    .tool_context("Failed to get account")?;

                CallToolResult::from_serialize(&account)
            },
        )
        .build()
}

/// Input for getting account system logs
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetSystemLogsInput {
    /// Number of entries to skip (for pagination)
    #[serde(default)]
    pub offset: Option<i32>,
    /// Maximum number of entries to return
    #[serde(default)]
    pub limit: Option<i32>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_system_logs tool
pub fn get_system_logs(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_system_logs")
        .description(
            "Get system audit logs for the Redis Cloud account. Includes events like \
             subscription changes, database modifications, and user actions.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetSystemLogsInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<GetSystemLogsInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AccountHandler::new(client);
                let logs = handler
                    .get_account_system_logs(input.offset, input.limit)
                    .await
                    .tool_context("Failed to get system logs")?;

                CallToolResult::from_serialize(&logs)
            },
        )
        .build()
}

/// Input for getting account session logs
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetSessionLogsInput {
    /// Number of entries to skip (for pagination)
    #[serde(default)]
    pub offset: Option<i32>,
    /// Maximum number of entries to return
    #[serde(default)]
    pub limit: Option<i32>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_session_logs tool
pub fn get_session_logs(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_session_logs")
        .description(
            "Get session activity logs for the Redis Cloud account. Includes user login/logout \
             events and session information.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetSessionLogsInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<GetSessionLogsInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AccountHandler::new(client);
                let logs = handler
                    .get_account_session_logs(input.offset, input.limit)
                    .await
                    .tool_context("Failed to get session logs")?;

                CallToolResult::from_serialize(&logs)
            },
        )
        .build()
}

/// Input for getting supported regions
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetRegionsInput {
    /// Optional cloud provider filter (e.g., "AWS", "GCP", "Azure")
    #[serde(default)]
    pub provider: Option<String>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_regions tool
pub fn get_regions(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_regions")
        .description(
            "Get supported cloud regions for Redis Cloud. Optionally filter by provider (AWS, GCP, Azure).",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetRegionsInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<GetRegionsInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AccountHandler::new(client);
                let regions = handler
                    .get_supported_regions(input.provider)
                    .await
                    .tool_context("Failed to get regions")?;

                CallToolResult::from_serialize(&regions)
            },
        )
        .build()
}

/// Input for getting database modules
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetModulesInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_modules tool
pub fn get_modules(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_modules")
        .description(
            "Get supported Redis database modules (e.g., Search, JSON, TimeSeries, Bloom).",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetModulesInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<GetModulesInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AccountHandler::new(client);
                let modules = handler
                    .get_supported_database_modules()
                    .await
                    .tool_context("Failed to get modules")?;

                CallToolResult::from_serialize(&modules)
            },
        )
        .build()
}

// ============================================================================
// Account Users tools
// ============================================================================

/// Input for listing account users
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListAccountUsersInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the list_account_users tool
pub fn list_account_users(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("list_account_users")
        .description(
            "List all users in the Redis Cloud account (team members with console access).",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ListAccountUsersInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<ListAccountUsersInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = UserHandler::new(client);
                let users = handler
                    .get_all_users()
                    .await
                    .tool_context("Failed to list users")?;

                CallToolResult::from_serialize(&users)
            },
        )
        .build()
}

/// Input for getting a specific account user
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetAccountUserInput {
    /// Account user ID
    pub user_id: i32,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_account_user tool
pub fn get_account_user(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_account_user")
        .description(
            "Get detailed information about a specific account user (team member) by ID.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetAccountUserInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<GetAccountUserInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = UserHandler::new(client);
                let user = handler
                    .get_user_by_id(input.user_id)
                    .await
                    .tool_context("Failed to get account user")?;

                CallToolResult::from_serialize(&user)
            },
        )
        .build()
}

// ============================================================================
// ACL tools (database-level access control)
// ============================================================================

/// Input for listing ACL users
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListAclUsersInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the list_acl_users tool
pub fn list_acl_users(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("list_acl_users")
        .description("List all ACL users (database-level Redis users for authentication).")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ListAclUsersInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ListAclUsersInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let users = handler
                    .get_all_acl_users()
                    .await
                    .tool_context("Failed to list ACL users")?;

                CallToolResult::from_serialize(&users)
            },
        )
        .build()
}

/// Input for getting a specific ACL user
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetAclUserInput {
    /// ACL user ID
    pub user_id: i32,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_acl_user tool
pub fn get_acl_user(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_acl_user")
        .description("Get detailed information about a specific ACL user by ID.")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetAclUserInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<GetAclUserInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let user = handler
                    .get_user_by_id(input.user_id)
                    .await
                    .tool_context("Failed to get ACL user")?;

                CallToolResult::from_serialize(&user)
            },
        )
        .build()
}

/// Input for listing ACL roles
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListAclRolesInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the list_acl_roles tool
pub fn list_acl_roles(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("list_acl_roles")
        .description("List all ACL roles (permission templates for database access).")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ListAclRolesInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ListAclRolesInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let roles = handler
                    .get_roles()
                    .await
                    .tool_context("Failed to list ACL roles")?;

                CallToolResult::from_serialize(&roles)
            },
        )
        .build()
}

/// Input for listing Redis rules
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListRedisRulesInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the list_redis_rules tool
pub fn list_redis_rules(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("list_redis_rules")
        .description("List all Redis ACL rules (command permissions for Redis users).")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ListRedisRulesInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<ListRedisRulesInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let rules = handler
                    .get_all_redis_rules()
                    .await
                    .tool_context("Failed to list Redis rules")?;

                CallToolResult::from_serialize(&rules)
            },
        )
        .build()
}

// ============================================================================
// ACL write operations (require write permission)
// ============================================================================

/// Input for creating an ACL user
#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateAclUserInput {
    /// Access control user name
    pub name: String,
    /// Name of the database access role to assign. Use list_acl_roles to get available roles.
    pub role: String,
    /// Database password for the user
    pub password: String,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the create_acl_user tool
pub fn create_acl_user(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("create_acl_user")
        .description(
            "Create a new ACL user with the assigned database access role. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, CreateAclUserInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<CreateAclUserInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let request = AclUserCreateRequest {
                    name: input.name,
                    role: input.role,
                    password: input.password,
                    command_type: None,
                };
                let result = handler
                    .create_user(&request)
                    .await
                    .tool_context("Failed to create ACL user")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for updating an ACL user
#[derive(Debug, Deserialize, JsonSchema)]
pub struct UpdateAclUserInput {
    /// ACL user ID to update
    pub user_id: i32,
    /// New database access role name (optional)
    #[serde(default)]
    pub role: Option<String>,
    /// New database password (optional)
    #[serde(default)]
    pub password: Option<String>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the update_acl_user tool
pub fn update_acl_user(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("update_acl_user")
        .description(
            "Update an ACL user's role or password. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, UpdateAclUserInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<UpdateAclUserInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let request = AclUserUpdateRequest {
                    user_id: None,
                    role: input.role,
                    password: input.password,
                    command_type: None,
                };
                let result = handler
                    .update_acl_user(input.user_id, &request)
                    .await
                    .tool_context("Failed to update ACL user")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for deleting an ACL user
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteAclUserInput {
    /// ACL user ID to delete
    pub user_id: i32,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the delete_acl_user tool
pub fn delete_acl_user(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("delete_acl_user")
        .description(
            "DANGEROUS: Permanently deletes an ACL user. Active sessions using this user \
             will be terminated. Requires write permission.",
        )
        .destructive()
        .extractor_handler_typed::<_, _, _, DeleteAclUserInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<DeleteAclUserInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let result = handler
                    .delete_user(input.user_id)
                    .await
                    .tool_context("Failed to delete ACL user")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Database specification for ACL role assignment
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DatabaseSpec {
    /// Subscription ID for the database
    pub subscription_id: i32,
    /// Database ID
    pub database_id: i32,
    /// Optional list of regions for Active-Active databases
    #[serde(default)]
    pub regions: Option<Vec<String>>,
}

/// Redis rule specification for role creation/update
#[derive(Debug, Deserialize, JsonSchema)]
pub struct RedisRuleSpec {
    /// Redis ACL rule name. Use list_redis_rules to get available rules.
    pub rule_name: String,
    /// List of databases where this rule applies
    pub databases: Vec<DatabaseSpec>,
}

/// Input for creating an ACL role
#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateAclRoleInput {
    /// Database access role name
    pub name: String,
    /// List of Redis ACL rules to assign to this role
    pub redis_rules: Vec<RedisRuleSpec>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the create_acl_role tool
pub fn create_acl_role(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("create_acl_role")
        .description(
            "Create a new ACL role with assigned Redis rules and database associations. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, CreateAclRoleInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<CreateAclRoleInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let request = AclRoleCreateRequest {
                    name: input.name,
                    redis_rules: input
                        .redis_rules
                        .into_iter()
                        .map(|r| AclRoleRedisRuleSpec {
                            rule_name: r.rule_name,
                            databases: r
                                .databases
                                .into_iter()
                                .map(|d| AclRoleDatabaseSpec {
                                    subscription_id: d.subscription_id,
                                    database_id: d.database_id,
                                    regions: d.regions,
                                })
                                .collect(),
                        })
                        .collect(),
                    command_type: None,
                };
                let result = handler
                    .create_role(&request)
                    .await
                    .tool_context("Failed to create ACL role")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for updating an ACL role
#[derive(Debug, Deserialize, JsonSchema)]
pub struct UpdateAclRoleInput {
    /// ACL role ID to update
    pub role_id: i32,
    /// New role name (optional)
    #[serde(default)]
    pub name: Option<String>,
    /// New list of Redis ACL rules (optional)
    #[serde(default)]
    pub redis_rules: Option<Vec<RedisRuleSpec>>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the update_acl_role tool
pub fn update_acl_role(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("update_acl_role")
        .description(
            "Update an ACL role's name or Redis rule assignments. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, UpdateAclRoleInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<UpdateAclRoleInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let request = AclRoleUpdateRequest {
                    name: input.name,
                    redis_rules: input.redis_rules.map(|rules| {
                        rules
                            .into_iter()
                            .map(|r| AclRoleRedisRuleSpec {
                                rule_name: r.rule_name,
                                databases: r
                                    .databases
                                    .into_iter()
                                    .map(|d| AclRoleDatabaseSpec {
                                        subscription_id: d.subscription_id,
                                        database_id: d.database_id,
                                        regions: d.regions,
                                    })
                                    .collect(),
                            })
                            .collect()
                    }),
                    role_id: None,
                    command_type: None,
                };
                let result = handler
                    .update_role(input.role_id, &request)
                    .await
                    .tool_context("Failed to update ACL role")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for deleting an ACL role
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteAclRoleInput {
    /// ACL role ID to delete
    pub role_id: i32,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the delete_acl_role tool
pub fn delete_acl_role(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("delete_acl_role")
        .description(
            "DANGEROUS: Permanently deletes an ACL role. Users assigned to this role \
             will lose their permissions. Requires write permission.",
        )
        .destructive()
        .extractor_handler_typed::<_, _, _, DeleteAclRoleInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<DeleteAclRoleInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let result = handler
                    .delete_acl_role(input.role_id)
                    .await
                    .tool_context("Failed to delete ACL role")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for creating a Redis ACL rule
#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateRedisRuleInput {
    /// Redis ACL rule name
    pub name: String,
    /// Redis ACL rule pattern (e.g., "+@all ~*" or "+@read ~cache:*")
    pub redis_rule: String,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the create_redis_rule tool
pub fn create_redis_rule(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("create_redis_rule")
        .description(
            "Create a new Redis ACL rule defining command permissions. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, CreateRedisRuleInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<CreateRedisRuleInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let request = AclRedisRuleCreateRequest {
                    name: input.name,
                    redis_rule: input.redis_rule,
                    command_type: None,
                };
                let result = handler
                    .create_redis_rule(&request)
                    .await
                    .tool_context("Failed to create Redis rule")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for updating a Redis ACL rule
#[derive(Debug, Deserialize, JsonSchema)]
pub struct UpdateRedisRuleInput {
    /// Redis ACL rule ID to update
    pub rule_id: i32,
    /// New rule name
    pub name: String,
    /// New Redis ACL rule pattern
    pub redis_rule: String,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the update_redis_rule tool
pub fn update_redis_rule(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("update_redis_rule")
        .description(
            "Update a Redis ACL rule's name or pattern. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, UpdateRedisRuleInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<UpdateRedisRuleInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let request = AclRedisRuleUpdateRequest {
                    redis_rule_id: None,
                    name: input.name,
                    redis_rule: input.redis_rule,
                    command_type: None,
                };
                let result = handler
                    .update_redis_rule(input.rule_id, &request)
                    .await
                    .tool_context("Failed to update Redis rule")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for deleting a Redis ACL rule
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteRedisRuleInput {
    /// Redis ACL rule ID to delete
    pub rule_id: i32,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the delete_redis_rule tool
pub fn delete_redis_rule(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("delete_redis_rule")
        .description(
            "DANGEROUS: Permanently deletes a Redis ACL rule. Roles using this rule \
             will lose those permissions. Requires write permission.",
        )
        .destructive()
        .extractor_handler_typed::<_, _, _, DeleteRedisRuleInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<DeleteRedisRuleInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AclHandler::new(client);
                let result = handler
                    .delete_redis_rule(input.rule_id)
                    .await
                    .tool_context("Failed to delete Redis rule")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

// ============================================================================
// Cost report tools
// ============================================================================

/// Input for generating a cost report
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GenerateCostReportInput {
    /// Start date in YYYY-MM-DD format
    pub start_date: String,
    /// End date in YYYY-MM-DD format (max 40 days from start_date)
    pub end_date: String,
    /// Output format: "csv" or "json" (default: "csv")
    #[serde(default)]
    pub format: Option<String>,
    /// Filter by subscription IDs
    #[serde(default)]
    pub subscription_ids: Option<Vec<i32>>,
    /// Filter by database IDs
    #[serde(default)]
    pub database_ids: Option<Vec<i32>>,
    /// Filter by subscription type: "pro" or "essentials"
    #[serde(default)]
    pub subscription_type: Option<String>,
    /// Filter by cloud regions
    #[serde(default)]
    pub regions: Option<Vec<String>>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the generate_cost_report tool
pub fn generate_cost_report(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("generate_cost_report")
        .description(
            "Generate a cost report in FOCUS format for the specified date range. \
             Returns a task ID to track generation progress. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, GenerateCostReportInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<GenerateCostReportInput>| async move {
                use redis_cloud::{CostReportFormat, SubscriptionType};

                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = CostReportHandler::new(client);
                let format = input.format.as_deref().map(|f| match f {
                    "json" => CostReportFormat::Json,
                    _ => CostReportFormat::Csv,
                });
                let subscription_type = input.subscription_type.as_deref().map(|t| match t {
                    "essentials" => SubscriptionType::Essentials,
                    _ => SubscriptionType::Pro,
                });
                let request = CostReportCreateRequest {
                    start_date: input.start_date,
                    end_date: input.end_date,
                    format,
                    subscription_ids: input.subscription_ids,
                    database_ids: input.database_ids,
                    subscription_type,
                    regions: input.regions,
                    tags: None,
                };
                let result = handler
                    .generate_cost_report(request)
                    .await
                    .tool_context("Failed to generate cost report")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for downloading a cost report
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DownloadCostReportInput {
    /// Cost report ID from a completed generation task
    pub cost_report_id: String,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the download_cost_report tool
pub fn download_cost_report(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("download_cost_report")
        .description(
            "Download a previously generated cost report by ID. \
             Returns the report content (CSV or JSON).",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, DownloadCostReportInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<DownloadCostReportInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = CostReportHandler::new(client);
                let bytes = handler
                    .download_cost_report(&input.cost_report_id)
                    .await
                    .tool_context("Failed to download cost report")?;

                let content = String::from_utf8(bytes).unwrap_or_else(|e| {
                    format!("<binary data, {} bytes>", e.into_bytes().len())
                });
                CallToolResult::from_serialize(&content)
            },
        )
        .build()
}

// ============================================================================
// Payment method tools
// ============================================================================

/// Input for listing payment methods
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListPaymentMethodsInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the list_payment_methods tool
pub fn list_payment_methods(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("list_payment_methods")
        .description("List all payment methods for the Redis Cloud account.")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ListPaymentMethodsInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<ListPaymentMethodsInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = AccountHandler::new(client);
                let methods = handler
                    .get_account_payment_methods()
                    .await
                    .tool_context("Failed to list payment methods")?;

                CallToolResult::from_serialize(&methods)
            },
        )
        .build()
}

// ============================================================================
// Task tools
// ============================================================================

/// Input for listing tasks
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListTasksInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the list_tasks tool
pub fn list_tasks(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("list_tasks")
        .description("List all async tasks in the Redis Cloud account. Tasks track long-running operations like database creation.")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ListTasksInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<ListTasksInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = TaskHandler::new(client);
                let tasks = handler
                    .get_all_tasks()
                    .await
                    .tool_context("Failed to list tasks")?;

                wrap_list("tasks", &tasks)
            },
        )
        .build()
}

/// Input for getting a specific task
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetTaskInput {
    /// Task ID
    pub task_id: String,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_task tool
pub fn get_task(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_task")
        .description("Get status and details of a specific async task by ID.")
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetTaskInput>(
            state,
            |State(state): State<Arc<AppState>>, Json(input): Json<GetTaskInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = TaskHandler::new(client);
                let task = handler
                    .get_task_by_id(input.task_id)
                    .await
                    .tool_context("Failed to get task")?;

                CallToolResult::from_serialize(&task)
            },
        )
        .build()
}

// ============================================================================
// Cloud Account (BYOC) tools
// ============================================================================

/// Input for listing cloud accounts
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListCloudAccountsInput {
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the list_cloud_accounts tool
pub fn list_cloud_accounts(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("list_cloud_accounts")
        .description(
            "List all configured cloud provider accounts (BYOC). Returns cloud accounts \
             for AWS, GCP, or Azure that are integrated with Redis Cloud.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, ListCloudAccountsInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<ListCloudAccountsInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = CloudAccountHandler::new(client);
                let result = handler
                    .get_cloud_accounts()
                    .await
                    .tool_context("Failed to list cloud accounts")?;

                let accounts = result.cloud_accounts.unwrap_or_default();
                wrap_list("cloud_accounts", &accounts)
            },
        )
        .build()
}

/// Input for getting a cloud account by ID
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetCloudAccountInput {
    /// Cloud account ID
    pub cloud_account_id: i32,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the get_cloud_account tool
pub fn get_cloud_account(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("get_cloud_account")
        .description(
            "Get details for a specific cloud provider account (BYOC) by ID, \
             including provider type, access credentials, and status.",
        )
        .read_only_safe()
        .extractor_handler_typed::<_, _, _, GetCloudAccountInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<GetCloudAccountInput>| async move {
                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = CloudAccountHandler::new(client);
                let account = handler
                    .get_cloud_account_by_id(input.cloud_account_id)
                    .await
                    .tool_context("Failed to get cloud account")?;

                CallToolResult::from_serialize(&account)
            },
        )
        .build()
}

/// Input for creating a cloud account
#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateCloudAccountInput {
    /// Cloud account display name
    pub name: String,
    /// Cloud provider (e.g., "AWS", "GCP", "Azure"). Defaults to "AWS" if not specified.
    #[serde(default)]
    pub provider: Option<String>,
    /// Cloud provider access key
    pub access_key_id: String,
    /// Cloud provider secret key
    pub access_secret_key: String,
    /// Cloud provider management console username
    pub console_username: String,
    /// Cloud provider management console password
    pub console_password: String,
    /// Cloud provider management console login URL
    pub sign_in_login_url: String,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the create_cloud_account tool
pub fn create_cloud_account(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("create_cloud_account")
        .description(
            "Create a new cloud provider account (BYOC) for AWS, GCP, or Azure. \
             Registers cloud credentials with Redis Cloud for resource provisioning. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, CreateCloudAccountInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<CreateCloudAccountInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = CloudAccountHandler::new(client);
                let request = CloudAccountCreateRequest {
                    name: input.name,
                    provider: input.provider,
                    access_key_id: input.access_key_id,
                    access_secret_key: input.access_secret_key,
                    console_username: input.console_username,
                    console_password: input.console_password,
                    sign_in_login_url: input.sign_in_login_url,
                    command_type: None,
                };
                let result = handler
                    .create_cloud_account(&request)
                    .await
                    .tool_context("Failed to create cloud account")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for updating a cloud account
#[derive(Debug, Deserialize, JsonSchema)]
pub struct UpdateCloudAccountInput {
    /// Cloud account ID to update
    pub cloud_account_id: i32,
    /// New display name (optional)
    #[serde(default)]
    pub name: Option<String>,
    /// Cloud provider access key
    pub access_key_id: String,
    /// Cloud provider secret key
    pub access_secret_key: String,
    /// Cloud provider management console username
    pub console_username: String,
    /// Cloud provider management console password
    pub console_password: String,
    /// Cloud provider management console login URL (optional)
    #[serde(default)]
    pub sign_in_login_url: Option<String>,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the update_cloud_account tool
pub fn update_cloud_account(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("update_cloud_account")
        .description(
            "Update an existing cloud provider account (BYOC) configuration, \
             including credentials and console access details. \
             Requires write permission.",
        )
        .non_destructive()
        .extractor_handler_typed::<_, _, _, UpdateCloudAccountInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<UpdateCloudAccountInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = CloudAccountHandler::new(client);
                let request = CloudAccountUpdateRequest {
                    name: input.name,
                    cloud_account_id: None,
                    access_key_id: input.access_key_id,
                    access_secret_key: input.access_secret_key,
                    console_username: input.console_username,
                    console_password: input.console_password,
                    sign_in_login_url: input.sign_in_login_url,
                    command_type: None,
                };
                let result = handler
                    .update_cloud_account(input.cloud_account_id, &request)
                    .await
                    .tool_context("Failed to update cloud account")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Input for deleting a cloud account
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteCloudAccountInput {
    /// Cloud account ID to delete
    pub cloud_account_id: i32,
    /// Profile name for multi-account support. If not specified, uses the first configured profile or default.
    #[serde(default)]
    pub profile: Option<String>,
}

/// Build the delete_cloud_account tool
pub fn delete_cloud_account(state: Arc<AppState>) -> Tool {
    ToolBuilder::new("delete_cloud_account")
        .description(
            "DANGEROUS: Permanently deletes a cloud provider account (BYOC). This removes \
             the cloud account integration and cannot be undone. Requires write permission.",
        )
        .destructive()
        .extractor_handler_typed::<_, _, _, DeleteCloudAccountInput>(
            state,
            |State(state): State<Arc<AppState>>,
             Json(input): Json<DeleteCloudAccountInput>| async move {
                if !state.is_write_allowed() {
                    return Err(McpError::tool(
                        "Write operations not allowed in read-only mode",
                    ));
                }

                let client = state
                    .cloud_client_for_profile(input.profile.as_deref())
                    .await
                    .map_err(|e| crate::tools::credential_error("cloud", e))?;

                let handler = CloudAccountHandler::new(client);
                let result = handler
                    .delete_cloud_account(input.cloud_account_id)
                    .await
                    .tool_context("Failed to delete cloud account")?;

                CallToolResult::from_serialize(&result)
            },
        )
        .build()
}

/// Build an MCP sub-router containing account, ACL, cloud account, and task tools
pub fn router(state: Arc<AppState>) -> McpRouter {
    McpRouter::new()
        // Account & Configuration
        .tool(get_account(state.clone()))
        .tool(get_regions(state.clone()))
        .tool(get_modules(state.clone()))
        .tool(list_account_users(state.clone()))
        .tool(get_account_user(state.clone()))
        .tool(list_acl_users(state.clone()))
        .tool(get_acl_user(state.clone()))
        .tool(list_acl_roles(state.clone()))
        .tool(list_redis_rules(state.clone()))
        .tool(list_payment_methods(state.clone()))
        // ACL Write Operations
        .tool(create_acl_user(state.clone()))
        .tool(update_acl_user(state.clone()))
        .tool(delete_acl_user(state.clone()))
        .tool(create_acl_role(state.clone()))
        .tool(update_acl_role(state.clone()))
        .tool(delete_acl_role(state.clone()))
        .tool(create_redis_rule(state.clone()))
        .tool(update_redis_rule(state.clone()))
        .tool(delete_redis_rule(state.clone()))
        // Cloud Accounts (BYOC)
        .tool(list_cloud_accounts(state.clone()))
        .tool(get_cloud_account(state.clone()))
        .tool(create_cloud_account(state.clone()))
        .tool(update_cloud_account(state.clone()))
        .tool(delete_cloud_account(state.clone()))
        // Cost Reports
        .tool(generate_cost_report(state.clone()))
        .tool(download_cost_report(state.clone()))
        // Logs
        .tool(get_system_logs(state.clone()))
        .tool(get_session_logs(state.clone()))
        // Tasks
        .tool(list_tasks(state.clone()))
        .tool(get_task(state.clone()))
}