sqry-mcp 8.0.7

MCP server for sqry semantic code search
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
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
//! MCP server configuration.
//!
//! This module contains configuration for the MCP server, including
//! timeout and retry settings.

use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use std::env;

/// MCP server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpConfig {
    /// Timeout for MCP tool execution in milliseconds (default: 60000)
    ///
    /// Controls the maximum time allowed for a tool to execute before
    /// being cancelled. This prevents long-running operations from blocking
    /// the MCP server.
    ///
    /// # Validation
    /// - Minimum: 1000ms (1 second)
    /// - Maximum: 600000ms (10 minutes, recommended)
    /// - Hard cap: 3600000ms (1 hour, absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_TIMEOUT_MS` environment variable.
    pub timeout_ms: u64,

    /// Retry delay for deadline exceeded errors in milliseconds (default: 500)
    ///
    /// When a tool execution exceeds its deadline, this value is returned
    /// to the client as a suggested retry delay. The client can use this
    /// to implement exponential backoff or other retry strategies.
    ///
    /// # Validation
    /// - Minimum: 100ms
    /// - Maximum: 30000ms (30 seconds, recommended)
    /// - Hard cap: 60000ms (1 minute, absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_RETRY_DELAY_MS` environment variable.
    pub retry_delay_ms: u64,

    /// Cache capacity for `trace_path` results (default: 256)
    ///
    /// Controls how many `trace_path` query results are cached to improve
    /// performance for repeated queries. Larger values use more memory
    /// but reduce computation for frequently requested paths.
    ///
    /// # Validation
    /// - Minimum: 16 (basic caching)
    /// - Maximum: 1024 (recommended)
    /// - Hard cap: 4096 (absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_TRACE_CACHE_SIZE` environment variable.
    pub trace_cache_size: usize,

    /// Cache capacity for subgraph results (default: 128)
    ///
    /// Controls how many subgraph extraction results are cached. Subgraphs
    /// are typically larger than trace paths, so a smaller cache is used.
    ///
    /// # Validation
    /// - Minimum: 8 (basic caching)
    /// - Maximum: 512 (recommended)
    /// - Hard cap: 2048 (absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_SUBGRAPH_CACHE_SIZE` environment variable.
    pub subgraph_cache_size: usize,

    /// Maximum edges to scan for cross-language analysis (default: 50000)
    ///
    /// Performance guard to prevent excessive scanning when analyzing
    /// cross-language dependencies. Large codebases may have millions of
    /// edges, so this limit prevents timeouts and memory issues.
    ///
    /// # Validation
    /// - Minimum: 1000 (basic analysis)
    /// - Maximum: 500000 (recommended for large codebases)
    /// - Hard cap: 1000000 (absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_MAX_CROSS_LANG_EDGES` environment variable.
    pub max_cross_lang_edges: usize,

    /// Engine cache capacity (default: 5)
    ///
    /// Controls how many workspace engine instances are cached in memory.
    /// Each workspace gets its own Engine with loaded index. Larger values
    /// allow working with more repositories simultaneously without reloading.
    ///
    /// # Validation
    /// - Minimum: 1 (cache at least one workspace)
    /// - Maximum: 100 (recommended for memory management)
    /// - Hard cap: 1000 (absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_ENGINE_CACHE_CAPACITY` environment variable.
    #[serde(default = "default_engine_cache_capacity")]
    pub engine_cache_capacity: usize,

    /// Discovery cache capacity (default: 100)
    ///
    /// Controls how many workspace path resolution results are cached.
    /// This cache maps user-provided paths to canonical workspace roots,
    /// avoiding repeated filesystem traversal.
    ///
    /// # Validation
    /// - Minimum: 10 (basic caching)
    /// - Maximum: 1000 (recommended)
    /// - Hard cap: 10000 (absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_DISCOVERY_CACHE_CAPACITY` environment variable.
    #[serde(default = "default_discovery_cache_capacity")]
    pub discovery_cache_capacity: usize,

    /// Trace path cache capacity (default: 256)
    ///
    /// Controls how many `trace_path` query results are cached to improve
    /// performance for repeated queries. This is the primary cache capacity
    /// field; the legacy `trace_cache_size` field is retained for backward
    /// compatibility but this field takes precedence.
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_TRACE_PATH_CACHE_CAPACITY` environment variable.
    #[serde(default = "default_trace_path_cache_capacity")]
    pub trace_path_cache_capacity: usize,

    /// Subgraph cache capacity (default: 128)
    ///
    /// Controls how many subgraph extraction results are cached. This is the
    /// primary cache capacity field; the legacy `subgraph_cache_size` field
    /// is retained for backward compatibility but this field takes precedence.
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_SUBGRAPH_CACHE_CAPACITY` environment variable.
    #[serde(default = "default_subgraph_cache_capacity")]
    pub subgraph_cache_capacity: usize,

    /// Query cache TTL in seconds (default: 300)
    ///
    /// Time-to-live for cached query results (`trace_path`, subgraph).
    /// Expired entries are evicted on access. Lower values keep results
    /// fresher but increase computation. Higher values improve performance
    /// but may serve stale results.
    ///
    /// # Validation
    /// - Minimum: 10 seconds (avoid thrashing)
    /// - Maximum: 3600 seconds (1 hour, recommended)
    /// - Hard cap: 86400 seconds (24 hours, absolute maximum)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_QUERY_CACHE_TTL_SECS` environment variable.
    #[serde(default = "default_query_cache_ttl")]
    pub query_cache_ttl_secs: u64,

    /// Timeout for index rebuild operations in milliseconds (default: 600000 = 10 min).
    ///
    /// Separate from the general tool timeout because index builds are inherently
    /// slow on large codebases. Only applies to the `rebuild_index` MCP tool.
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_MCP_INDEX_TIMEOUT_MS` environment variable.
    #[serde(default = "default_index_timeout")]
    pub index_timeout_ms: u64,

    /// Redaction preset for MCP responses (default: "minimal")
    ///
    /// Controls what sensitive data is redacted from MCP tool responses
    /// before they are sent to clients. Presets: `none` (passthrough),
    /// `minimal` (paths only), `standard` (paths + code), `strict` (all).
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_REDACTION_PRESET` environment variable.
    /// Additional fine-grained control via `SQRY_REDACT_PATHS`, `SQRY_REDACT_CODE`, etc.
    #[serde(default = "default_redaction_preset")]
    pub redaction_preset: String,
}

