binscout 0.7.0

Headless, agent-first binary analysis: functions, CFGs, xrefs, strings, and IR over a JSON CLI or MCP server
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
//! binscout MCP server: 28 tools over a cached [`Project`].
//!
//! Every tool takes a `binary` path (plus optional `db` sidecar path), opens
//! the project, and returns one JSON document as text. Failures surface as
//! tool errors, never as silent empty results.
//!
//! Opens go through a small in-process LRU (`CACHE_CAPACITY` entries):
//! the first call for a binary pays the full open (file read, content hash,
//! analysis or sidecar replay) while repeat calls only stat the binary and
//! reuse the entry while its length and mtime agree. A changed file reopens
//! outside any lock and replaces the entry. Reads never save; the sidecar
//! is written solely by `load` and the annotation setters, exactly like
//! the CLI.
//!
//! Tool bodies are `async` and run the open inside
//! [`tokio::task::spawn_blocking`], so analysis never stalls the MCP event
//! loop. Only a brief map lookup plus one per-project [`Mutex`] guard the
//! cached entries, so different binaries open concurrently.

use std::collections::{HashMap, VecDeque};
use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::time::SystemTime;

use rmcp::ErrorData;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::{ServerHandler, tool, tool_handler, tool_router};

use crate::{FunctionFilter, Project, parse_addr, parse_xref_kind};

/// Explicit raw mapping for MCP binary-taking tools.
///
/// Mirrors the CLI `--raw --arch ARCH --base ADDR [--entry ADDR]` flags:
/// `arch`/`base` are required when `raw` is present, `entry` is optional,
/// and addresses parse as `0x`-hex or decimal via [`parse_addr`].
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct RawParams {
    /// Raw arch: `x86_64`, `x86_32`, `aarch64`, `arm32`, `thumb`.
    pub arch: Option<String>,
    /// Raw base address (`0x`-hex or decimal string).
    pub base: Option<String>,
    /// Raw entry address (`0x`-hex or decimal string).
    pub entry: Option<String>,
}

/// Max live projects in the in-process MCP cache: enough for an agent
/// comparing a couple of builds, small enough that idle entries cannot pile
/// up resident analysis. In-flight calls keep their `Arc` alive past
/// eviction, so eviction never invalidates a running query.
const CACHE_CAPACITY: usize = 4;

/// Identity of one cached project: canonical binary path, resolved sidecar
/// path, and loader mapping description. File identity (length plus mtime)
/// rides alongside in the entry and revalidates on every call, so an edited
/// binary reopens instead of serving stale analysis.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct CacheKey {
    /// Canonicalized binary path.
    binary: String,
    /// Explicit `db` path (canonicalized when it exists, absolutized
    /// otherwise) or the default sidecar of the canonical binary.
    db: String,
    /// Loader mapping ([`crate::db::StoredMapping::describe`]).
    mapping: String,
}

/// One cached open: validation file facts plus the project behind its own
/// lock. Sharing the handler shares the cache; each entry serializes its
/// own queries and read-modify-write annotations independently of the
/// other entries.
#[derive(Debug)]
struct ProjectEntry {
    /// Cache identity; never inserted for fallback opens that skipped the
    /// stat (missing binary: the open reports the error instead).
    key: CacheKey,
    /// Binary length at open time; a mismatch reopens.
    file_len: u64,
    /// Binary mtime at open time; a mismatch reopens.
    file_mtime: SystemTime,
    /// The open project. Mutations (rename/comment/import) hold this
    /// across their persist; queries hold it across row reads.
    project: Mutex<Project>,
}

impl ProjectEntry {
    /// Lock the project, tolerating a poisoned mutex: a panicked tool call
    /// must not wedge later calls on the same binary.
    fn lock_project(&self) -> MutexGuard<'_, Project> {
        self.project.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// In-memory-only entry for opens that skipped validation (the binary
    /// could not be statted, so no later call could match it anyway).
    fn ephemeral(project: Project) -> Self {
        Self {
            key: CacheKey {
                binary: String::new(),
                db: String::new(),
                mapping: String::new(),
            },
            file_len: 0,
            file_mtime: SystemTime::UNIX_EPOCH,
            project: Mutex::new(project),
        }
    }
}

/// In-process LRU over open projects, shared by every tool call served by
/// one `binscout-mcp` process. The map lock is held only for pointer
/// manipulations, never across file I/O or analysis.
#[derive(Debug, Default)]
struct ProjectCache {
    /// Entries plus MRU-first key order.
    state: Mutex<CacheState>,
}

/// Map plus recency order behind [`ProjectCache::state`].
#[derive(Debug, Default)]
struct CacheState {
    /// Live entries by identity.
    entries: HashMap<CacheKey, Arc<ProjectEntry>>,
    /// Key recency, most-recently-used first.
    order: VecDeque<CacheKey>,
}

impl ProjectCache {
    /// Return the entry when the key is cached and the file facts still
    /// match, refreshing its recency. A length/mtime mismatch returns
    /// `None` so the caller reopens and replaces the entry; the stale
    /// entry stays valid for calls already holding it.
    fn lookup(&self, key: &CacheKey, len: u64, mtime: SystemTime) -> Option<Arc<ProjectEntry>> {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        let entry = state.entries.get(key)?.clone();
        if entry.file_len != len || entry.file_mtime != mtime {
            return None;
        }
        if let Some(pos) = state.order.iter().position(|k| k == key) {
            state.order.remove(pos);
        }
        state.order.push_front(key.clone());
        Some(entry)
    }

    /// Insert an entry, replacing the same key or evicting
    /// least-recently-used entries past [`CACHE_CAPACITY`].
    fn insert(&self, entry: Arc<ProjectEntry>) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(pos) = state.order.iter().position(|k| k == &entry.key) {
            state.order.remove(pos);
        }
        state.order.push_front(entry.key.clone());
        state.entries.insert(entry.key.clone(), entry);
        while state.entries.len() > CACHE_CAPACITY {
            match state.order.pop_back() {
                Some(old) => {
                    state.entries.remove(&old);
                }
                None => break,
            }
        }
    }
}