fn default_engine_cache_capacity() -> usize {
    5
}

fn default_discovery_cache_capacity() -> usize {
    100
}

fn default_trace_path_cache_capacity() -> usize {
    256
}

fn default_subgraph_cache_capacity() -> usize {
    128
}

fn default_query_cache_ttl() -> u64 {
    300
}

fn default_index_timeout() -> u64 {
    600_000 // 10 minutes
}

fn default_redaction_preset() -> String {
    "minimal".to_string()
}

impl Default for McpConfig {
    fn default() -> Self {
        Self {
            timeout_ms: 60_000,
            retry_delay_ms: 500,
            trace_cache_size: 256,
            subgraph_cache_size: 128,
            max_cross_lang_edges: 50_000,
            engine_cache_capacity: default_engine_cache_capacity(),
            discovery_cache_capacity: default_discovery_cache_capacity(),
            trace_path_cache_capacity: default_trace_path_cache_capacity(),
            subgraph_cache_capacity: default_subgraph_cache_capacity(),
            query_cache_ttl_secs: default_query_cache_ttl(),
            index_timeout_ms: default_index_timeout(),
            redaction_preset: default_redaction_preset(),
        }
    }
}

impl McpConfig {
    /// Minimum allowed timeout (1 second)
    const MIN_TIMEOUT_MS: u64 = 1000;

    /// Maximum recommended timeout (10 minutes)
    const MAX_TIMEOUT_MS: u64 = 600_000;

    /// Absolute hard cap for timeout (1 hour, security constraint)
    const ABSOLUTE_MAX_TIMEOUT_MS: u64 = 3_600_000;

    /// Minimum allowed retry delay (100ms)
    const MIN_RETRY_DELAY_MS: u64 = 100;

    /// Maximum recommended retry delay (30 seconds)
    const MAX_RETRY_DELAY_MS: u64 = 30_000;

    /// Absolute hard cap for retry delay (1 minute, security constraint)
    const ABSOLUTE_MAX_RETRY_DELAY_MS: u64 = 60_000;

    /// Minimum allowed trace cache size
    const MIN_TRACE_CACHE_SIZE: usize = 16;

    /// Maximum recommended trace cache size
    const MAX_TRACE_CACHE_SIZE: usize = 1024;

    /// Absolute hard cap for trace cache size
    const ABSOLUTE_MAX_TRACE_CACHE_SIZE: usize = 4096;

    /// Minimum allowed subgraph cache size
    const MIN_SUBGRAPH_CACHE_SIZE: usize = 8;

    /// Maximum recommended subgraph cache size
    const MAX_SUBGRAPH_CACHE_SIZE: usize = 512;

    /// Absolute hard cap for subgraph cache size
    const ABSOLUTE_MAX_SUBGRAPH_CACHE_SIZE: usize = 2048;

    /// Minimum allowed cross-language edges scan limit
    const MIN_CROSS_LANG_EDGES: usize = 1000;

    /// Maximum recommended cross-language edges scan limit
    const MAX_CROSS_LANG_EDGES: usize = 500_000;

    /// Absolute hard cap for cross-language edges scan limit
    const ABSOLUTE_MAX_CROSS_LANG_EDGES: usize = 1_000_000;

    /// Minimum allowed engine cache capacity
    #[allow(dead_code)] // Used for validation logic consistency
    const MIN_ENGINE_CACHE_CAPACITY: usize = 1;

    /// Maximum recommended engine cache capacity
    const MAX_ENGINE_CACHE_CAPACITY: usize = 100;

    /// Absolute hard cap for engine cache capacity
    const ABSOLUTE_MAX_ENGINE_CACHE_CAPACITY: usize = 1000;

    /// Minimum allowed discovery cache capacity
    const MIN_DISCOVERY_CACHE_CAPACITY: usize = 10;

    /// Maximum recommended discovery cache capacity
    const MAX_DISCOVERY_CACHE_CAPACITY: usize = 1000;

    /// Absolute hard cap for discovery cache capacity
    const ABSOLUTE_MAX_DISCOVERY_CACHE_CAPACITY: usize = 10_000;

    /// Minimum allowed trace path cache capacity (overrides `trace_cache_size`)
    const MIN_TRACE_PATH_CACHE_CAPACITY: usize = 16;

    /// Maximum recommended trace path cache capacity
    const MAX_TRACE_PATH_CACHE_CAPACITY: usize = 1024;

    /// Absolute hard cap for trace path cache capacity
    const ABSOLUTE_MAX_TRACE_PATH_CACHE_CAPACITY: usize = 4096;

    /// Minimum allowed subgraph cache capacity (overrides `subgraph_cache_size`)
    const MIN_SUBGRAPH_CACHE_CAPACITY: usize = 8;

    /// Maximum recommended subgraph cache capacity
    const MAX_SUBGRAPH_CACHE_CAPACITY: usize = 512;

    /// Absolute hard cap for subgraph cache capacity
    const ABSOLUTE_MAX_SUBGRAPH_CACHE_CAPACITY: usize = 2048;

    /// Minimum allowed query cache TTL
    const MIN_QUERY_CACHE_TTL_SECS: u64 = 10;

    /// Maximum recommended query cache TTL
    const MAX_QUERY_CACHE_TTL_SECS: u64 = 3600;

    /// Absolute hard cap for query cache TTL
    const ABSOLUTE_MAX_QUERY_CACHE_TTL_SECS: u64 = 86_400;

    /// Create a new MCP configuration with custom values
    ///
    /// # Errors
    ///
    /// Returns an error if validation fails (invalid cache sizes, timeouts, etc.)
    #[allow(dead_code)] // Used in tests or programmatic configuration setup.
    pub fn new(
        timeout_ms: u64,
        retry_delay_ms: u64,
        trace_cache_size: usize,
        subgraph_cache_size: usize,
        max_cross_lang_edges: usize,
    ) -> Result<Self> {
        let config = Self {
            timeout_ms,
            retry_delay_ms,
            trace_cache_size,
            subgraph_cache_size,
            max_cross_lang_edges,
            engine_cache_capacity: default_engine_cache_capacity(),
            discovery_cache_capacity: default_discovery_cache_capacity(),
            trace_path_cache_capacity: default_trace_path_cache_capacity(),
            subgraph_cache_capacity: default_subgraph_cache_capacity(),
            query_cache_ttl_secs: default_query_cache_ttl(),
            index_timeout_ms: default_index_timeout(),
            redaction_preset: default_redaction_preset(),
        };
        config.validate()?;
        Ok(config)
    }