/// Join failure of a blocking open: the analysis thread itself never
/// returns this, only a cancelled runtime does.
fn join_error(e: tokio::task::JoinError) -> ErrorData {
    ErrorData::internal_error(format!("background open failed: {e}"), None)
}

/// Resolve an explicit `db` string for cache identity: canonicalized when
/// the file exists, else its canonicalized parent plus the file name.
/// Best-effort: distinct spellings of one path only cost a duplicate
/// entry, never a wrong one.
///
/// Parent canonicalization (not just absolutization) keeps the key
/// stable across sidecar creation: the pre-creation key must equal the
/// post-creation canonical path, or one file would fork into two cache
/// keys — and two handle mutexes, breaking the single-handle guarantee.
/// (`/tmp` on macOS is a symlink, so a plain absolute path is not
/// stable.) When even the parent is unresolvable the open itself will
/// fail, so any stable string does.
fn resolve_db_str(db: &str) -> String {
    if let Ok(canonical) = std::fs::canonicalize(db) {
        return canonical.display().to_string();
    }
    let path = Path::new(db);
    if let (Some(parent), Some(file)) = (path.parent(), path.file_name())
        && let Ok(canon_parent) = std::fs::canonicalize(parent)
    {
        return canon_parent.join(file).display().to_string();
    }
    if path.is_absolute() {
        return db.to_string();
    }
    match std::env::current_dir() {
        Ok(cwd) => {
            let base = std::fs::canonicalize(&cwd).unwrap_or(cwd);
            base.join(path).display().to_string()
        }
        Err(_) => db.to_string(),
    }
}

/// Shared validated opener: explicit `db` path (or the default sidecar),
/// the optional explicit raw mapping, and the optional fat Mach-O slice
/// selection, parsed through [`crate::parse_raw_options`] so CLI and MCP
/// interpret options identically. Never saves; see [`Project::save`].
fn open_uncached(
    binary: &str,
    db: Option<&str>,
    raw_opts: Option<crate::loader::RawOptions>,
    fat_arch: Option<&str>,
) -> Result<Project, ErrorData> {
    let db_path;
    let db_ref = match db {
        Some(d) => {
            db_path = Path::new(d).to_path_buf();
            Some(db_path.as_path())
        }
        None => None,
    };
    crate::open_mapped(Path::new(binary), db_ref, raw_opts, fat_arch).map_err(|e| match e {
        crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
        other => ErrorData::internal_error(other.to_string(), None),
    })
}

/// Parse an MCP `raw` object through the shared CLI/MCP validator.
fn raw_options(raw: Option<&RawParams>) -> Result<Option<crate::loader::RawOptions>, ErrorData> {
    let (present, arch, base, entry) = match raw {
        None => (false, None, None, None),
        Some(r) => (
            true,
            r.arch.as_deref(),
            r.base.as_deref(),
            r.entry.as_deref(),
        ),
    };
    crate::parse_raw_options(present, arch, base, entry).map_err(|e| match e {
        crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
        other => ErrorData::internal_error(other.to_string(), None),
    })
}

fn ok(value: serde_json::Value) -> Result<String, ErrorData> {
    serde_json::to_string(&value)
        .map_err(|e| ErrorData::internal_error(format!("serialize result: {e}"), None))
}

fn opt_addr(s: Option<String>) -> Result<Option<u64>, ErrorData> {
    s.map(|v| parse_addr(&v))
        .transpose()
        .map_err(|e| ErrorData::invalid_params(e.to_string(), None))
}

fn all_params<T>(p: Parameters<T>) -> T {
    p.0
}

/// Parameters for single-binary tools (`project_info`, `symbols`, `sections`, `stats`).
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BinaryParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping (`arch`/`base` required, `entry` optional).
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
}

/// Parameters for the `strings` tool: filtered, paged string search.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct StringsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Rows to skip after filtering.
    pub start: Option<usize>,
    /// Deprecated alias of `start`.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
    /// Case-sensitive substring, or `regex:`-prefixed expression.
    pub pattern: Option<String>,
    /// Keep strings with at least this many characters.
    pub min_len: Option<usize>,
    /// Keep strings in exactly this section (e.g. `.rdata`).
    pub section: Option<String>,
    /// Show strings in executable memory (hidden by default).
    pub include_code: Option<bool>,
    /// Decode-and-display view over an in-memory transform: `xor:<byte>`,
    /// `add:<byte>`, or `rot:<0-7>` (byte is `0x`-hex or decimal). Reveals
    /// single-byte-obfuscated text with original offsets; never writes the
    /// binary.
    pub decode: Option<String>,
}

/// Parameters for the `functions` tool: paged list with optional filters.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct FunctionsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Case-insensitive substring over the rename-resolved name.
    pub query: Option<String>,
    /// Keep functions that call the function containing this address.
    pub caller: Option<String>,
    /// Keep functions called by the function containing this address.
    pub callee: Option<String>,
    /// Keep functions with entry at or above this address (needs range_hi).
    pub range_lo: Option<String>,
    /// Keep functions with entry at or below this address (needs range_lo).
    pub range_hi: Option<String>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for single-address tools (`func`, `cfg`, `blocks`, `comment`).
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct AddrParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Virtual address (`0x`-hex or decimal string).
    pub addr: String,
}