    /// Load configuration with environment variable overrides
    ///
    /// # Errors
    ///
    /// Returns an error if environment variables contain invalid values or validation fails
    pub fn load_or_default() -> Result<Self> {
        let mut config = Self::default();

        // Apply environment variable overrides if present
        if let Ok(timeout_str) = env::var("SQRY_MCP_TIMEOUT_MS") {
            config.timeout_ms = Self::parse_env_var(&timeout_str, "SQRY_MCP_TIMEOUT_MS")?;
        }

        if let Ok(retry_str) = env::var("SQRY_MCP_RETRY_DELAY_MS") {
            config.retry_delay_ms = Self::parse_env_var(&retry_str, "SQRY_MCP_RETRY_DELAY_MS")?;
        }

        if let Ok(trace_str) = env::var("SQRY_MCP_TRACE_CACHE_SIZE") {
            config.trace_cache_size =
                Self::parse_env_var_usize(&trace_str, "SQRY_MCP_TRACE_CACHE_SIZE")?;
        }

        if let Ok(subgraph_str) = env::var("SQRY_MCP_SUBGRAPH_CACHE_SIZE") {
            config.subgraph_cache_size =
                Self::parse_env_var_usize(&subgraph_str, "SQRY_MCP_SUBGRAPH_CACHE_SIZE")?;
        }

        if let Ok(edges_str) = env::var("SQRY_MCP_MAX_CROSS_LANG_EDGES") {
            config.max_cross_lang_edges =
                Self::parse_env_var_usize(&edges_str, "SQRY_MCP_MAX_CROSS_LANG_EDGES")?;
        }

        if let Ok(engine_cache_str) = env::var("SQRY_MCP_ENGINE_CACHE_CAPACITY") {
            config.engine_cache_capacity =
                Self::parse_env_var_usize(&engine_cache_str, "SQRY_MCP_ENGINE_CACHE_CAPACITY")?;
        }

        if let Ok(discovery_cache_str) = env::var("SQRY_MCP_DISCOVERY_CACHE_CAPACITY") {
            config.discovery_cache_capacity = Self::parse_env_var_usize(
                &discovery_cache_str,
                "SQRY_MCP_DISCOVERY_CACHE_CAPACITY",
            )?;
        }

        if let Ok(trace_path_cache_str) = env::var("SQRY_MCP_TRACE_PATH_CACHE_CAPACITY") {
            config.trace_path_cache_capacity = Self::parse_env_var_usize(
                &trace_path_cache_str,
                "SQRY_MCP_TRACE_PATH_CACHE_CAPACITY",
            )?;
        }

        if let Ok(subgraph_cache_str) = env::var("SQRY_MCP_SUBGRAPH_CACHE_CAPACITY") {
            config.subgraph_cache_capacity =
                Self::parse_env_var_usize(&subgraph_cache_str, "SQRY_MCP_SUBGRAPH_CACHE_CAPACITY")?;
        }

        if let Ok(ttl_str) = env::var("SQRY_MCP_QUERY_CACHE_TTL_SECS") {
            config.query_cache_ttl_secs =
                Self::parse_env_var(&ttl_str, "SQRY_MCP_QUERY_CACHE_TTL_SECS")?;
        }

        if let Ok(index_timeout_str) = env::var("SQRY_MCP_INDEX_TIMEOUT_MS") {
            config.index_timeout_ms =
                Self::parse_env_var(&index_timeout_str, "SQRY_MCP_INDEX_TIMEOUT_MS")?;
        }

        // Store preset for logging; fine-grained overrides (SQRY_REDACT_PATHS, etc.)
        // are handled by RedactionConfig::from_env() when the Redactor is created
        if let Ok(preset_str) = env::var("SQRY_REDACTION_PRESET") {
            config.redaction_preset = preset_str;
        }

        config.validate()?;
        Ok(config)
    }

    /// Get effective timeout with validation
    ///
    /// This method enforces all validation constraints and returns the
    /// safe-to-use timeout value.
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (unlimited not allowed)
    /// - Value is below minimum (< 1000ms)
    /// - Value exceeds hard cap (> 3600000ms)
    pub fn effective_timeout_ms(&self) -> Result<u64> {
        if self.timeout_ms == 0 {
            bail!("mcp.timeout_ms cannot be 0 (unlimited not allowed for safety)");
        }

        if self.timeout_ms < Self::MIN_TIMEOUT_MS {
            bail!(
                "mcp.timeout_ms {} is below minimum {}ms",
                self.timeout_ms,
                Self::MIN_TIMEOUT_MS
            );
        }

        if self.timeout_ms > Self::MAX_TIMEOUT_MS {
            tracing::warn!(
                "mcp.timeout_ms {} exceeds recommended maximum {}ms",
                self.timeout_ms,
                Self::MAX_TIMEOUT_MS
            );
        }

        if self.timeout_ms > Self::ABSOLUTE_MAX_TIMEOUT_MS {
            bail!(
                "mcp.timeout_ms {} exceeds absolute hard cap {}ms",
                self.timeout_ms,
                Self::ABSOLUTE_MAX_TIMEOUT_MS
            );
        }

        Ok(self.timeout_ms)
    }