/// Parameters for the `blocks` tool: one function's block summaries, paged.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BlocksParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Function address: any address inside the function snaps to its
    /// containing entry.
    pub addr: String,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `block_insns` tool: one block's instructions, paged.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BlockInsnsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Function address: any address inside the function snaps to its
    /// containing entry.
    pub addr: String,
    /// Block start address; must belong to the containing function.
    pub block: String,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `diagnostics` tool: paged provenance records.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DiagnosticsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Only `unresolved-indirect-jump`, `unresolved-indirect-call`, or
    /// `decode-failure` sites.
    pub kind: Option<String>,
    /// Only sites in the function containing this address (`0x`-hex or
    /// decimal string).
    pub func: Option<String>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for byte-range tools (`disasm`, `ir`).
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RangeParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Virtual address (`0x`-hex or decimal string).
    pub addr: String,
    /// Bytes to decode.
    pub len: usize,
}

/// Parameters for the `xrefs` tool.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct XrefsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Only xrefs pointing at this address (`0x`-hex or decimal).
    pub to: Option<String>,
    /// Only xrefs originating at this address.
    pub from: Option<String>,
    /// Only `code`, `data`, `string`, `import`, or `inferred-code` xrefs.
    pub kind: Option<String>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `ir_coverage` tool: arch-only coverage, or coverage
/// plus per-range accounting when `binary`/`addr`/`len` are all given.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct IrCoverageParams {
    /// Coverage arch: `x86_64`, `x86_32`, `aarch64`, `arm32`, `thumb`.
    pub arch: String,
    /// Path to the analyzed binary (needs `addr` and `len` for a range).
    pub binary: Option<String>,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Range address (`0x`-hex or decimal string; needs `binary` and `len`).
    pub addr: Option<String>,
    /// Range length in bytes (needs `binary` and `addr`).
    pub len: Option<usize>,
}

/// Parameters for the `rename` tool.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RenameParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Function entry address (`0x`-hex or decimal string).
    pub addr: String,
    /// New name (empty string clears).
    pub name: String,
}

/// Parameters for the `comment` tool.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CommentParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Address to comment (`0x`-hex or decimal string).
    pub addr: String,
    /// Comment text (empty string clears).
    pub comment: String,
}

/// Parameters for the `search_bytes` tool: bounded byte-pattern search.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct SearchBytesParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Whitespace-separated full-byte tokens: two hex digits or `??`.
    pub pattern: String,
    /// Keep matches fully inside this section (e.g. `.text`).
    pub section: Option<String>,
    /// Range start (`0x`-hex or decimal, needs range_end).
    pub range_start: Option<String>,
    /// Range end (`0x`-hex or decimal, needs range_start).
    pub range_end: Option<String>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `callees`/`callers` tools: depth-bounded transitive
/// callgraph reachability, paged under the protocol-1 envelope.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CallgraphParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Query address: any address inside the root function snaps to its
    /// containing entry.
    pub addr: String,
    /// Max call edges from the root (direct neighbors are depth 1;
    /// defaults to the 64-hop cap).
    pub depth: Option<usize>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `slice` tool: depth-bounded backward reachability
/// to one address, paged under the protocol-1 envelope.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct SliceParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Slice root: every returned instruction can reach this address
    /// (`0x`-hex or decimal string; any address is valid, including
    /// data/string targets in no function).
    pub addr: String,
    /// Max reverse hops from the root (direct predecessors are depth 1;
    /// defaults to the 64-hop cap).
    pub depth: Option<usize>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `annotations_import` tool: merge a portable document.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct AnnotationsImportParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Interchange document, as returned by `annotations_export`.
    pub document: String,
    /// Replace supplied fields on conflict instead of failing.
    pub overwrite: Option<bool>,
}