    /// Get effective retry delay with validation
    ///
    /// This method enforces all validation constraints and returns the
    /// safe-to-use retry delay value.
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (no delay not allowed)
    /// - Value is below minimum (< 100ms)
    /// - Value exceeds hard cap (> 60000ms)
    pub fn effective_retry_delay_ms(&self) -> Result<u64> {
        if self.retry_delay_ms == 0 {
            bail!("mcp.retry_delay_ms cannot be 0 (no delay not allowed for safety)");
        }

        if self.retry_delay_ms < Self::MIN_RETRY_DELAY_MS {
            bail!(
                "mcp.retry_delay_ms {} is below minimum {}ms",
                self.retry_delay_ms,
                Self::MIN_RETRY_DELAY_MS
            );
        }

        if self.retry_delay_ms > Self::MAX_RETRY_DELAY_MS {
            tracing::warn!(
                "mcp.retry_delay_ms {} exceeds recommended maximum {}ms",
                self.retry_delay_ms,
                Self::MAX_RETRY_DELAY_MS
            );
        }

        if self.retry_delay_ms > Self::ABSOLUTE_MAX_RETRY_DELAY_MS {
            bail!(
                "mcp.retry_delay_ms {} exceeds absolute hard cap {}ms",
                self.retry_delay_ms,
                Self::ABSOLUTE_MAX_RETRY_DELAY_MS
            );
        }

        Ok(self.retry_delay_ms)
    }

    /// Get effective trace cache size with validation
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (caching disabled not allowed)
    /// - Value is below minimum (< 16)
    /// - Value exceeds hard cap (> 4096)
    pub fn effective_trace_cache_size(&self) -> Result<usize> {
        if self.trace_cache_size == 0 {
            bail!("mcp.trace_cache_size cannot be 0 (caching disabled not allowed)");
        }

        if self.trace_cache_size < Self::MIN_TRACE_CACHE_SIZE {
            bail!(
                "mcp.trace_cache_size {} is below minimum {}",
                self.trace_cache_size,
                Self::MIN_TRACE_CACHE_SIZE
            );
        }

        if self.trace_cache_size > Self::MAX_TRACE_CACHE_SIZE {
            tracing::warn!(
                "mcp.trace_cache_size {} exceeds recommended maximum {}",
                self.trace_cache_size,
                Self::MAX_TRACE_CACHE_SIZE
            );
        }

        if self.trace_cache_size > Self::ABSOLUTE_MAX_TRACE_CACHE_SIZE {
            bail!(
                "mcp.trace_cache_size {} exceeds absolute hard cap {}",
                self.trace_cache_size,
                Self::ABSOLUTE_MAX_TRACE_CACHE_SIZE
            );
        }

        Ok(self.trace_cache_size)
    }

    /// Get effective subgraph cache size with validation
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (caching disabled not allowed)
    /// - Value is below minimum (< 8)
    /// - Value exceeds hard cap (> 2048)
    pub fn effective_subgraph_cache_size(&self) -> Result<usize> {
        if self.subgraph_cache_size == 0 {
            bail!("mcp.subgraph_cache_size cannot be 0 (caching disabled not allowed)");
        }

        if self.subgraph_cache_size < Self::MIN_SUBGRAPH_CACHE_SIZE {
            bail!(
                "mcp.subgraph_cache_size {} is below minimum {}",
                self.subgraph_cache_size,
                Self::MIN_SUBGRAPH_CACHE_SIZE
            );
        }

        if self.subgraph_cache_size > Self::MAX_SUBGRAPH_CACHE_SIZE {
            tracing::warn!(
                "mcp.subgraph_cache_size {} exceeds recommended maximum {}",
                self.subgraph_cache_size,
                Self::MAX_SUBGRAPH_CACHE_SIZE
            );
        }

        if self.subgraph_cache_size > Self::ABSOLUTE_MAX_SUBGRAPH_CACHE_SIZE {
            bail!(
                "mcp.subgraph_cache_size {} exceeds absolute hard cap {}",
                self.subgraph_cache_size,
                Self::ABSOLUTE_MAX_SUBGRAPH_CACHE_SIZE
            );
        }

        Ok(self.subgraph_cache_size)
    }

    /// Get effective max cross-language edges limit with validation
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (analysis disabled not allowed)
    /// - Value is below minimum (< 1000)
    /// - Value exceeds hard cap (> 1000000)
    pub fn effective_max_cross_lang_edges(&self) -> Result<usize> {
        if self.max_cross_lang_edges == 0 {
            bail!("mcp.max_cross_lang_edges cannot be 0 (analysis disabled not allowed)");
        }

        if self.max_cross_lang_edges < Self::MIN_CROSS_LANG_EDGES {
            bail!(
                "mcp.max_cross_lang_edges {} is below minimum {}",
                self.max_cross_lang_edges,
                Self::MIN_CROSS_LANG_EDGES
            );
        }

        if self.max_cross_lang_edges > Self::MAX_CROSS_LANG_EDGES {
            tracing::warn!(
                "mcp.max_cross_lang_edges {} exceeds recommended maximum {}",
                self.max_cross_lang_edges,
                Self::MAX_CROSS_LANG_EDGES
            );
        }

        if self.max_cross_lang_edges > Self::ABSOLUTE_MAX_CROSS_LANG_EDGES {
            bail!(
                "mcp.max_cross_lang_edges {} exceeds absolute hard cap {}",
                self.max_cross_lang_edges,
                Self::ABSOLUTE_MAX_CROSS_LANG_EDGES
            );
        }

        Ok(self.max_cross_lang_edges)
    }

    /// Get effective engine cache capacity with validation
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (caching disabled not allowed)
    /// - Value exceeds hard cap (> 1000)
    pub fn effective_engine_cache_capacity(&self) -> Result<usize> {
        if self.engine_cache_capacity == 0 {
            bail!("mcp.engine_cache_capacity cannot be 0 (at least 1 workspace required)");
        }

        if self.engine_cache_capacity > Self::MAX_ENGINE_CACHE_CAPACITY {
            tracing::warn!(
                "mcp.engine_cache_capacity {} exceeds recommended maximum {}",
                self.engine_cache_capacity,
                Self::MAX_ENGINE_CACHE_CAPACITY
            );
        }

        if self.engine_cache_capacity > Self::ABSOLUTE_MAX_ENGINE_CACHE_CAPACITY {
            bail!(
                "mcp.engine_cache_capacity {} exceeds absolute hard cap {}",
                self.engine_cache_capacity,
                Self::ABSOLUTE_MAX_ENGINE_CACHE_CAPACITY
            );
        }

        Ok(self.engine_cache_capacity)
    }

    /// Get effective discovery cache capacity with validation
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (caching disabled not allowed)
    /// - Value is below minimum (< 10)
    /// - Value exceeds hard cap (> 10000)
    pub fn effective_discovery_cache_capacity(&self) -> Result<usize> {
        if self.discovery_cache_capacity == 0 {
            bail!("mcp.discovery_cache_capacity cannot be 0 (caching disabled not allowed)");
        }

        if self.discovery_cache_capacity < Self::MIN_DISCOVERY_CACHE_CAPACITY {
            bail!(
                "mcp.discovery_cache_capacity {} is below minimum {}",
                self.discovery_cache_capacity,
                Self::MIN_DISCOVERY_CACHE_CAPACITY
            );
        }

        if self.discovery_cache_capacity > Self::MAX_DISCOVERY_CACHE_CAPACITY {
            tracing::warn!(
                "mcp.discovery_cache_capacity {} exceeds recommended maximum {}",
                self.discovery_cache_capacity,
                Self::MAX_DISCOVERY_CACHE_CAPACITY
            );
        }

        if self.discovery_cache_capacity > Self::ABSOLUTE_MAX_DISCOVERY_CACHE_CAPACITY {
            bail!(
                "mcp.discovery_cache_capacity {} exceeds absolute hard cap {}",
                self.discovery_cache_capacity,
                Self::ABSOLUTE_MAX_DISCOVERY_CACHE_CAPACITY
            );
        }

        Ok(self.discovery_cache_capacity)
    }

    /// Get effective trace path cache capacity with validation
    ///
    /// This takes precedence over `trace_cache_size`.
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (caching disabled not allowed)
    /// - Value is below minimum (< 16)
    /// - Value exceeds hard cap (> 4096)
    pub fn effective_trace_path_cache_capacity(&self) -> Result<usize> {
        if self.trace_path_cache_capacity == 0 {
            bail!("mcp.trace_path_cache_capacity cannot be 0 (caching disabled not allowed)");
        }

        if self.trace_path_cache_capacity < Self::MIN_TRACE_PATH_CACHE_CAPACITY {
            bail!(
                "mcp.trace_path_cache_capacity {} is below minimum {}",
                self.trace_path_cache_capacity,
                Self::MIN_TRACE_PATH_CACHE_CAPACITY
            );
        }

        if self.trace_path_cache_capacity > Self::MAX_TRACE_PATH_CACHE_CAPACITY {
            tracing::warn!(
                "mcp.trace_path_cache_capacity {} exceeds recommended maximum {}",
                self.trace_path_cache_capacity,
                Self::MAX_TRACE_PATH_CACHE_CAPACITY
            );
        }

        if self.trace_path_cache_capacity > Self::ABSOLUTE_MAX_TRACE_PATH_CACHE_CAPACITY {
            bail!(
                "mcp.trace_path_cache_capacity {} exceeds absolute hard cap {}",
                self.trace_path_cache_capacity,
                Self::ABSOLUTE_MAX_TRACE_PATH_CACHE_CAPACITY
            );
        }

        Ok(self.trace_path_cache_capacity)
    }

    /// Get effective subgraph cache capacity with validation
    ///
    /// This takes precedence over `subgraph_cache_size`.
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (caching disabled not allowed)
    /// - Value is below minimum (< 8)
    /// - Value exceeds hard cap (> 2048)
    pub fn effective_subgraph_cache_capacity(&self) -> Result<usize> {
        if self.subgraph_cache_capacity == 0 {
            bail!("mcp.subgraph_cache_capacity cannot be 0 (caching disabled not allowed)");
        }

        if self.subgraph_cache_capacity < Self::MIN_SUBGRAPH_CACHE_CAPACITY {
            bail!(
                "mcp.subgraph_cache_capacity {} is below minimum {}",
                self.subgraph_cache_capacity,
                Self::MIN_SUBGRAPH_CACHE_CAPACITY
            );
        }

        if self.subgraph_cache_capacity > Self::MAX_SUBGRAPH_CACHE_CAPACITY {
            tracing::warn!(
                "mcp.subgraph_cache_capacity {} exceeds recommended maximum {}",
                self.subgraph_cache_capacity,
                Self::MAX_SUBGRAPH_CACHE_CAPACITY
            );
        }

        if self.subgraph_cache_capacity > Self::ABSOLUTE_MAX_SUBGRAPH_CACHE_CAPACITY {
            bail!(
                "mcp.subgraph_cache_capacity {} exceeds absolute hard cap {}",
                self.subgraph_cache_capacity,
                Self::ABSOLUTE_MAX_SUBGRAPH_CACHE_CAPACITY
            );
        }

        Ok(self.subgraph_cache_capacity)
    }

    /// Get effective query cache TTL with validation
    ///
    /// # Errors
    /// Returns an error if:
    /// - Value is 0 (no TTL not allowed)
    /// - Value is below minimum (< 10 seconds)
    /// - Value exceeds hard cap (> 86400 seconds)
    pub fn effective_query_cache_ttl_secs(&self) -> Result<u64> {
        if self.query_cache_ttl_secs == 0 {
            bail!("mcp.query_cache_ttl_secs cannot be 0 (TTL required for freshness)");
        }

        if self.query_cache_ttl_secs < Self::MIN_QUERY_CACHE_TTL_SECS {
            bail!(
                "mcp.query_cache_ttl_secs {} is below minimum {}",
                self.query_cache_ttl_secs,
                Self::MIN_QUERY_CACHE_TTL_SECS
            );
        }

        if self.query_cache_ttl_secs > Self::MAX_QUERY_CACHE_TTL_SECS {
            tracing::warn!(
                "mcp.query_cache_ttl_secs {} exceeds recommended maximum {}",
                self.query_cache_ttl_secs,
                Self::MAX_QUERY_CACHE_TTL_SECS
            );
        }

        if self.query_cache_ttl_secs > Self::ABSOLUTE_MAX_QUERY_CACHE_TTL_SECS {
            bail!(
                "mcp.query_cache_ttl_secs {} exceeds absolute hard cap {}",
                self.query_cache_ttl_secs,
                Self::ABSOLUTE_MAX_QUERY_CACHE_TTL_SECS
            );
        }

        Ok(self.query_cache_ttl_secs)
    }