/// Parameters for the `flirt_hints` tool: read-only library-idiom hints.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct FlirtHintsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Optional explicit raw mapping.
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection (canonical `x86_64`/`x86_32`/`aarch64`/`arm32`
    /// or a `lipo` alias like `arm64`); required for fat containers.
    pub fat_arch: Option<String>,
    /// Only hints for the function containing this address (`0x`-hex or
    /// decimal string).
    pub addr: Option<String>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `diff` tool: function-level diff between two binaries.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DiffParams {
    /// Path of the first (baseline) binary.
    pub binary_a: String,
    /// Path of the second (new) binary.
    pub binary_b: String,
    /// Explicit project DB path for side A.
    pub db_a: Option<String>,
    /// Explicit project DB path for side B.
    pub db_b: Option<String>,
    /// Optional explicit raw mapping, applied to both binaries (the
    /// two-builds case shares one mapping).
    pub raw: Option<RawParams>,
    /// Fat Mach-O slice selection, applied to both binaries (the two-builds
    /// case shares one selection); required for fat containers.
    pub fat_arch: Option<String>,
}

/// MCP server handler; tools share one project cache.
///
/// The cache lock is held only for map manipulations: opens run outside
/// any lock (in `spawn_blocking`), and each cached project carries its own
/// [`Mutex`], so calls on different binaries proceed concurrently while
/// calls on one binary serialize. `redb` handles are never held across
/// calls — every sidecar open/save reopens its file under that file's
/// handle mutex (see the `db_locks` field), so the single-handle rule
/// holds without a global call lock.
#[derive(Debug, Clone, Default)]
pub struct BinscoutMcp {
    /// In-process LRU over open projects (see [`ProjectCache`]).
    cache: Arc<ProjectCache>,
    /// One mutex per sidecar path, shared by every entry that names it.
    ///
    /// `redb` enforces a single open handle per file per process with an
    /// OS file lock: a second open while a writable handle lives fails
    /// with `DatabaseAlreadyOpen`. Every window holding a sidecar handle —
    /// miss opens (read-only) and annotation persists/saves (writable) —
    /// runs under the file's mutex, so same-sidecar calls serialize while
    /// different sidecars proceed concurrently. Weak refs so idle files
    /// release their mutex; any spelling that resolves to one path shares
    /// one mutex through [`resolve_db_str`].
    db_locks: Arc<Mutex<HashMap<String, Weak<Mutex<()>>>>>,
}

impl BinscoutMcp {
    /// New handler with a fresh project cache.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Mutex serializing sidecar-handle windows for one resolved `db` path
    /// (see the [`BinscoutMcp::db_locks`] field docs). Shared by opens and
    /// persists; always taken before the entry lock, never after.
    fn db_lock(&self, db: &str) -> Arc<Mutex<()>> {
        let mut locks = self.db_locks.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(live) = locks.get(db).and_then(Weak::upgrade) {
            return live;
        }
        let live = Arc::new(Mutex::new(()));
        locks.insert(db.to_string(), Arc::downgrade(&live));
        locks.retain(|_, w| w.strong_count() > 0);
        live
    }

    /// Cache identity plus validation facts for one open request, or `None`
    /// when the binary cannot be statted: the open path then runs uncached
    /// so it reports the canonical error.
    fn cache_key(
        binary: &str,
        db: Option<&str>,
        raw_opts: Option<crate::loader::RawOptions>,
        fat_arch: Option<&str>,
    ) -> Result<Option<(CacheKey, u64, SystemTime)>, ErrorData> {
        let bin_path = Path::new(binary);
        let (meta, canonical) = match (std::fs::metadata(bin_path), std::fs::canonicalize(bin_path))
        {
            (Ok(meta), Ok(canonical)) => (meta, canonical),
            _ => return Ok(None),
        };
        let mtime = match meta.modified() {
            Ok(t) => t,
            Err(_) => return Ok(None),
        };
        let mapping = match (raw_opts, fat_arch) {
            (Some(_), Some(_)) => {
                return Err(ErrorData::invalid_params(
                    "--raw and --fat-arch are exclusive (or MCP raw with fat_arch)",
                    None,
                ));
            }
            (Some(opts), None) => crate::db::StoredMapping::for_request(Some(opts)),
            (None, Some(arch)) => crate::db::StoredMapping::for_fat_slice(arch),
            (None, None) => crate::db::StoredMapping::for_request(None),
        };
        let db_str = match db {
            Some(d) => resolve_db_str(d),
            None => format!("{}.rsdbg.redb", canonical.display()),
        };
        Ok(Some((
            CacheKey {
                binary: canonical.display().to_string(),
                db: db_str,
                mapping: mapping.describe(),
            },
            meta.len(),
            mtime,
        )))
    }

    /// Open through the cache: a length/mtime-validated hit returns the
    /// live entry, otherwise the binary opens outside any lock and the
    /// result replaces the entry. Synchronous file I/O and analysis: call
    /// from `spawn_blocking` via [`BinscoutMcp::open_owned`].
    fn cached_entry(
        &self,
        binary: &str,
        db: Option<&str>,
        raw: Option<&RawParams>,
        fat_arch: Option<&str>,
    ) -> Result<Arc<ProjectEntry>, ErrorData> {
        let raw_opts = raw_options(raw)?;
        let keyed = Self::cache_key(binary, db, raw_opts, fat_arch)?;
        let Some((key, len, mtime)) = keyed else {
            return Ok(Arc::new(ProjectEntry::ephemeral(open_uncached(
                binary, db, raw_opts, fat_arch,
            )?)));
        };
        if let Some(hit) = self.cache.lookup(&key, len, mtime) {
            return Ok(hit);
        }
        // The sidecar read inside the open holds a handle, so it runs under
        // the file mutex; analysis itself needs no lock and concurrent
        // misses on other files proceed.
        let db_mutex = self.db_lock(&key.db);
        let _db_guard = db_mutex.lock().unwrap_or_else(|e| e.into_inner());
        let project = open_uncached(binary, db, raw_opts, fat_arch)?;
        // Re-stat so the stored facts describe the opened bytes; when the
        // file changed mid-open (or vanished) the entry stays ephemeral and
        // the next call revalidates from scratch.
        let entry = match Self::cache_key(binary, db, raw_opts, fat_arch)? {
            Some((_, fresh_len, fresh_mtime)) => {
                let entry = Arc::new(ProjectEntry {
                    key,
                    file_len: fresh_len,
                    file_mtime: fresh_mtime,
                    project: Mutex::new(project),
                });
                self.cache.insert(entry.clone());
                entry
            }
            None => Arc::new(ProjectEntry::ephemeral(project)),
        };
        Ok(entry)
    }

    /// Async entry point for every binary-taking tool: the open (file
    /// read, hash, analysis or sidecar replay) runs on the blocking pool
    /// while the caller only awaits the `Arc`. Queries then run inline
    /// under the entry lock: row reads plus serialization, no I/O.
    async fn open_owned(
        &self,
        binary: String,
        db: Option<String>,
        raw: Option<RawParams>,
        fat_arch: Option<String>,
    ) -> Result<Arc<ProjectEntry>, ErrorData> {
        let this = self.clone();
        tokio::task::spawn_blocking(move || {
            this.cached_entry(&binary, db.as_deref(), raw.as_ref(), fat_arch.as_deref())
        })
        .await
        .map_err(join_error)?
    }
}

#[tool_handler(
    name = "binscout-mcp",
    instructions = "Headless agent-first binary analysis. Every tool takes a binary path and returns one JSON document as text."
)]
impl ServerHandler for BinscoutMcp {}