    /// Get effective index rebuild timeout with validation.
    ///
    /// # Errors
    /// Returns an error if value is 0 or exceeds the absolute hard cap.
    pub fn effective_index_timeout_ms(&self) -> Result<u64> {
        if self.index_timeout_ms == 0 {
            bail!("mcp.index_timeout_ms cannot be 0 (unlimited not allowed for safety)");
        }
        if self.index_timeout_ms < Self::MIN_TIMEOUT_MS {
            bail!(
                "mcp.index_timeout_ms {} is below minimum {}ms",
                self.index_timeout_ms,
                Self::MIN_TIMEOUT_MS
            );
        }
        if self.index_timeout_ms > Self::ABSOLUTE_MAX_TIMEOUT_MS {
            bail!(
                "mcp.index_timeout_ms {} exceeds absolute hard cap {}ms",
                self.index_timeout_ms,
                Self::ABSOLUTE_MAX_TIMEOUT_MS
            );
        }
        Ok(self.index_timeout_ms)
    }

    /// Validate the configuration
    fn validate(&self) -> Result<()> {
        // Validation happens in effective_* methods
        self.effective_timeout_ms()?;
        self.effective_retry_delay_ms()?;
        self.effective_index_timeout_ms()?;
        self.effective_trace_cache_size()?;
        self.effective_subgraph_cache_size()?;
        self.effective_max_cross_lang_edges()?;
        self.effective_engine_cache_capacity()?;
        self.effective_discovery_cache_capacity()?;
        self.effective_trace_path_cache_capacity()?;
        self.effective_subgraph_cache_capacity()?;
        self.effective_query_cache_ttl_secs()?;
        Ok(())
    }

    /// Parse environment variable with strict error handling
    ///
    /// This method implements the fail-fast parse policy:
    /// - Parse errors result in immediate failure with clear message
    /// - Out-of-range values result in immediate failure
    /// - NO silent fallbacks to default values
    fn parse_env_var(value: &str, var_name: &str) -> Result<u64> {
        match value.parse::<u64>() {
            Ok(parsed) => Ok(parsed),
            Err(_) => bail!("Invalid value for {var_name}: '{value}'. Expected u64 milliseconds"),
        }
    }

    /// Parse usize environment variable with strict error handling
    ///
    /// This method implements the fail-fast parse policy for usize values:
    /// - Parse errors result in immediate failure with clear message
    /// - Out-of-range values result in immediate failure
    /// - NO silent fallbacks to default values
    fn parse_env_var_usize(value: &str, var_name: &str) -> Result<usize> {
        match value.parse::<usize>() {
            Ok(parsed) => Ok(parsed),
            Err(_) => bail!("Invalid value for {var_name}: '{value}'. Expected usize"),
        }
    }
}

#[cfg(test)]
#[allow(clippy::field_reassign_with_default)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = McpConfig::default();
        assert_eq!(config.timeout_ms, 60_000);
        assert_eq!(config.retry_delay_ms, 500);
        assert_eq!(config.trace_cache_size, 256);
        assert_eq!(config.subgraph_cache_size, 128);
        assert_eq!(config.max_cross_lang_edges, 50_000);
        assert!(config.effective_timeout_ms().is_ok());
        assert!(config.effective_retry_delay_ms().is_ok());
        assert!(config.effective_trace_cache_size().is_ok());
        assert!(config.effective_subgraph_cache_size().is_ok());
        assert!(config.effective_max_cross_lang_edges().is_ok());
    }

    #[test]
    fn test_new_with_valid_values() {
        let config = McpConfig::new(5000, 1000, 512, 256, 100_000).unwrap();
        assert_eq!(config.effective_timeout_ms().unwrap(), 5000);
        assert_eq!(config.effective_retry_delay_ms().unwrap(), 1000);
        assert_eq!(config.effective_trace_cache_size().unwrap(), 512);
        assert_eq!(config.effective_subgraph_cache_size().unwrap(), 256);
        assert_eq!(config.effective_max_cross_lang_edges().unwrap(), 100_000);
    }

    // --- Table-driven boundary tests for McpConfig::new parameters ---

    struct NewParamCase {
        name: &'static str,
        timeout: u64,
        retry: u64,
        trace: usize,
        subgraph: usize,
        cross_lang: usize,
        expect_ok: bool,
        error_contains: &'static str,
    }

    #[test]
    #[allow(clippy::too_many_lines)] // Config validation covers many fields
    fn test_new_boundary_cases() {
        let cases = [
            // timeout_ms boundaries
            NewParamCase {
                name: "timeout_zero",
                timeout: 0,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "cannot be 0",
            },
            NewParamCase {
                name: "timeout_below_min",
                timeout: 500,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "below minimum 1000ms",
            },
            NewParamCase {
                name: "timeout_at_min",
                timeout: 1000,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "timeout_at_cap",
                timeout: 3_600_000,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "timeout_above_cap",
                timeout: 3_600_001,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "exceeds absolute hard cap",
            },
            // retry_delay_ms boundaries
            NewParamCase {
                name: "retry_zero",
                timeout: 30_000,
                retry: 0,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "cannot be 0",
            },
            NewParamCase {
                name: "retry_below_min",
                timeout: 30_000,
                retry: 50,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "below minimum 100ms",
            },
            NewParamCase {
                name: "retry_at_min",
                timeout: 30_000,
                retry: 100,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "retry_at_cap",
                timeout: 30_000,
                retry: 60_000,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "retry_above_cap",
                timeout: 30_000,
                retry: 60_001,
                trace: 256,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "exceeds absolute hard cap",
            },
            // trace_cache_size boundaries
            NewParamCase {
                name: "trace_zero",
                timeout: 30_000,
                retry: 500,
                trace: 0,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "cannot be 0",
            },
            NewParamCase {
                name: "trace_below_min",
                timeout: 30_000,
                retry: 500,
                trace: 8,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "below minimum 16",
            },
            NewParamCase {
                name: "trace_at_min",
                timeout: 30_000,
                retry: 500,
                trace: 16,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "trace_at_cap",
                timeout: 30_000,
                retry: 500,
                trace: 4096,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "trace_above_cap",
                timeout: 30_000,
                retry: 500,
                trace: 4097,
                subgraph: 128,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "exceeds absolute hard cap",
            },
            // subgraph_cache_size boundaries
            NewParamCase {
                name: "subgraph_zero",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 0,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "cannot be 0",
            },
            NewParamCase {
                name: "subgraph_below_min",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 4,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "below minimum 8",
            },
            NewParamCase {
                name: "subgraph_at_min",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 8,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "subgraph_at_cap",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 2048,
                cross_lang: 50_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "subgraph_above_cap",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 2049,
                cross_lang: 50_000,
                expect_ok: false,
                error_contains: "exceeds absolute hard cap",
            },
            // max_cross_lang_edges boundaries
            NewParamCase {
                name: "cross_lang_zero",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 0,
                expect_ok: false,
                error_contains: "cannot be 0",
            },
            NewParamCase {
                name: "cross_lang_below_min",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 500,
                expect_ok: false,
                error_contains: "below minimum 1000",
            },
            NewParamCase {
                name: "cross_lang_at_min",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 1000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "cross_lang_at_cap",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 1_000_000,
                expect_ok: true,
                error_contains: "",
            },
            NewParamCase {
                name: "cross_lang_above_cap",
                timeout: 30_000,
                retry: 500,
                trace: 256,
                subgraph: 128,
                cross_lang: 1_000_001,
                expect_ok: false,
                error_contains: "exceeds absolute hard cap",
            },
        ];

        for case in &cases {
            let result = McpConfig::new(
                case.timeout,
                case.retry,
                case.trace,
                case.subgraph,
                case.cross_lang,
            );
            if case.expect_ok {
                assert!(
                    result.is_ok(),
                    "case '{}' should succeed but failed: {:?}",
                    case.name,
                    result.unwrap_err()
                );
            } else {
                assert!(
                    result.is_err(),
                    "case '{}' should fail but succeeded",
                    case.name
                );
                let err = result.unwrap_err().to_string();
                assert!(
                    err.contains(case.error_contains),
                    "case '{}': expected error containing '{}', got '{}'",
                    case.name,
                    case.error_contains,
                    err
                );
            }
        }
    }

    // --- Table-driven boundary tests for cache capacity fields ---

    struct CacheCapacityCase {
        name: &'static str,
        field: &'static str,
        value: usize,
        expect_ok: bool,
        expected_value: usize,
        error_contains: &'static str,
    }

    fn apply_and_check(case: &CacheCapacityCase) {
        let mut config = McpConfig::default();
        let result: Result<usize> = match case.field {
            "engine_cache_capacity" => {
                config.engine_cache_capacity = case.value;
                config.effective_engine_cache_capacity()
            }
            "discovery_cache_capacity" => {
                config.discovery_cache_capacity = case.value;
                config.effective_discovery_cache_capacity()
            }
            "trace_path_cache_capacity" => {
                config.trace_path_cache_capacity = case.value;
                config.effective_trace_path_cache_capacity()
            }
            "subgraph_cache_capacity" => {
                config.subgraph_cache_capacity = case.value;
                config.effective_subgraph_cache_capacity()
            }
            "query_cache_ttl_secs" => {
                config.query_cache_ttl_secs = case.value as u64;
                #[allow(clippy::cast_possible_truncation)] // Port number fits in u16
                config.effective_query_cache_ttl_secs().map(|v| v as usize)
            }
            _ => panic!("Unknown field: {}", case.field),
        };

        if case.expect_ok {
            assert!(
                result.is_ok(),
                "case '{}' should succeed but failed: {:?}",
                case.name,
                result.unwrap_err()
            );
            assert_eq!(
                result.unwrap(),
                case.expected_value,
                "case '{}' value mismatch",
                case.name
            );
        } else {
            assert!(
                result.is_err(),
                "case '{}' should fail but succeeded",
                case.name
            );
            let err = result.unwrap_err().to_string();
            assert!(
                err.contains(case.error_contains),
                "case '{}': expected error containing '{}', got '{}'",
                case.name,
                case.error_contains,
                err
            );
        }
    }

    #[test]
    #[allow(clippy::too_many_lines)] // Complex function kept cohesive
    fn test_cache_capacity_boundary_cases() {
        let cases = [
            // engine_cache_capacity: default=5, min=1 (no below_min distinct from zero), cap=1000
            CacheCapacityCase {
                name: "engine_default",
                field: "engine_cache_capacity",
                value: 5,
                expect_ok: true,
                expected_value: 5,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "engine_zero",
                field: "engine_cache_capacity",
                value: 0,
                expect_ok: false,
                expected_value: 0,
                error_contains: "cannot be 0",
            },
            CacheCapacityCase {
                name: "engine_at_cap",
                field: "engine_cache_capacity",
                value: 1000,
                expect_ok: true,
                expected_value: 1000,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "engine_above_cap",
                field: "engine_cache_capacity",
                value: 1001,
                expect_ok: false,
                expected_value: 0,
                error_contains: "exceeds absolute hard cap",
            },
            // discovery_cache_capacity: default=100, min=10, cap=10_000
            CacheCapacityCase {
                name: "discovery_default",
                field: "discovery_cache_capacity",
                value: 100,
                expect_ok: true,
                expected_value: 100,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "discovery_zero",
                field: "discovery_cache_capacity",
                value: 0,
                expect_ok: false,
                expected_value: 0,
                error_contains: "cannot be 0",
            },
            CacheCapacityCase {
                name: "discovery_below_min",
                field: "discovery_cache_capacity",
                value: 5,
                expect_ok: false,
                expected_value: 0,
                error_contains: "below minimum 10",
            },
            CacheCapacityCase {
                name: "discovery_at_cap",
                field: "discovery_cache_capacity",
                value: 10_000,
                expect_ok: true,
                expected_value: 10_000,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "discovery_above_cap",
                field: "discovery_cache_capacity",
                value: 10_001,
                expect_ok: false,
                expected_value: 0,
                error_contains: "exceeds absolute hard cap",
            },
            // trace_path_cache_capacity: default=256, min=16, cap=4096
            CacheCapacityCase {
                name: "trace_path_default",
                field: "trace_path_cache_capacity",
                value: 256,
                expect_ok: true,
                expected_value: 256,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "trace_path_zero",
                field: "trace_path_cache_capacity",
                value: 0,
                expect_ok: false,
                expected_value: 0,
                error_contains: "cannot be 0",
            },
            CacheCapacityCase {
                name: "trace_path_below_min",
                field: "trace_path_cache_capacity",
                value: 8,
                expect_ok: false,
                expected_value: 0,
                error_contains: "below minimum 16",
            },
            CacheCapacityCase {
                name: "trace_path_at_cap",
                field: "trace_path_cache_capacity",
                value: 4096,
                expect_ok: true,
                expected_value: 4096,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "trace_path_above_cap",
                field: "trace_path_cache_capacity",
                value: 4097,
                expect_ok: false,
                expected_value: 0,
                error_contains: "exceeds absolute hard cap",
            },
            // subgraph_cache_capacity: default=128, min=8, cap=2048
            CacheCapacityCase {
                name: "subgraph_cap_default",
                field: "subgraph_cache_capacity",
                value: 128,
                expect_ok: true,
                expected_value: 128,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "subgraph_cap_zero",
                field: "subgraph_cache_capacity",
                value: 0,
                expect_ok: false,
                expected_value: 0,
                error_contains: "cannot be 0",
            },
            CacheCapacityCase {
                name: "subgraph_cap_below_min",
                field: "subgraph_cache_capacity",
                value: 4,
                expect_ok: false,
                expected_value: 0,
                error_contains: "below minimum 8",
            },
            CacheCapacityCase {
                name: "subgraph_cap_at_cap",
                field: "subgraph_cache_capacity",
                value: 2048,
                expect_ok: true,
                expected_value: 2048,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "subgraph_cap_above_cap",
                field: "subgraph_cache_capacity",
                value: 2049,
                expect_ok: false,
                expected_value: 0,
                error_contains: "exceeds absolute hard cap",
            },
            // query_cache_ttl_secs: default=300, min=10, cap=86_400
            CacheCapacityCase {
                name: "ttl_default",
                field: "query_cache_ttl_secs",
                value: 300,
                expect_ok: true,
                expected_value: 300,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "ttl_zero",
                field: "query_cache_ttl_secs",
                value: 0,
                expect_ok: false,
                expected_value: 0,
                error_contains: "cannot be 0",
            },
            CacheCapacityCase {
                name: "ttl_below_min",
                field: "query_cache_ttl_secs",
                value: 5,
                expect_ok: false,
                expected_value: 0,
                error_contains: "below minimum 10",
            },
            CacheCapacityCase {
                name: "ttl_at_cap",
                field: "query_cache_ttl_secs",
                value: 86_400,
                expect_ok: true,
                expected_value: 86_400,
                error_contains: "",
            },
            CacheCapacityCase {
                name: "ttl_above_cap",
                field: "query_cache_ttl_secs",
                value: 86_401,
                expect_ok: false,
                expected_value: 0,
                error_contains: "exceeds absolute hard cap",
            },
        ];

        for case in &cases {
            apply_and_check(case);
        }
    }

    // --- Non-repetitive tests kept individually ---

    #[test]
    fn test_parse_env_var_valid() {
        let result = McpConfig::parse_env_var("5000", "TEST_VAR");
        assert_eq!(result.unwrap(), 5000);
    }

    #[test]
    fn test_parse_env_var_invalid() {
        let result = McpConfig::parse_env_var("abc", "TEST_VAR");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Invalid value for TEST_VAR")
        );
    }

    #[test]
    fn test_parse_env_var_negative() {
        let result = McpConfig::parse_env_var("-1000", "TEST_VAR");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid value"));
    }

    #[test]
    fn test_effective_timeout_warns_at_max() {
        let config = McpConfig {
            timeout_ms: 600_000,
            retry_delay_ms: 500,
            trace_cache_size: 256,
            subgraph_cache_size: 128,
            max_cross_lang_edges: 50_000,
            engine_cache_capacity: default_engine_cache_capacity(),
            discovery_cache_capacity: default_discovery_cache_capacity(),
            trace_path_cache_capacity: default_trace_path_cache_capacity(),
            subgraph_cache_capacity: default_subgraph_cache_capacity(),
            query_cache_ttl_secs: default_query_cache_ttl(),
            index_timeout_ms: default_index_timeout(),
            redaction_preset: default_redaction_preset(),
        };
        assert_eq!(config.effective_timeout_ms().unwrap(), 600_000);
    }

    #[test]
    fn test_effective_retry_delay_warns_at_max() {
        let config = McpConfig {
            timeout_ms: 30_000,
            retry_delay_ms: 30_000,
            trace_cache_size: 256,
            subgraph_cache_size: 128,
            max_cross_lang_edges: 50_000,
            engine_cache_capacity: default_engine_cache_capacity(),
            discovery_cache_capacity: default_discovery_cache_capacity(),
            trace_path_cache_capacity: default_trace_path_cache_capacity(),
            subgraph_cache_capacity: default_subgraph_cache_capacity(),
            query_cache_ttl_secs: default_query_cache_ttl(),
            index_timeout_ms: default_index_timeout(),
            redaction_preset: default_redaction_preset(),
        };
        assert_eq!(config.effective_retry_delay_ms().unwrap(), 30_000);
    }

    #[test]
    fn test_config_validation() {
        let config = McpConfig::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_index_timeout_default() {
        let config = McpConfig::default();
        assert_eq!(config.index_timeout_ms, 600_000);
    }

    #[test]
    fn test_effective_index_timeout_rejects_zero() {
        let mut config = McpConfig::default();
        config.index_timeout_ms = 0;
        assert!(config.effective_index_timeout_ms().is_err());
    }

    #[test]
    fn test_effective_index_timeout_rejects_below_minimum() {
        let mut config = McpConfig::default();
        config.index_timeout_ms = 1; // below MIN_TIMEOUT_MS (1000)
        assert!(config.effective_index_timeout_ms().is_err());
    }

    #[test]
    fn test_effective_index_timeout_rejects_over_hard_cap() {
        let mut config = McpConfig::default();
        config.index_timeout_ms = McpConfig::ABSOLUTE_MAX_TIMEOUT_MS + 1;
        assert!(config.effective_index_timeout_ms().is_err());
    }

    #[test]
    fn test_effective_index_timeout_accepts_valid() {
        let mut config = McpConfig::default();
        config.index_timeout_ms = 300_000;
        assert_eq!(config.effective_index_timeout_ms().unwrap(), 300_000);
    }
}