#[tool_router]
impl BinscoutMcp {
    #[tool(
        name = "project_info",
        description = "Open a binary and report arch, format, entry, and analysis counts"
    )]
    async fn project_info(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        ok(serde_json::to_value(proj.project_info()).expect("project_info serializes"))
    }

    #[tool(
        name = "load",
        description = "Open a binary and persist the analysis snapshot to the project DB (binary untouched); CLI `load` parity, warms the sidecar so later opens replay it instead of re-analyzing"
    )]
    async fn load(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let db_mutex = self.db_lock(&entry.key.db);
        let _db_guard = db_mutex.lock().unwrap_or_else(|e| e.into_inner());
        let proj = entry.lock_project();
        proj.save()
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
        ok(serde_json::to_value(proj.project_info()).expect("project_info serializes"))
    }

    #[tool(
        name = "functions",
        description = "List functions with rename-resolved names, filtered by query/caller/callee/range, paged by offset/limit"
    )]
    async fn functions(&self, p: Parameters<FunctionsParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        // Cloned before the move into the open so filter errors keep their
        // post-open precedence (a missing binary still reports first).
        let (query, caller, callee, range_lo, range_hi, offset, limit) = (
            p.query.clone(),
            p.caller.clone(),
            p.callee.clone(),
            p.range_lo.clone(),
            p.range_hi.clone(),
            p.offset,
            p.limit,
        );
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let filter = FunctionFilter {
            query,
            caller: opt_addr(caller)?,
            callee: opt_addr(callee)?,
            range: match (range_lo, range_hi) {
                (None, None) => None,
                (Some(lo), Some(hi)) => Some((
                    parse_addr(&lo).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
                    parse_addr(&hi).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
                )),
                _ => {
                    return Err(ErrorData::invalid_params(
                        "range_lo and range_hi must be given together",
                        None,
                    ));
                }
            },
        };
        let rows = proj.functions_filtered(&filter, offset.unwrap_or(0), limit.unwrap_or(50));
        ok(serde_json::Value::Array(rows))
    }

    #[tool(
        name = "func",
        description = "Compact metadata of one function: entry, name, and block/insn/call counts. Any address inside the function snaps to its containing entry"
    )]
    async fn func(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let addr_s = p.addr.clone();
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.func_meta(addr)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(|m| ok(serde_json::to_value(m).expect("func_meta serializes")))
    }

    #[tool(
        name = "blocks",
        description = "Block summaries of one function ordered by block start, paged with total block count. Any address inside the function snaps to its containing entry"
    )]
    async fn blocks(&self, p: Parameters<BlocksParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, offset, limit) = (p.addr.clone(), p.offset, p.limit);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.func_blocks_page(addr, offset.unwrap_or(0), limit.unwrap_or(50))
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(|page| ok(serde_json::to_value(page).expect("blocks page serializes")))
    }

    #[tool(
        name = "block_insns",
        description = "Instructions of one function-owned block in address order, paged. Addr snaps to its containing function; block must be a block start belonging to that function"
    )]
    async fn block_insns(&self, p: Parameters<BlockInsnsParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, block_s, offset, limit) = (p.addr.clone(), p.block.clone(), p.offset, p.limit);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        let block =
            parse_addr(&block_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.func_block_insns_page(addr, block, offset.unwrap_or(0), limit.unwrap_or(50))
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(|page| ok(serde_json::to_value(page).expect("block_insns page serializes")))
    }

    #[tool(
        name = "diagnostics",
        description = "Analysis provenance: unresolved indirect sites and decode failures, filtered by kind and containing function, paged under the protocol-1 envelope"
    )]
    async fn diagnostics(&self, p: Parameters<DiagnosticsParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (kind_s, func_s, offset, limit) = (p.kind.clone(), p.func.clone(), p.offset, p.limit);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let kind = kind_s
            .as_deref()
            .map(crate::parse_diagnostic_kind)
            .transpose()
            .map_err(|e| match e {
                crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
                other => ErrorData::internal_error(other.to_string(), None),
            })?;
        let func = opt_addr(func_s)?;
        proj.query_diagnostics(kind, func, offset.unwrap_or(0), limit.unwrap_or(50))
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(|page| ok(serde_json::to_value(page).expect("diagnostics page serializes")))
    }

    #[tool(
        name = "disasm",
        description = "Disassemble len bytes at addr with the binary architecture; returns the valid prefix plus error_at for the first bad opcode (null on a clean range)"
    )]
    async fn disasm(&self, p: Parameters<RangeParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, len) = (p.addr.clone(), p.len);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.disasm_at(addr, len)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(|v| ok(serde_json::to_value(v).expect("partial disasm serializes")))
    }

    #[tool(
        name = "cfg",
        description = "Control-flow graph of one function: block nodes plus block edges. Any address inside the function snaps to its containing entry"
    )]
    async fn cfg(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let addr_s = p.addr.clone();
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.cfg_of(addr)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(ok)
    }

    #[tool(
        name = "structure",
        description = "Approximate control-flow structure of one function: syntactic loops (back-edge headers with latches) and ifs (two-successor branch sites with then/else targets) plus an approximation warning. Any address inside the function snaps to its containing entry"
    )]
    async fn structure(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let addr_s = p.addr.clone();
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.structure_of(addr)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(ok)
    }

    #[tool(
        name = "pseudo",
        description = "Approximate pseudo-C of one function: one lossy C-like line per IR row plus assembled text, with an approximation warning. Any address inside the function snaps to its containing entry"
    )]
    async fn pseudo(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let addr_s = p.addr.clone();
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.pseudo_of(addr)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(ok)
    }

    #[tool(
        name = "callees",
        description = "Transitive callees of one function out to depth hops (direct callees are depth 1), ordered by entry with shortest distance, paged under the protocol-1 envelope. Addr snaps to its containing function"
    )]
    async fn callees(&self, p: Parameters<CallgraphParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, depth, offset, limit) = (p.addr.clone(), p.depth, p.offset, p.limit);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.callees_page(
            addr,
            depth.unwrap_or(crate::analysis::MAX_CALL_DEPTH),
            offset.unwrap_or(0),
            limit.unwrap_or(50),
        )
        .map_err(|e| match e {
            crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
            other => ErrorData::internal_error(other.to_string(), None),
        })
        .and_then(|page| ok(serde_json::to_value(page).expect("callees page serializes")))
    }

    #[tool(
        name = "callers",
        description = "Transitive callers of one function out to depth hops (direct callers are depth 1), ordered by entry with shortest distance, paged under the protocol-1 envelope. Addr snaps to its containing function"
    )]
    async fn callers(&self, p: Parameters<CallgraphParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, depth, offset, limit) = (p.addr.clone(), p.depth, p.offset, p.limit);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.callers_page(
            addr,
            depth.unwrap_or(crate::analysis::MAX_CALL_DEPTH),
            offset.unwrap_or(0),
            limit.unwrap_or(50),
        )
        .map_err(|e| match e {
            crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
            other => ErrorData::internal_error(other.to_string(), None),
        })
        .and_then(|page| ok(serde_json::to_value(page).expect("callers page serializes")))
    }

    #[tool(
        name = "slice",
        description = "Backward slice of one address: every instruction that can reach it via xref edges (any kind) and intra-function CFG predecessors, out to depth hops (direct predecessors are depth 1), ordered by address with shortest distance, paged under the protocol-1 envelope. Any address is a valid root"
    )]
    async fn slice(&self, p: Parameters<SliceParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, depth, offset, limit) = (p.addr.clone(), p.depth, p.offset, p.limit);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.slice_page(
            addr,
            depth.unwrap_or(crate::analysis::MAX_SLICE_DEPTH),
            offset.unwrap_or(0),
            limit.unwrap_or(50),
        )
        .map_err(|e| match e {
            crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
            other => ErrorData::internal_error(other.to_string(), None),
        })
        .and_then(|page| ok(serde_json::to_value(page).expect("slice page serializes")))
    }

    #[tool(
        name = "xrefs",
        description = "Cross-references filtered by to/from address and kind, paged with total match count"
    )]
    async fn xrefs(&self, p: Parameters<XrefsParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (kind_s, to_s, from_s, offset, limit) = (
            p.kind.clone(),
            p.to.clone(),
            p.from.clone(),
            p.offset,
            p.limit,
        );
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let kind = kind_s
            .as_deref()
            .map(parse_xref_kind)
            .transpose()
            .map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        let (to, from) = (opt_addr(to_s)?, opt_addr(from_s)?);
        let total = proj.count_xrefs(to, from, kind);
        let rows = proj.query_xrefs(to, from, kind, offset.unwrap_or(0), limit.unwrap_or(50));
        ok(serde_json::json!({ "total": total, "xrefs": rows }))
    }

    #[tool(
        name = "strings",
        description = "Extracted strings ordered by address, filtered by pattern/min-len/section, paged by start/limit. Hits in executable memory are hidden unless pattern, section, or include_code is given. Decode renders a read-only single-byte-obfuscated view: xor:<byte>, add:<byte>, or rot:<0-7>"
    )]
    async fn strings(&self, p: Parameters<StringsParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        if p.offset.is_some() {
            eprintln!("warning: strings offset is deprecated, use start");
        }
        let decode = p
            .decode
            .as_deref()
            .map(crate::loader::strings::parse_decode_spec)
            .transpose()
            .map_err(|e| match e {
                crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
                other => ErrorData::internal_error(other.to_string(), None),
            })?;
        // Cloned before the move into the open; the decode error above keeps
        // its pre-open precedence.
        let (pattern, min_len, section, include_code, start, offset, limit) = (
            p.pattern.clone(),
            p.min_len,
            p.section.clone(),
            p.include_code,
            p.start,
            p.offset,
            p.limit,
        );
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let filter = crate::analysis::StringsFilter {
            pattern,
            min_len,
            section,
            include_code: include_code.unwrap_or(false),
            start: start.or(offset).unwrap_or(0),
            limit: limit.unwrap_or(50),
        };
        let rows = match decode {
            Some(spec) => proj.query_strings_decoded(&filter, spec),
            None => proj.query_strings(&filter),
        }
        .map_err(|e| match e {
            crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
            other => ErrorData::internal_error(other.to_string(), None),
        })?;
        ok(serde_json::to_value(rows).expect("strings serialize"))
    }

    #[tool(
        name = "symbols",
        description = "Imports, exports, and symbol-table code addresses of the binary"
    )]
    async fn symbols(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        ok(entry.lock_project().symbols_json())
    }

    #[tool(
        name = "stats",
        description = "Storage stats: binary size, sidecar DB size, and analysis counts"
    )]
    async fn stats(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        entry
            .lock_project()
            .stats_json()
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(ok)
    }

    #[tool(
        name = "sections",
        description = "Section table: name, virtual address (PE: IMAGE_BASE + RVA), in-memory and file sizes, permissions"
    )]
    async fn sections(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        ok(entry.lock_project().sections_json())
    }

    #[tool(
        name = "ir",
        description = "Lift len bytes at addr to P-code-inspired IR"
    )]
    async fn ir(&self, p: Parameters<RangeParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, len) = (p.addr.clone(), p.len);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.ir_at(addr, len)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(ok)
    }

    #[tool(
        name = "ir_coverage",
        description = "Machine-readable IR lift coverage for one arch (implemented families, partial mappings, limitations); with binary/addr/len adds per-range decoded/lifted/unlifted counts from actual lifts plus a bounded mnemonic summary"
    )]
    async fn ir_coverage(&self, p: Parameters<IrCoverageParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let arch = crate::parse_raw_arch(&p.arch)
            .map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        match (p.binary, p.addr, p.len) {
            (None, None, None) => ok(crate::ir_coverage(arch)),
            (Some(binary), Some(addr_s), Some(len)) => {
                let entry = self.open_owned(binary, p.db, p.raw, p.fat_arch).await?;
                let proj = entry.lock_project();
                let addr = parse_addr(&addr_s)
                    .map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
                proj.ir_coverage_at(arch, addr, len)
                    .map_err(|e| match e {
                        crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
                        other => ErrorData::internal_error(other.to_string(), None),
                    })
                    .and_then(ok)
            }
            _ => Err(ErrorData::invalid_params(
                "ir_coverage range needs binary, addr, and len together",
                None,
            )),
        }
    }

    #[tool(
        name = "rename",
        description = "Rename a function in the project DB (binary untouched); empty name clears"
    )]
    async fn rename(&self, p: Parameters<RenameParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, name) = (p.addr.clone(), p.name.clone());
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let db_mutex = self.db_lock(&entry.key.db);
        let _db_guard = db_mutex.lock().unwrap_or_else(|e| e.into_inner());
        let mut proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.rename_function(addr, &name)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
        ok(proj.annotation_json(addr))
    }

    #[tool(
        name = "comment",
        description = "Comment any address in the project DB (binary untouched); empty comment clears"
    )]
    async fn comment(&self, p: Parameters<CommentParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, comment) = (p.addr.clone(), p.comment.clone());
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let db_mutex = self.db_lock(&entry.key.db);
        let _db_guard = db_mutex.lock().unwrap_or_else(|e| e.into_inner());
        let mut proj = entry.lock_project();
        let addr =
            parse_addr(&addr_s).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.set_comment(addr, &comment)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
        ok(proj.annotation_json(addr))
    }

    #[tool(
        name = "search_bytes",
        description = "Search mapped file bytes for a whitespace-separated hex pattern (two hex digits or ?? per token), filtered by section/range, paged with total match count"
    )]
    async fn search_bytes(&self, p: Parameters<SearchBytesParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (pattern, section, range_start, range_end, offset, limit) = (
            p.pattern.clone(),
            p.section.clone(),
            p.range_start.clone(),
            p.range_end.clone(),
            p.offset,
            p.limit,
        );
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let range = match (range_start, range_end) {
            (None, None) => None,
            (Some(lo), Some(hi)) => Some((
                parse_addr(&lo).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
                parse_addr(&hi).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
            )),
            _ => {
                return Err(ErrorData::invalid_params(
                    "range_start and range_end must be given together",
                    None,
                ));
            }
        };
        proj.search_bytes(
            &pattern,
            section.as_deref(),
            range,
            offset.unwrap_or(0),
            limit.unwrap_or(50),
        )
        .map_err(|e| match e {
            crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
            other => ErrorData::internal_error(other.to_string(), None),
        })
        .and_then(|page| ok(serde_json::to_value(page).expect("search_bytes page serializes")))
    }

    #[tool(
        name = "annotations_export",
        description = "Emit the portable annotation interchange document (revision, sha256, size, mapping, sorted rows); read-only, never creates or modifies the sidecar"
    )]
    async fn annotations_export(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let doc = proj
            .export_annotations()
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
        serde_json::from_str::<serde_json::Value>(&doc)
            .map_err(|e| {
                ErrorData::internal_error(format!("encode annotation document: {e}"), None)
            })
            .and_then(ok)
    }

    #[tool(
        name = "annotations_import",
        description = "Atomically merge a portable annotation document into the project DB; returns row/change counts. Default fails on conflicting fields, overwrite replaces supplied fields only"
    )]
    async fn annotations_import(
        &self,
        p: Parameters<AnnotationsImportParams>,
    ) -> Result<String, ErrorData> {
        let p = all_params(p);
        // Cloned before the move into the open so the transport note below
        // still holds: validation happens after the open, inside the entry
        // lock, before any write.
        let (document, overwrite) = (p.document.clone(), p.overwrite);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let db_mutex = self.db_lock(&entry.key.db);
        let _db_guard = db_mutex.lock().unwrap_or_else(|e| e.into_inner());
        let mut proj = entry.lock_project();
        // Transport note: rmcp delivers `document` as a fully-materialized
        // `String` before this runs, so no pre-parse cap exists at this
        // layer; the core re-checks the 16 MiB serialized cap plus row/text
        // budgets during validation, before any write, and every failure
        // leaves the DB and memory unchanged.
        proj.import_annotations(&document, overwrite.unwrap_or(false))
            .map_err(|e| match e {
                crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
                other => ErrorData::internal_error(other.to_string(), None),
            })
            .and_then(|s| ok(serde_json::json!({"rows": s.rows, "changed": s.changed})))
    }

    #[tool(
        name = "flirt_hints",
        description = "FLIRT-like library hints: corpus signature matches over each function's leading bytes, paged under the protocol-1 envelope. Suggested names stay hints; read-only, never renames or writes the sidecar"
    )]
    async fn flirt_hints(&self, p: Parameters<FlirtHintsParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        let (addr_s, offset, limit) = (p.addr.clone(), p.offset, p.limit);
        let entry = self.open_owned(p.binary, p.db, p.raw, p.fat_arch).await?;
        let proj = entry.lock_project();
        let addr = opt_addr(addr_s)?;
        proj.query_flirt_hints(addr, offset.unwrap_or(0), limit.unwrap_or(50))
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(|page| ok(serde_json::to_value(page).expect("flirt hints page serializes")))
    }

    #[tool(
        name = "diff",
        description = "Function-level diff between two binaries: byte-identical pairs are matched, content-matched pairs are changed (with the match reason), the rest is added (only in B) / removed (only in A). Both projects open read-only, never creating or modifying a sidecar"
    )]
    async fn diff(&self, p: Parameters<DiffParams>) -> Result<String, ErrorData> {
        let p = all_params(p);
        raw_options(p.raw.as_ref())?;
        // Both sides open concurrently on the blocking pool; each lands on
        // its own cache entry (same binary twice shares one). Guards take
        // in pointer order below, so opposite-side concurrent diffs cannot
        // deadlock.
        let (entry_a, entry_b) = tokio::join!(
            self.open_owned(
                p.binary_a.clone(),
                p.db_a.clone(),
                p.raw.clone(),
                p.fat_arch.clone(),
            ),
            self.open_owned(
                p.binary_b.clone(),
                p.db_b.clone(),
                p.raw.clone(),
                p.fat_arch.clone(),
            )
        );
        let (entry_a, entry_b) = (entry_a?, entry_b?);
        if Arc::ptr_eq(&entry_a, &entry_b) {
            let proj = entry_a.lock_project();
            let report = crate::diff::diff_projects(&proj, &proj);
            ok(serde_json::to_value(report).expect("diff report serializes"))
        } else if Arc::as_ptr(&entry_a) < Arc::as_ptr(&entry_b) {
            let a = entry_a.lock_project();
            let b = entry_b.lock_project();
            let report = crate::diff::diff_projects(&a, &b);
            ok(serde_json::to_value(report).expect("diff report serializes"))
        } else {
            let b = entry_b.lock_project();
            let a = entry_a.lock_project();
            let report = crate::diff::diff_projects(&a, &b);
            ok(serde_json::to_value(report).expect("diff report serializes"))
        }
    }
}

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

    use std::sync::atomic::{AtomicU64, Ordering};

    static SEQ: AtomicU64 = AtomicU64::new(0);

    /// Unique scratch dir for one test; removed afterwards.
    fn scratch(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "binscout-mcp-cache-{}-{}-{}",
            tag,
            std::process::id(),
            SEQ.fetch_add(1, Ordering::SeqCst)
        ));
        std::fs::create_dir_all(&dir).expect("scratch dir");
        dir
    }

    /// Raw x86-64 blob (`nop; nop; ret`) at its own path: unrecognized
    /// bytes open through the raw fallback at base 0.
    fn write_blob(dir: &std::path::Path, name: &str, byte: u8) -> std::path::PathBuf {
        let mut bytes = vec![0x90, 0x90, 0xC3];
        bytes.push(byte);
        let path = dir.join(name);
        std::fs::write(&path, &bytes).expect("write blob");
        path
    }

    fn open_params(bin: &std::path::Path, db: &std::path::Path) -> (String, Option<String>) {
        (bin.display().to_string(), Some(db.display().to_string()))
    }

    #[test]
    fn repeat_open_returns_same_entry() {
        let dir = scratch("hit");
        let bin = write_blob(&dir, "a.bin", 0x90);
        let db = dir.join("a.redb");
        let (binary, db_s) = open_params(&bin, &db);
        let mcp = BinscoutMcp::new();
        let first = mcp
            .cached_entry(&binary, db_s.as_deref(), None, None)
            .expect("first open");
        let second = mcp
            .cached_entry(&binary, db_s.as_deref(), None, None)
            .expect("second open");
        assert!(Arc::ptr_eq(&first, &second), "hit must reuse the entry");
        assert!(!db.exists(), "reads never create the sidecar");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn edited_binary_reopens() {
        let dir = scratch("stale");
        let bin = write_blob(&dir, "a.bin", 0x90);
        let db = dir.join("a.redb");
        let (binary, db_s) = open_params(&bin, &db);
        let mcp = BinscoutMcp::new();
        let first = mcp
            .cached_entry(&binary, db_s.as_deref(), None, None)
            .expect("first open");
        assert_eq!(first.lock_project().analysis().summary().insns, 3);
        // Same path, different length: the entry must revalidate.
        std::fs::write(&bin, [0x90, 0xC3]).expect("rewrite blob");
        let second = mcp
            .cached_entry(&binary, db_s.as_deref(), None, None)
            .expect("second open");
        assert!(!Arc::ptr_eq(&first, &second), "edit must replace the entry");
        assert_eq!(second.lock_project().analysis().summary().insns, 2);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn mapping_and_db_split_entries() {
        let dir = scratch("keys");
        let bin = write_blob(&dir, "a.bin", 0x90);
        let db_a = dir.join("a.redb");
        let db_b = dir.join("b.redb");
        let mcp = BinscoutMcp::new();
        let raw = |base: &str| RawParams {
            arch: Some("x86_64".to_string()),
            base: Some(base.to_string()),
            entry: None,
        };
        let auto = mcp
            .cached_entry(
                &bin.display().to_string(),
                Some(&db_a.display().to_string()),
                None,
                None,
            )
            .expect("auto open");
        let raw_open = mcp
            .cached_entry(
                &bin.display().to_string(),
                Some(&db_a.display().to_string()),
                Some(&raw("0x1000")),
                None,
            )
            .expect("raw open");
        let other_db = mcp
            .cached_entry(
                &bin.display().to_string(),
                Some(&db_b.display().to_string()),
                None,
                None,
            )
            .expect("other db open");
        assert!(!Arc::ptr_eq(&auto, &raw_open), "mapping splits entries");
        assert!(!Arc::ptr_eq(&auto, &other_db), "db path splits entries");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn lru_evicts_past_capacity() {
        let dir = scratch("lru");
        let mcp = BinscoutMcp::new();
        let mut first_key = String::new();
        for i in 0..CACHE_CAPACITY + 1 {
            let bin = write_blob(&dir, &format!("f{i}.bin"), i as u8);
            let db = dir.join(format!("f{i}.redb"));
            let (binary, db_s) = open_params(&bin, &db);
            if i == 0 {
                first_key = binary.clone();
            }
            mcp.cached_entry(&binary, db_s.as_deref(), None, None)
                .expect("open");
        }
        let state = mcp.cache.state.lock().unwrap_or_else(|e| e.into_inner());
        assert_eq!(state.entries.len(), CACHE_CAPACITY);
        assert!(
            state.entries.keys().all(|k| k.binary != first_key),
            "least-recently-used entry must evict"
        );
        std::fs::remove_dir_all(&dir).ok();
    }
}