solo-api 0.7.0

Solo: MCP and HTTP transports
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
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
// SPDX-License-Identifier: Apache-2.0

//! MCP (Model Context Protocol) server for Solo.
//!
//! Exposes thirteen tools to MCP clients (Claude Desktop, Cursor, etc.):
//!
//! Episode tools (v0.1+):
//!   - `memory_remember(content, source_type?, source_id?)` — store an
//!     episode. Returns the new MemoryId.
//!   - `memory_recall(query, limit?)` — vector search. Returns the top-K
//!     matches with content + tier + status.
//!   - `memory_forget(memory_id, reason?)` — soft-delete an episode.
//!   - `memory_inspect(memory_id)` — return the full episode record.
//!
//! Derived-layer tools (v0.4.0+):
//!   - `memory_themes(window_days?, limit?)` — list cluster themes.
//!   - `memory_facts_about(subject, ...)` — query the structured-fact
//!     knowledge graph (subject-predicate-object triples).
//!   - `memory_contradictions(limit?)` — disagreements flagged during
//!     consolidation.
//!
//! Derived-layer tools (v0.5.0+):
//!   - `memory_inspect_cluster(cluster_id, full_content?)` — drill
//!     into one cluster's abstraction + source episodes (truncated).
//!
//! Document tools (v0.7.0+):
//!   - `memory_ingest_document(path)` — read a file from disk, split it
//!     into chunks, embed each, and store under documents/document_chunks.
//!   - `memory_search_docs(query, limit?)` — vector search restricted to
//!     document chunks; returns chunk content + parent-doc context.
//!   - `memory_inspect_document(doc_id)` — show one document's metadata
//!     plus a previewed list of its chunks.
//!   - `memory_list_documents(limit?, offset?, include_forgotten?)` —
//!     paginate over ingested documents, newest first.
//!   - `memory_forget_document(doc_id)` — soft-delete a document; chunks
//!     stop appearing in `memory_search_docs` and tombstone in HNSW.
//!
//! ## Transport
//!
//! `serve_stdio` wires the server to stdin/stdout for use as a subprocess
//! ("`claude_desktop_config.json` or `~/.cursor/mcp.json` invokes
//! `solo mcp-stdio`"). The function awaits a graceful shutdown when stdin
//! closes (parent disconnects) — same lifecycle as `solo daemon`'s
//! Ctrl+C path.
//!
//! ## What's deferred
//!
//! - SSE/HTTP transports — `rmcp` ships them, but v0.1 ships stdio only.
//! - `prompts/` and `resources/` capabilities — not needed for the
//!   four-tool surface; ServerHandler defaults return empty lists.
//! - Tool argument validation beyond JSON Schema typing — we trust rmcp
//!   to deserialize per the schema, then serde-deserialize into our
//!   typed param structs. Bad inputs surface as clear errors.

use std::sync::Arc;

use rmcp::handler::server::ServerHandler;
use rmcp::model::{
    CallToolRequestParam, CallToolResult, Content, Implementation, ListToolsResult,
    PaginatedRequestParam, ProtocolVersion, ServerCapabilities, ServerInfo, Tool,
    ToolsCapability,
};
use rmcp::service::{RequestContext, RoleServer};
use rmcp::{Error as McpError, ServiceExt};
use serde::{Deserialize, Serialize};
use solo_core::{
    Confidence, DocumentId, Embedder, EncodingContext, Episode, MemoryId, Tier,
    VectorIndex,
};
use solo_storage::{ReaderPool, WriteHandle};
use std::str::FromStr;

/// The MCP server. Cheap to clone — every field is `Arc`-cloneable.
#[derive(Clone)]
pub struct SoloMcpServer {
    inner: Arc<Inner>,
}

struct Inner {
    write: WriteHandle,
    pool: ReaderPool,
    embedder: Arc<dyn Embedder>,
    hnsw: Arc<dyn VectorIndex + Send + Sync>,
    /// Read-path aliases for the canonical `"user"` subject. Sourced
    /// from `solo.config.toml` `[identity] user_aliases`; threaded
    /// through to `solo_query::facts_about` so a query for `"alex"`
    /// also surfaces rows historically extracted as `"user"`. Empty
    /// vec = behave as today (no expansion).
    user_aliases: Vec<String>,
}

impl SoloMcpServer {
    /// Build a server without identity-config aliases (back-compat
    /// constructor + tests). Equivalent to `new_with_identity` with an
    /// empty alias list.
    pub fn new(
        write: WriteHandle,
        pool: ReaderPool,
        embedder: Arc<dyn Embedder>,
        hnsw: Arc<dyn VectorIndex + Send + Sync>,
    ) -> Self {
        Self::new_with_identity(write, pool, embedder, hnsw, Vec::new())
    }

    /// Build a server, threading in `user_aliases` so `memory_facts_about`
    /// resolves the canonical `"user"` subject to + from each alias.
    /// Sourced from `solo.config.toml` `[identity] user_aliases`.
    pub fn new_with_identity(
        write: WriteHandle,
        pool: ReaderPool,
        embedder: Arc<dyn Embedder>,
        hnsw: Arc<dyn VectorIndex + Send + Sync>,
        user_aliases: Vec<String>,
    ) -> Self {
        Self {
            inner: Arc::new(Inner {
                write,
                pool,
                embedder,
                hnsw,
                user_aliases,
            }),
        }
    }
}

/// Convenience: run the server over stdio and await its termination.
/// Returns when stdin closes (parent disconnect) or the runtime exits.
pub async fn serve_stdio(server: SoloMcpServer) -> anyhow::Result<()> {
    use rmcp::transport::io::stdio;
    let (stdin, stdout) = stdio();
    let running = server.serve((stdin, stdout)).await?;
    running.waiting().await?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Tool argument schemas
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RememberArgs {
    pub content: String,
    #[serde(default)]
    pub source_type: Option<String>,
    #[serde(default)]
    pub source_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecallArgs {
    pub query: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

fn default_limit() -> usize {
    5
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForgetArgs {
    pub memory_id: String,
    #[serde(default = "default_forget_reason")]
    pub reason: String,
}

fn default_forget_reason() -> String {
    "user-initiated via MCP".into()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InspectArgs {
    pub memory_id: String,
}

// Path 1 derived-layer tools (v0.4.0+) — query the Steward's outputs.
// `solo_query::derived` is the single source of truth; these handlers
// just translate JSON args to function args and serialise the result
// vec to JSON for the MCP wire.

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemesArgs {
    /// Optional time window in days; `None` = unfiltered, return up
    /// to `limit` most-recent themes across all time. `Some(7)` =
    /// "themes from the last week".
    #[serde(default)]
    pub window_days: Option<i64>,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FactsAboutArgs {
    /// Subject id to query — required (predicate-only scans
    /// intentionally not supported).
    pub subject: String,
    #[serde(default)]
    pub predicate: Option<String>,
    #[serde(default)]
    pub since_ms: Option<i64>,
    #[serde(default)]
    pub until_ms: Option<i64>,
    /// v0.5.1 Priority 8 — widen the query to also match rows where
    /// `subject` appears as the object (e.g. surface "Sam pushes back
    /// on PRs about Maya" under `facts_about(subject="maya")`).
    /// Default `false` preserves v0.5.0 behaviour.
    #[serde(default)]
    pub include_as_object: bool,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContradictionsArgs {
    #[serde(default = "default_limit")]
    pub limit: usize,
}

/// Args for `memory_inspect_cluster` (v0.5.0 Priority 3). `cluster_id`
/// is required; `full_content` is opt-in for the rare power-user case
/// where 200-char-per-episode truncation is too aggressive.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InspectClusterArgs {
    pub cluster_id: String,
    /// If `true`, episode `content` fields are returned verbatim. If
    /// `false` or omitted (the default), each episode's content is
    /// truncated to `solo_query::EPISODE_TRUNCATE_CHARS` chars with a
    /// trailing `…`.
    #[serde(default)]
    pub full_content: bool,
}

// Document tools (v0.7.0+). Five args structs paired with five handlers.
// Wire shapes per `docs/dev-log/0083-v0.7.0-implementation-plan.md` §2 P5.

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngestDocumentArgs {
    /// Server-side filesystem path to the file to ingest. Must be
    /// readable by the Solo process. The writer parses the file by
    /// extension, splits it into ~500-token chunks, embeds each, and
    /// stores them under `documents` + `document_chunks`.
    pub path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchDocsArgs {
    pub query: String,
    #[serde(default = "default_search_docs_limit")]
    pub limit: usize,
}

fn default_search_docs_limit() -> usize {
    5
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InspectDocumentArgs {
    pub doc_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListDocumentsArgs {
    #[serde(default = "default_list_documents_limit")]
    pub limit: usize,
    #[serde(default)]
    pub offset: usize,
    /// If `true`, also include documents the user has forgotten. Default
    /// `false` matches the agent-UX expectation that recall + listing
    /// ignore soft-deleted rows.
    #[serde(default)]
    pub include_forgotten: bool,
}

fn default_list_documents_limit() -> usize {
    20
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForgetDocumentArgs {
    pub doc_id: String,
}

// ---------------------------------------------------------------------------
// ServerHandler implementation
// ---------------------------------------------------------------------------

impl ServerHandler for SoloMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::default(),
            capabilities: ServerCapabilities {
                tools: Some(ToolsCapability {
                    list_changed: Some(false),
                }),
                ..Default::default()
            },
            server_info: Implementation {
                name: "solo".into(),
                version: env!("CARGO_PKG_VERSION").into(),
            },
            instructions: Some(
                "Solo gives you persistent memory across conversations \
                 with this user — what they've told you before, the \
                 people and projects in their life, and where their \
                 stated beliefs have shifted, plus a library of \
                 documents the user has ingested (notes, runbooks, \
                 PDFs). Reach for these tools whenever the user \
                 references something from earlier (\"like I \
                 mentioned\", \"the project I'm working on\", \"my \
                 friend Alex\", \"the notes I uploaded last week\") \
                 or asks a question that hinges on personal context \
                 or document content you don't have in the current \
                 chat. \
                 \n\nTools to write or look up specific moments: \
                 memory_remember (save something worth keeping), \
                 memory_recall (search past conversations by topic), \
                 memory_inspect (show one saved item by id), \
                 memory_forget (delete one saved item). \
                 \n\nTools for the bigger picture (populated as the \
                 user uses Solo over time): memory_themes (recent \
                 topics they've been thinking about), \
                 memory_facts_about (what you know about a person, \
                 project, or place — \"what do you know about \
                 Alex?\"), memory_contradictions (places where the \
                 user has said two things that disagree — surface \
                 these before answering), memory_inspect_cluster \
                 (the raw conversations behind one summary). \
                 \n\nTools for the user's documents: \
                 memory_ingest_document (read a file from disk and \
                 add it to Solo's library), memory_search_docs \
                 (search across ingested documents by topic — use \
                 when the user asks about something they wrote down \
                 or saved as a file), memory_inspect_document (show \
                 one document's metadata plus a preview of its \
                 chunks), memory_list_documents (browse documents \
                 by recency), memory_forget_document (drop a \
                 document from the library)."
                    .into(),
            ),
        }
    }

    async fn list_tools(
        &self,
        _request: PaginatedRequestParam,
        _context: RequestContext<RoleServer>,
    ) -> std::result::Result<ListToolsResult, McpError> {
        Ok(ListToolsResult {
            tools: build_tools(),
            next_cursor: None,
        })
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParam,
        _context: RequestContext<RoleServer>,
    ) -> std::result::Result<CallToolResult, McpError> {
        let CallToolRequestParam { name, arguments } = request;
        let args_value = serde_json::Value::Object(arguments.unwrap_or_default());
        self.dispatch_tool(&name, args_value).await
    }
}

impl SoloMcpServer {
    /// Direct tool-dispatch path used by both `call_tool` (the
    /// ServerHandler trait method, behind the rmcp protocol layer) and
    /// in-process tests that don't want to spin up a full transport pair.
    /// Bypasses `RequestContext` (which requires a `Peer` not constructible
    /// outside rmcp internals).
    pub async fn dispatch_tool(
        &self,
        name: &str,
        args_value: serde_json::Value,
    ) -> std::result::Result<CallToolResult, McpError> {
        match name {
            "memory_remember" => {
                let args: RememberArgs = parse_args(&args_value)?;
                self.handle_remember(args).await
            }
            "memory_recall" => {
                let args: RecallArgs = parse_args(&args_value)?;
                self.handle_recall(args).await
            }
            "memory_forget" => {
                let args: ForgetArgs = parse_args(&args_value)?;
                self.handle_forget(args).await
            }
            "memory_inspect" => {
                let args: InspectArgs = parse_args(&args_value)?;
                self.handle_inspect(args).await
            }
            "memory_themes" => {
                let args: ThemesArgs = parse_args(&args_value)?;
                self.handle_themes(args).await
            }
            "memory_facts_about" => {
                let args: FactsAboutArgs = parse_args(&args_value)?;
                self.handle_facts_about(args).await
            }
            "memory_contradictions" => {
                let args: ContradictionsArgs = parse_args(&args_value)?;
                self.handle_contradictions(args).await
            }
            "memory_inspect_cluster" => {
                let args: InspectClusterArgs = parse_args(&args_value)?;
                self.handle_inspect_cluster(args).await
            }
            "memory_ingest_document" => {
                let args: IngestDocumentArgs = parse_args(&args_value)?;
                self.handle_ingest_document(args).await
            }
            "memory_search_docs" => {
                let args: SearchDocsArgs = parse_args(&args_value)?;
                self.handle_search_docs(args).await
            }
            "memory_inspect_document" => {
                let args: InspectDocumentArgs = parse_args(&args_value)?;
                self.handle_inspect_document(args).await
            }
            "memory_list_documents" => {
                let args: ListDocumentsArgs = parse_args(&args_value)?;
                self.handle_list_documents(args).await
            }
            "memory_forget_document" => {
                let args: ForgetDocumentArgs = parse_args(&args_value)?;
                self.handle_forget_document(args).await
            }
            other => Err(McpError::invalid_params(
                format!("unknown tool `{other}`"),
                None,
            )),
        }
    }

    /// List the tools this server exposes. Mirrors `ServerHandler::list_tools`
    /// without requiring a RequestContext.
    pub fn dispatch_list_tools(&self) -> Vec<Tool> {
        build_tools()
    }
}

fn parse_args<T: serde::de::DeserializeOwned>(
    v: &serde_json::Value,
) -> std::result::Result<T, McpError> {
    serde_json::from_value(v.clone()).map_err(|e| {
        McpError::invalid_params(format!("invalid tool arguments: {e}"), None)
    })
}

fn solo_to_mcp(e: solo_core::Error) -> McpError {
    use solo_core::Error;
    match e {
        Error::NotFound(msg) => McpError::invalid_params(msg, None),
        Error::InvalidInput(msg) => McpError::invalid_params(msg, None),
        Error::Conflict(msg) => McpError::invalid_params(msg, None),
        other => McpError::internal_error(other.to_string(), None),
    }
}

// ---------------------------------------------------------------------------
// Tool definitions (JSON Schema)
// ---------------------------------------------------------------------------

fn build_tools() -> Vec<Tool> {
    vec![
        Tool::new(
            "memory_remember",
            "Save something the user has told you — a fact, a \
             preference, a name, a date, a context — so you can pick \
             it up next conversation. Use whenever the user mentions \
             something they'd reasonably expect you to recall later \
             (\"I just started at Quotient\", \"my partner is Maya\"). \
             Returns the saved item's id.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "content": {
                        "type": "string",
                        "description": "The text to remember.",
                    },
                    "source_type": {
                        "type": "string",
                        "description": "Optional source-type tag (default: \"user_message\").",
                    },
                    "source_id": {
                        "type": "string",
                        "description": "Optional upstream id for traceability.",
                    },
                },
                "required": ["content"],
            })),
        ),
        Tool::new(
            "memory_recall",
            "Search past conversations with this user by topic or \
             phrase. Returns up to `limit` of the closest matches, \
             best match first. Use when the user references \
             something they said before (\"that book I told you \
             about\", \"the bug we were debugging last week\"). \
             Skips items the user has deleted.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The query text.",
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results (default 5).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                },
                "required": ["query"],
            })),
        ),
        Tool::new(
            "memory_forget",
            "Delete one saved item by id. Use when the user asks you \
             to forget something specific (\"forget that I said \
             X\"). The item stops appearing in future recalls. \
             Reversible only via backups.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "memory_id": {
                        "type": "string",
                        "description": "MemoryId to forget (UUID v7).",
                    },
                    "reason": {
                        "type": "string",
                        "description": "Optional free-form reason (logged, not yet persisted).",
                    },
                },
                "required": ["memory_id"],
            })),
        ),
        Tool::new(
            "memory_inspect",
            "Show the full record for one saved item — when it was \
             saved, where it came from, and the full text. Use after \
             memory_recall when you want the complete content of a \
             specific hit (recall results may be truncated).",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "memory_id": {
                        "type": "string",
                        "description": "MemoryId to inspect (UUID v7).",
                    },
                },
                "required": ["memory_id"],
            })),
        ),
        // Path 1 derived-layer tools (v0.4.0+) — query the Steward's
        // outputs. These four are populated by `solo consolidate` and
        // were previously unreadable except via direct SQL.
        Tool::new(
            "memory_themes",
            "Recent topics the user has been thinking about. Use to \
             orient yourself at the start of a conversation, or when \
             the user asks \"what have I been up to\" / \"what was I \
             working on last week\". Pass `window_days` to scope \
             (e.g. 7 for last week); omit for all-time.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "window_days": {
                        "type": "integer",
                        "description": "Optional time window in days. Omit for unfiltered.",
                        "minimum": 1,
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results (default 5).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                },
            })),
        ),
        Tool::new(
            "memory_facts_about",
            "Look up what you remember about a person, project, or \
             topic — names, dates, preferences, relationships. Use \
             when the user asks \"what do you know about Alex?\", \
             \"when did I start at Quotient?\", \"who is Maya?\", or \
             whenever you need grounded facts about someone or \
             something before answering. Subject is required (the \
             person/place/thing you're asking about); narrow further \
             with `predicate` (\"works_at\", \"lives_in\") or a date \
             range. Set `include_as_object=true` to also surface \
             facts where the subject appears on the receiving side of \
             a relationship (e.g. \"Sam pushes back on PRs about \
             Maya\" surfaces under facts_about(subject=\"Maya\", \
             include_as_object=true)). (Backed by \
             subject-predicate-object triples distilled from past \
             conversations.) Clients should set a 30s timeout on this \
             call; if exceeded, retry once or fall back to \
             `memory_recall`.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "subject": {
                        "type": "string",
                        "description": "Subject id to query (e.g. 'Sam').",
                    },
                    "predicate": {
                        "type": "string",
                        "description": "Optional predicate filter (e.g. 'works_at').",
                    },
                    "since_ms": {
                        "type": "integer",
                        "description": "Optional valid_from_ms lower bound (epoch ms).",
                    },
                    "until_ms": {
                        "type": "integer",
                        "description": "Optional valid_to_ms upper bound (epoch ms). NULL upper bounds (still-valid facts) pass through.",
                    },
                    "include_as_object": {
                        "type": "boolean",
                        "description": "If true, also match facts where `subject` appears as the object (e.g. 'Sam pushes back on PRs about Maya' surfaces under subject='Maya'). Default false.",
                        "default": false,
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results (default 5).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                },
                "required": ["subject"],
            })),
        ),
        Tool::new(
            "memory_contradictions",
            "Find places where the user's stated beliefs or facts \
             disagree across conversations — flag disagreements \
             before answering. Use whenever you're about to rely on \
             a remembered fact that could have changed (jobs, \
             relationships, preferences, opinions); a disagreement \
             here means the user has told you both X and not-X over \
             time and you should ask which is current instead of \
             guessing. Each result shows both conflicting statements \
             with the topic.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results (default 5).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                },
            })),
        ),
        Tool::new(
            "memory_inspect_cluster",
            "Show the raw conversations behind one summary. Returns \
             the one-line topic (the LLM-generated summary) and the \
             source conversations the topic was built from. Use \
             after memory_themes when the user asks \"show me the \
             raw context behind this\" or \"why does Solo think \
             that about cluster Y\". Source items are truncated to \
             200 chars unless `full_content` is set.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "cluster_id": {
                        "type": "string",
                        "description": "Cluster id to inspect (from memory_themes hits).",
                    },
                    "full_content": {
                        "type": "boolean",
                        "description": "If true, episode content is returned verbatim. Default false (truncate to 200 chars + ellipsis).",
                    },
                },
                "required": ["cluster_id"],
            })),
        ),
        // Document tools (v0.7.0+). RAG over user-supplied files —
        // markdown notes, PDFs, runbooks, code, etc. Same vector space
        // as episodes; same embedder; same HNSW index.
        Tool::new(
            "memory_ingest_document",
            "Read a file from disk and add it to the user's document \
             library so it becomes searchable alongside past \
             conversations. Use when the user asks you to remember a \
             whole file (\"add my notes/runbook.md\", \"ingest this \
             PDF\"). The file is split into ~500-token chunks and \
             each chunk is embedded; chunks then surface through \
             memory_search_docs. Returns the new document id, chunk \
             count, and a `deduped` flag (true if the same content \
             was already ingested under another id).",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Server-side absolute path to the file to ingest. The file must be readable by the Solo process.",
                    },
                },
                "required": ["path"],
            })),
        ),
        Tool::new(
            "memory_search_docs",
            "Search across the user's ingested documents by topic or \
             phrase. Returns up to `limit` matching chunks, best \
             match first, each with the parent document's title + \
             source path so you can cite where the answer came from. \
             Use when the user asks a question that hinges on \
             material they've added as a file (\"what does my \
             runbook say about backups?\", \"find the section in the \
             notes about the new policy\"). Forgotten documents are \
             skipped.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The query text.",
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results (default 5).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                },
                "required": ["query"],
            })),
        ),
        Tool::new(
            "memory_inspect_document",
            "Show one document's metadata plus a preview of every \
             chunk it was split into. Use after memory_search_docs \
             when the user wants the bigger picture for one hit \
             (\"show me the whole document this came from\"), or \
             after memory_list_documents to drill into one entry. \
             Each chunk preview is truncated to 200 chars.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "doc_id": {
                        "type": "string",
                        "description": "Document id to inspect (UUID v7).",
                    },
                },
                "required": ["doc_id"],
            })),
        ),
        Tool::new(
            "memory_list_documents",
            "List the user's ingested documents, newest first. Use \
             when the user asks \"what documents have I added?\" or \
             \"show me my files\". Returns a paginated index — pass \
             `offset` to page further back. Forgotten documents are \
             hidden by default; set `include_forgotten=true` to see \
             them too.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results per page (default 20).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                    "offset": {
                        "type": "integer",
                        "description": "Number of rows to skip (for paging). Default 0.",
                        "minimum": 0,
                    },
                    "include_forgotten": {
                        "type": "boolean",
                        "description": "If true, also include documents the user has forgotten. Default false.",
                    },
                },
            })),
        ),
        Tool::new(
            "memory_forget_document",
            "Drop one document from the user's library by id. Use \
             when the user asks you to forget a specific file \
             (\"forget my old runbook\"). The document's chunks stop \
             appearing in memory_search_docs and the vectors are \
             tombstoned in the index. The chunk rows themselves are \
             kept for forensic value (a future restore command can \
             undo this).",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "doc_id": {
                        "type": "string",
                        "description": "Document id to forget (UUID v7).",
                    },
                },
                "required": ["doc_id"],
            })),
        ),
    ]
}

fn json_schema_object(value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
    match value {
        serde_json::Value::Object(map) => map,
        _ => panic!("json_schema_object: input must be an object"),
    }
}

/// Names of every tool this server exposes, in registration order.
///
/// Exposed for cross-crate consumers (notably `solo doctor
/// --check-mcp-compat`) that want the name list without paying the
/// cost of building full `rmcp::Tool` records (which allocate JSON
/// schemas). The registration order matches `build_tools()` so any
/// drift between the two would be caught by the cross-provider regex
/// test which iterates `build_tools()`.
pub fn tool_names() -> Vec<&'static str> {
    vec![
        "memory_remember",
        "memory_recall",
        "memory_forget",
        "memory_inspect",
        "memory_themes",
        "memory_facts_about",
        "memory_contradictions",
        "memory_inspect_cluster",
        // Document tools added in v0.7.0:
        "memory_ingest_document",
        "memory_search_docs",
        "memory_inspect_document",
        "memory_list_documents",
        "memory_forget_document",
    ]
}

// ---------------------------------------------------------------------------
// Tool handlers
// ---------------------------------------------------------------------------

impl SoloMcpServer {
    async fn handle_remember(
        &self,
        args: RememberArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let content = args.content.trim_end().to_string();
        if content.is_empty() {
            return Err(McpError::invalid_params(
                "memory_remember: content must not be empty".to_string(),
                None,
            ));
        }
        let embedding: solo_core::Embedding = self
            .inner
            .embedder
            .embed(&content)
            .await
            .map_err(solo_to_mcp)?;
        let episode = Episode {
            memory_id: MemoryId::new(),
            ts_ms: chrono::Utc::now().timestamp_millis(),
            source_type: args.source_type.unwrap_or_else(|| "user_message".into()),
            source_id: args.source_id,
            content,
            encoding_context: EncodingContext::default(),
            provenance: None,
            confidence: Confidence::new(0.9).unwrap(),
            strength: 0.5,
            salience: 0.5,
            tier: Tier::Hot,
        };
        let mid = self
            .inner
            .write
            .remember(episode, embedding)
            .await
            .map_err(solo_to_mcp)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "remembered {mid}"
        ))]))
    }

    async fn handle_recall(
        &self,
        args: RecallArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        // Pipeline lives in solo-query; the transport just formats the
        // result. solo_query::run_recall validates empty queries
        // (returns InvalidInput → invalid_params via solo_to_mcp).
        let result = solo_query::run_recall(
            &self.inner.embedder,
            &self.inner.hnsw,
            &self.inner.pool,
            &args.query,
            args.limit,
        )
        .await
        .map_err(solo_to_mcp)?;

        if result.hits.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(format!(
                "no matches (index has {} vectors)",
                result.index_len
            ))]));
        }
        let body = serde_json::to_string_pretty(&result.hits).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    async fn handle_forget(
        &self,
        args: ForgetArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let mid = MemoryId::from_str(&args.memory_id).map_err(|e| {
            McpError::invalid_params(format!("invalid memory_id: {e}"), None)
        })?;
        self.inner
            .write
            .forget(mid, args.reason)
            .await
            .map_err(solo_to_mcp)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "forgotten {mid}"
        ))]))
    }

    async fn handle_inspect(
        &self,
        args: InspectArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let mid = MemoryId::from_str(&args.memory_id).map_err(|e| {
            McpError::invalid_params(format!("invalid memory_id: {e}"), None)
        })?;
        // Pipeline lives in solo-query::inspect; transports just format.
        let row = solo_query::inspect_one(&self.inner.pool, mid)
            .await
            .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&row).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    // Path 1 derived-layer handlers (v0.4.0+). Each one delegates to a
    // single solo-query::derived pipeline and serialises the result Vec
    // to pretty JSON for the MCP wire. Empty result → JSON empty array
    // `[]` (not a special-case "no matches" string) so MCP clients can
    // parse uniformly.

    async fn handle_themes(
        &self,
        args: ThemesArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let hits = solo_query::themes(
            &self.inner.pool,
            args.window_days,
            args.limit,
        )
        .await
        .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&hits).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    async fn handle_facts_about(
        &self,
        args: FactsAboutArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        if args.subject.trim().is_empty() {
            return Err(McpError::invalid_params(
                "memory_facts_about: subject must not be empty".to_string(),
                None,
            ));
        }
        let hits = solo_query::facts_about(
            &self.inner.pool,
            &args.subject,
            &self.inner.user_aliases,
            args.include_as_object,
            args.predicate.as_deref(),
            args.since_ms,
            args.until_ms,
            args.limit,
        )
        .await
        .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&hits).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    async fn handle_contradictions(
        &self,
        args: ContradictionsArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let hits = solo_query::contradictions(&self.inner.pool, args.limit)
            .await
            .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&hits).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    async fn handle_inspect_cluster(
        &self,
        args: InspectClusterArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        if args.cluster_id.trim().is_empty() {
            return Err(McpError::invalid_params(
                "memory_inspect_cluster: cluster_id must not be empty".to_string(),
                None,
            ));
        }
        // `solo_to_mcp` maps `Error::NotFound` → `invalid_params` for
        // MCP (the protocol does not have a separate "not found" error
        // shape; clients see the message verbatim, which includes the
        // cluster_id).
        let record = solo_query::inspect_cluster(
            &self.inner.pool,
            &args.cluster_id,
            args.full_content,
        )
        .await
        .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&record).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    // Document handlers (v0.7.0+). Each wraps the corresponding writer
    // / query API; the MCP wire shape is plain JSON serialisation of
    // the returned report / records.

    async fn handle_ingest_document(
        &self,
        args: IngestDocumentArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        if args.path.trim().is_empty() {
            return Err(McpError::invalid_params(
                "memory_ingest_document: path must not be empty".to_string(),
                None,
            ));
        }
        let path = std::path::PathBuf::from(args.path);
        // Defaults match what the daemon uses today (target 500 tokens,
        // 50-token overlap). Future: thread a per-call override through
        // the args struct if a use case appears.
        let chunk_config = solo_storage::document::ChunkConfig::default();
        let report = self
            .inner
            .write
            .ingest_document(path, chunk_config)
            .await
            .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&report).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    async fn handle_search_docs(
        &self,
        args: SearchDocsArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        // `solo_query::run_doc_search` validates empty queries (returns
        // InvalidInput → invalid_params via solo_to_mcp) and clamps
        // limit upstream of the embedder call.
        let hits = solo_query::run_doc_search(
            &self.inner.embedder,
            &self.inner.hnsw,
            &self.inner.pool,
            &args.query,
            args.limit,
        )
        .await
        .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&hits).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    async fn handle_inspect_document(
        &self,
        args: InspectDocumentArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let doc_id = DocumentId::from_str(&args.doc_id).map_err(|e| {
            McpError::invalid_params(format!("invalid doc_id: {e}"), None)
        })?;
        let result_opt = solo_query::inspect_document(&self.inner.pool, &doc_id)
            .await
            .map_err(solo_to_mcp)?;
        match result_opt {
            Some(record) => {
                let body =
                    serde_json::to_string_pretty(&record).unwrap_or_else(|_| String::new());
                Ok(CallToolResult::success(vec![Content::text(body)]))
            }
            None => Err(McpError::invalid_params(
                format!("document {doc_id} not found"),
                None,
            )),
        }
    }

    async fn handle_list_documents(
        &self,
        args: ListDocumentsArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let rows = solo_query::list_documents(
            &self.inner.pool,
            args.limit,
            args.offset,
            args.include_forgotten,
        )
        .await
        .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&rows).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    async fn handle_forget_document(
        &self,
        args: ForgetDocumentArgs,
    ) -> std::result::Result<CallToolResult, McpError> {
        let doc_id = DocumentId::from_str(&args.doc_id).map_err(|e| {
            McpError::invalid_params(format!("invalid doc_id: {e}"), None)
        })?;
        let report = self
            .inner
            .write
            .forget_document(doc_id)
            .await
            .map_err(solo_to_mcp)?;
        let body = serde_json::to_string_pretty(&report).unwrap_or_else(|_| String::new());
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }
}

#[cfg(test)]
mod dispatch_tests {
    //! In-process integration tests for the MCP tool surface. We invoke
    //! `SoloMcpServer::dispatch_tool` directly (bypasses the rmcp
    //! protocol framing + `RequestContext`, which requires a `Peer`
    //! that's not constructible outside rmcp internals). The server is
    //! constructed against a real WriterActor + ReaderPool +
    //! StubEmbedder + StubVectorIndex from `solo_storage::test_support`.
    //!
    //! Tests live inline in this module rather than `tests/` because an
    //! external integration-test exe in `target/debug/deps/mcp_dispatch-*`
    //! tripped Windows UAC ERROR_ELEVATION_REQUIRED on the dev machine.
    //! The lib test binary doesn't have that issue.
    use super::*;
    use serde_json::json;
    use solo_core::VectorIndex;
    use solo_storage::test_support::StubVectorIndex;
    use solo_storage::{ReaderPool, StubEmbedder, WriterActor, WriterSpawn};
    use std::sync::Arc as StdArc;

    struct Harness {
        server: SoloMcpServer,
        _tmp: tempfile::TempDir,
        write_handle_extra: Option<solo_storage::WriteHandle>,
        join: Option<std::thread::JoinHandle<()>>,
    }

    impl Harness {
        fn new(runtime: &tokio::runtime::Runtime) -> Self {
            let tmp = tempfile::TempDir::new().unwrap();
            let dim = 16usize;
            let hnsw: StdArc<dyn VectorIndex + Send + Sync> = StdArc::new(StubVectorIndex::new(dim));
            let embedder: StdArc<dyn solo_core::Embedder> = StdArc::new(StubEmbedder::new("stub", "v1", dim));

            let conn = solo_storage::test_support::open_test_db_at(&tmp.path().join("test.db"));
            let WriterSpawn { handle, join } = WriterActor::spawn(conn, hnsw.clone());

            // ReaderPool's deadpool::Pool needs a live tokio runtime for
            // both build + drop; build inside block_on.
            let path = tmp.path().join("test.db");
            let pool: ReaderPool =
                runtime.block_on(async { ReaderPool::new(&path, None, hnsw.clone()).unwrap() });

            let server = SoloMcpServer::new(handle.clone(), pool, embedder, hnsw);
            Harness {
                server,
                _tmp: tmp,
                write_handle_extra: Some(handle),
                join: Some(join),
            }
        }

        fn shutdown(mut self, runtime: &tokio::runtime::Runtime) {
            // The whole shutdown runs inside block_on so deadpool-sqlite's
            // drop (which schedules cleanup on the active runtime) sees a
            // live reactor. Without this, dropping the SoloMcpServer
            // (which holds the ReaderPool through its Arc<Inner>) panics
            // with "no reactor running".
            let join = self.join.take();
            let extra = self.write_handle_extra.take();
            runtime.block_on(async move {
                drop(extra);
                drop(self.server);
                drop(self._tmp);
                if let Some(join) = join {
                    let (tx, rx) = std::sync::mpsc::channel();
                    std::thread::spawn(move || {
                        let _ = tx.send(join.join());
                    });
                    tokio::task::spawn_blocking(move || {
                        rx.recv_timeout(std::time::Duration::from_secs(5))
                    })
                    .await
                    .expect("blocking task")
                    .expect("writer thread did not exit within 5s")
                    .expect("writer thread panicked");
                }
            });
        }
    }

    fn rt() -> tokio::runtime::Runtime {
        tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .unwrap()
    }

    /// Pull the first Content::text body out of a CallToolResult. Use
    /// serde_json roundtrip as a robust extractor — `Content`'s public
    /// API doesn't directly expose the inner text without going through
    /// pattern-matching on RawContent.
    fn first_text(r: &rmcp::model::CallToolResult) -> String {
        let first = r.content.first().expect("at least one content item");
        let v = serde_json::to_value(first).expect("content serialises");
        v.get("text")
            .and_then(|t| t.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| format!("{v}"))
    }

    #[test]
    fn tools_list_returns_thirteen_canonical_tools() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        let tools = h.server.dispatch_list_tools();
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
        assert_eq!(
            names,
            vec![
                "memory_remember",
                "memory_recall",
                "memory_forget",
                "memory_inspect",
                // Derived-layer tools added in v0.4.0:
                "memory_themes",
                "memory_facts_about",
                "memory_contradictions",
                // Added in v0.5.0 (Priority 3):
                "memory_inspect_cluster",
                // Document tools added in v0.7.0:
                "memory_ingest_document",
                "memory_search_docs",
                "memory_inspect_document",
                "memory_list_documents",
                "memory_forget_document",
            ]
        );
        for t in &tools {
            assert!(!t.description.is_empty(), "{} description empty", t.name);
            let _schema = t.schema_as_json_value();
            // `required` is intentionally absent on memory_themes +
            // memory_contradictions + memory_list_documents (all args
            // optional with defaults). memory_facts_about has required
            // = ["subject"], etc. We don't assert per-tool 'required'
            // shape here; the schema's `properties` field is the more
            // important signal and is always present.
        }
        h.shutdown(&runtime);
    }

    #[test]
    fn themes_returns_json_array_on_empty_db() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let r = h
                .server
                .dispatch_tool("memory_themes", json!({}))
                .await
                .expect("themes succeeds");
            let text = first_text(&r);
            // Empty derived layer → empty array JSON. Parses cleanly.
            let v: serde_json::Value =
                serde_json::from_str(&text).expect("parses as json");
            assert!(v.is_array(), "expected array, got: {text}");
            assert_eq!(v.as_array().unwrap().len(), 0);
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn themes_passes_through_window_and_limit_args() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            // Should not crash with optional + integer args present.
            let r = h
                .server
                .dispatch_tool(
                    "memory_themes",
                    json!({ "window_days": 7, "limit": 20 }),
                )
                .await
                .expect("themes with args succeeds");
            let text = first_text(&r);
            let v: serde_json::Value =
                serde_json::from_str(&text).expect("parses as json");
            assert!(v.is_array());
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn facts_about_rejects_empty_subject() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool(
                    "memory_facts_about",
                    json!({ "subject": "   " }),
                )
                .await
                .expect_err("empty subject must error");
            // McpError doesn't expose a clean kind/message accessor; just
            // verify the error fires (validation path reached).
            let s = format!("{err:?}");
            assert!(
                s.to_lowercase().contains("subject")
                    || s.to_lowercase().contains("invalid"),
                "got: {s}"
            );
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn facts_about_returns_array_for_unknown_subject() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let r = h
                .server
                .dispatch_tool(
                    "memory_facts_about",
                    json!({ "subject": "NobodyKnowsThisSubject" }),
                )
                .await
                .expect("facts_about with unknown subject succeeds");
            let text = first_text(&r);
            let v: serde_json::Value =
                serde_json::from_str(&text).expect("parses as json");
            assert_eq!(v.as_array().unwrap().len(), 0);
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn facts_about_accepts_include_as_object_arg() {
        // Asserts the v0.5.1 P8 arg is parsed (serde default lets it
        // be omitted) and forwarded to the query lib without choking
        // the dispatcher. We don't seed triples — what we need to
        // verify is that the optional bool flows through. Both with
        // and without the arg, dispatch succeeds and returns an
        // empty array. (Functional coverage of the object-position
        // widening lives in the query-crate tests.)
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            // With include_as_object=true.
            let r = h
                .server
                .dispatch_tool(
                    "memory_facts_about",
                    json!({ "subject": "Maya", "include_as_object": true }),
                )
                .await
                .expect("dispatch with include_as_object=true succeeds");
            let v: serde_json::Value = serde_json::from_str(&first_text(&r))
                .expect("parses as json");
            assert_eq!(v.as_array().unwrap().len(), 0);

            // Omitted entirely — must default to false (no error).
            let r = h
                .server
                .dispatch_tool(
                    "memory_facts_about",
                    json!({ "subject": "Maya" }),
                )
                .await
                .expect("dispatch without include_as_object succeeds (default false)");
            let v: serde_json::Value = serde_json::from_str(&first_text(&r))
                .expect("parses as json");
            assert_eq!(v.as_array().unwrap().len(), 0);
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn contradictions_returns_json_array_on_empty_db() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let r = h
                .server
                .dispatch_tool("memory_contradictions", json!({}))
                .await
                .expect("contradictions succeeds");
            let text = first_text(&r);
            let v: serde_json::Value =
                serde_json::from_str(&text).expect("parses as json");
            assert!(v.is_array());
            assert_eq!(v.as_array().unwrap().len(), 0);
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn remember_then_recall_round_trip() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        // Use &h.server directly (no clone) so the only outstanding
        // reference at shutdown time is the harness's own. The clone
        // path triggered a 5-second writer-thread timeout because the
        // local clone held an Arc<Inner> with its own WriteHandle past
        // h.shutdown().
        runtime.block_on(async {
            let r = h
                .server
                .dispatch_tool("memory_remember", json!({ "content": "the cat sat on the mat" }))
                .await
                .expect("remember succeeds");
            let text = first_text(&r);
            assert!(text.starts_with("remembered "), "got: {text}");

            let r = h
                .server
                .dispatch_tool(
                    "memory_recall",
                    json!({ "query": "the cat sat on the mat", "limit": 5 }),
                )
                .await
                .expect("recall succeeds");
            let text = first_text(&r);
            assert!(text.contains("the cat sat on the mat"), "got: {text}");
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn forget_excludes_row_from_subsequent_recall() {
        let runtime = rt();
        let h = Harness::new(&runtime);

        runtime.block_on(async {
            let r = h
                .server
                .dispatch_tool("memory_remember", json!({ "content": "to be forgotten" }))
                .await
                .unwrap();
            let text = first_text(&r);
            let mid = text.strip_prefix("remembered ").unwrap().to_string();

            h.server
                .dispatch_tool(
                    "memory_forget",
                    json!({ "memory_id": mid, "reason": "test" }),
                )
                .await
                .expect("forget succeeds");

            let r = h
                .server
                .dispatch_tool(
                    "memory_recall",
                    json!({ "query": "to be forgotten", "limit": 5 }),
                )
                .await
                .unwrap();
            let text = first_text(&r);
            assert!(
                !text.contains(r#""content": "to be forgotten""#),
                "forgotten row should be excluded; got: {text}"
            );
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn empty_remember_returns_invalid_params() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool("memory_remember", json!({ "content": "" }))
                .await
                .unwrap_err();
            assert!(format!("{err:?}").contains("must not be empty"));
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn empty_recall_query_returns_invalid_params() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool("memory_recall", json!({ "query": "   " }))
                .await
                .unwrap_err();
            assert!(format!("{err:?}").contains("must not be empty"));
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn inspect_with_invalid_id_returns_invalid_params() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool("memory_inspect", json!({ "memory_id": "not-a-uuid" }))
                .await
                .unwrap_err();
            assert!(format!("{err:?}").contains("invalid memory_id"));
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn forget_unknown_id_returns_invalid_params() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            // Valid UUID format but not in episodes — handle_forget
            // surfaces NotFound, mapped to invalid_params per
            // solo_to_mcp.
            let err = h
                .server
                .dispatch_tool(
                    "memory_forget",
                    json!({ "memory_id": "00000000-0000-7000-8000-000000000000" }),
                )
                .await
                .unwrap_err();
            assert!(format!("{err:?}").contains("not found"));
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn unknown_tool_name_returns_invalid_params() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool("memory.summon", json!({}))
                .await
                .unwrap_err();
            assert!(format!("{err:?}").contains("unknown tool"));
        });
        h.shutdown(&runtime);
    }

    /// Regression guard for v0.4.1's MCP tool name fix, generalised
    /// in v0.5.0 Priority 4 to cover **all three** major LLM
    /// providers, not just Anthropic.
    ///
    /// Each provider enforces its own tool-name regex on the
    /// function-calling wire. A tool name has to satisfy ALL of them
    /// to be portable across clients:
    ///
    ///   - **Anthropic**: `^[a-zA-Z0-9_-]{1,64}$` (what shipped in
    ///     v0.4.1; failing this rejects the entire toolset on Claude
    ///     Desktop / Cursor / Claude Code with
    ///     `FrontendRemoteMcpToolDefinition.name: String should
    ///     match pattern ...`).
    ///   - **OpenAI** function-calling: `^[a-zA-Z_][a-zA-Z0-9_-]*$`
    ///     with length ≤ 64 (must start with letter or underscore).
    ///   - **Gemini** function-calling: documented as a-z, A-Z, 0-9,
    ///     underscores and dashes; some sources also allow dots. We
    ///     use the conservative intersection — must start with
    ///     letter or underscore, alphanumeric + underscore only (no
    ///     hyphen, no dot), length ≤ 63. This is the strictest of
    ///     the three patterns, so any tool that passes it also
    ///     passes the other two. Sources differ on whether Gemini
    ///     accepts dots or hyphens; the strictest reading guards us
    ///     against the future where one provider tightens the regex
    ///     (which is the failure mode v0.4.1 hit on Anthropic). See
    ///     <https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos/FunctionDeclaration.md>
    ///     and <https://ai.google.dev/gemini-api/docs/function-calling>.
    ///
    /// Lesson banked v0.3 #8: rmcp framing tests pass dot-named
    /// tools fine because rmcp's own client-side validation is
    /// permissive. Only the downstream provider API enforces the
    /// regex. This test gates the names at `cargo test` time so any
    /// future tool-name change has to pass all three provider
    /// regexes before reaching real clients.
    #[test]
    fn tool_names_match_cross_provider_regex() {
        /// Anthropic API name regex: `^[a-zA-Z0-9_-]{1,64}$`.
        fn passes_anthropic(name: &str) -> bool {
            let len = name.len();
            if !(1..=64).contains(&len) {
                return false;
            }
            name.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        }

        /// OpenAI function-calling name regex:
        /// `^[a-zA-Z_][a-zA-Z0-9_-]*$`, length ≤ 64.
        fn passes_openai(name: &str) -> bool {
            let len = name.len();
            if !(1..=64).contains(&len) {
                return false;
            }
            let mut chars = name.chars();
            let first = match chars.next() {
                Some(c) => c,
                None => return false,
            };
            if !(first.is_ascii_alphabetic() || first == '_') {
                return false;
            }
            chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        }

        /// Gemini function-calling name regex (conservative
        /// reading): `^[a-zA-Z_][a-zA-Z0-9_]*$`, length ≤ 63. No
        /// hyphen, no dot — strictest of the three so any name that
        /// passes this passes the other two.
        fn passes_gemini(name: &str) -> bool {
            let len = name.len();
            if !(1..=63).contains(&len) {
                return false;
            }
            let mut chars = name.chars();
            let first = match chars.next() {
                Some(c) => c,
                None => return false,
            };
            if !(first.is_ascii_alphabetic() || first == '_') {
                return false;
            }
            chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
        }

        let tools = build_tools();
        assert_eq!(
            tools.len(),
            13,
            "expected 13 tools in v0.7.0 (8 v0.5.x + 5 document tools)"
        );
        // Sanity-check that tool_names() agrees with build_tools().
        let tool_name_strings: Vec<String> =
            tools.iter().map(|t| t.name.to_string()).collect();
        let public_names: Vec<String> =
            super::tool_names().iter().map(|s| s.to_string()).collect();
        assert_eq!(
            tool_name_strings, public_names,
            "tool_names() drifted from build_tools() — keep them in sync"
        );

        for t in tools {
            assert!(
                passes_anthropic(&t.name),
                "tool name {:?} fails Anthropic regex \
                 ^[a-zA-Z0-9_-]{{1,64}}$ — see v0.3 lesson #8",
                t.name
            );
            assert!(
                passes_openai(&t.name),
                "tool name {:?} fails OpenAI function-calling regex \
                 ^[a-zA-Z_][a-zA-Z0-9_-]*$ (len ≤ 64)",
                t.name
            );
            assert!(
                passes_gemini(&t.name),
                "tool name {:?} fails Gemini function-calling regex \
                 ^[a-zA-Z_][a-zA-Z0-9_]*$ (len ≤ 63, strict)",
                t.name
            );
        }
    }

    /// Regression guard for the v0.5.0 Priority 4 jargon pass.
    ///
    /// Tool descriptions and `get_info().instructions` are the first
    /// (and often only) thing a calling LLM reads when its
    /// tool-search mechanism decides whether Solo's tools are
    /// relevant. Earlier descriptions leaned on Solo-internal
    /// vocabulary (`SPO`, `Steward`, `LEFT JOIN`, `candidate pair`,
    /// `tagged_with`) which doesn't pattern-match natural-language
    /// agent queries like "what do you know about Alex?" — that's
    /// the load-bearing v0.5.0 finding from the 2026-05-14
    /// thesis-test in Claude Desktop.
    ///
    /// This test pins the de-jargoning by forbidding the old
    /// vocabulary from appearing in any user-facing text. Future
    /// contributors who reach for jargon trip the test and have to
    /// pick plain-English phrasing instead.
    #[test]
    fn tool_descriptions_avoid_internal_jargon() {
        // Case-insensitive substring match. Drawn from the
        // pre-Priority-4 descriptions; expand only if a new term
        // creeps in.
        const FORBIDDEN: &[&str] = &[
            "SPO",
            "Steward",
            "Steward-flagged",
            "LEFT JOIN",
            "candidate pair",
            "candidate_pair",
            "tagged_with",
        ];

        fn contains_case_insensitive(haystack: &str, needle: &str) -> bool {
            haystack.to_lowercase().contains(&needle.to_lowercase())
        }

        // 1. Each tool description.
        for t in build_tools() {
            for term in FORBIDDEN {
                assert!(
                    !contains_case_insensitive(&t.description, term),
                    "tool {:?} description contains forbidden jargon \
                     {:?} — rewrite in plain English (see v0.5.0 \
                     Priority 4)",
                    t.name,
                    term,
                );
            }
        }

        // 2. The server-level instructions (what tool-search sees
        // first).
        let server_info = harness_server_info();
        let instructions = server_info
            .instructions
            .as_deref()
            .expect("get_info() must set instructions");
        for term in FORBIDDEN {
            assert!(
                !contains_case_insensitive(instructions, term),
                "get_info().instructions contains forbidden jargon \
                 {:?} — rewrite in plain English",
                term,
            );
        }
    }

    /// Build a `ServerInfo` for the jargon test without spinning up
    /// the full harness (which needs tokio + tempdir). The
    /// `ServerHandler::get_info()` method doesn't take `&self` state
    /// in any meaningful way for our impl — it returns a static
    /// `ServerInfo` literal — so we construct a minimal-input server
    /// just to call it.
    fn harness_server_info() -> rmcp::model::ServerInfo {
        let runtime = rt();
        let h = Harness::new(&runtime);
        let info = ServerHandler::get_info(&h.server);
        h.shutdown(&runtime);
        info
    }

    // ---- memory_inspect_cluster (v0.5.0 Priority 3) ----

    #[test]
    fn inspect_cluster_unknown_id_returns_invalid_params() {
        // NotFound from solo_query::inspect_cluster is mapped through
        // `solo_to_mcp` to `invalid_params` (MCP has no separate
        // not-found error shape). Error message should name the id.
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool(
                    "memory_inspect_cluster",
                    json!({ "cluster_id": "no-such-cluster" }),
                )
                .await
                .expect_err("unknown cluster must error");
            let s = format!("{err:?}");
            assert!(
                s.contains("no-such-cluster") || s.to_lowercase().contains("not found"),
                "expected error to mention the missing cluster id; got: {s}"
            );
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn inspect_cluster_rejects_empty_id() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool(
                    "memory_inspect_cluster",
                    json!({ "cluster_id": "   " }),
                )
                .await
                .expect_err("blank cluster_id must error");
            let s = format!("{err:?}");
            assert!(
                s.to_lowercase().contains("cluster_id")
                    || s.to_lowercase().contains("must not be empty"),
                "got: {s}"
            );
        });
        h.shutdown(&runtime);
    }

    // ---- Document tools (v0.7.0 P5) ----
    //
    // The five document handlers each have two arg-shape tests:
    //   - arg-struct parses from JSON (serde round-trip; defaults work).
    //   - dispatch arm routes to the handler (we observe behaviour via
    //     a known empty-DB response — bad routing surfaces as
    //     "unknown tool" or wrong shape).
    //
    // Functional coverage (ingest → search → inspect → forget) lives in
    // `crates/solo-cli/tests/mcp_smoke.rs` where a real subprocess + real
    // writer-with-embedder is wired up. The in-process Harness here uses
    // `WriterActor::spawn` which doesn't carry an embedder, so ingest /
    // search themselves return an error — but the dispatch + arg-parse
    // paths exercise correctly.

    #[test]
    fn ingest_document_args_parse_with_required_path() {
        let v: IngestDocumentArgs =
            serde_json::from_value(json!({ "path": "/tmp/notes.md" })).expect("parses");
        assert_eq!(v.path, "/tmp/notes.md");
        // path is required — missing must reject at deserialization.
        let err = serde_json::from_value::<IngestDocumentArgs>(json!({})).unwrap_err();
        assert!(format!("{err}").contains("path"));
    }

    #[test]
    fn search_docs_args_parse_with_default_limit() {
        let v: SearchDocsArgs =
            serde_json::from_value(json!({ "query": "backups" })).expect("parses");
        assert_eq!(v.query, "backups");
        assert_eq!(v.limit, 5, "default limit must be 5");
        let v: SearchDocsArgs =
            serde_json::from_value(json!({ "query": "backups", "limit": 20 })).expect("parses");
        assert_eq!(v.limit, 20);
    }

    #[test]
    fn inspect_document_args_parse_with_required_doc_id() {
        let v: InspectDocumentArgs =
            serde_json::from_value(json!({ "doc_id": "abc" })).expect("parses");
        assert_eq!(v.doc_id, "abc");
        let err = serde_json::from_value::<InspectDocumentArgs>(json!({})).unwrap_err();
        assert!(format!("{err}").contains("doc_id"));
    }

    #[test]
    fn list_documents_args_parse_with_all_defaults() {
        let v: ListDocumentsArgs = serde_json::from_value(json!({})).expect("parses");
        assert_eq!(v.limit, 20, "default limit must be 20");
        assert_eq!(v.offset, 0, "default offset must be 0");
        assert!(!v.include_forgotten, "default include_forgotten must be false");
        let v: ListDocumentsArgs = serde_json::from_value(
            json!({ "limit": 5, "offset": 10, "include_forgotten": true }),
        )
        .expect("parses");
        assert_eq!(v.limit, 5);
        assert_eq!(v.offset, 10);
        assert!(v.include_forgotten);
    }

    #[test]
    fn forget_document_args_parse_with_required_doc_id() {
        let v: ForgetDocumentArgs =
            serde_json::from_value(json!({ "doc_id": "abc" })).expect("parses");
        assert_eq!(v.doc_id, "abc");
        let err = serde_json::from_value::<ForgetDocumentArgs>(json!({})).unwrap_err();
        assert!(format!("{err}").contains("doc_id"));
    }

    #[test]
    fn ingest_document_rejects_empty_path() {
        // Reaches the dispatch arm → handle_ingest_document → empty
        // guard fires before the writer is touched. Proves routing.
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool("memory_ingest_document", json!({ "path": "" }))
                .await
                .expect_err("empty path must error");
            let s = format!("{err:?}");
            assert!(
                s.to_lowercase().contains("path")
                    || s.to_lowercase().contains("must not be empty"),
                "got: {s}"
            );
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn search_docs_rejects_empty_query() {
        // Empty query trips solo_query::run_doc_search's validation
        // → InvalidInput → invalid_params.
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool("memory_search_docs", json!({ "query": "   " }))
                .await
                .expect_err("empty query must error");
            let s = format!("{err:?}");
            assert!(
                s.to_lowercase().contains("must not be empty")
                    || s.to_lowercase().contains("invalid"),
                "got: {s}"
            );
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn inspect_document_unknown_id_returns_invalid_params() {
        // Valid UUID format but no row exists → handler returns
        // invalid_params with the missing id in the message.
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool(
                    "memory_inspect_document",
                    json!({ "doc_id": "00000000-0000-7000-8000-000000000000" }),
                )
                .await
                .expect_err("unknown doc must error");
            let s = format!("{err:?}");
            assert!(
                s.to_lowercase().contains("not found"),
                "expected 'not found' message; got: {s}"
            );
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn inspect_document_rejects_malformed_id() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool(
                    "memory_inspect_document",
                    json!({ "doc_id": "not-a-uuid" }),
                )
                .await
                .expect_err("malformed doc_id must error");
            let s = format!("{err:?}");
            assert!(s.contains("invalid doc_id"), "got: {s}");
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn list_documents_returns_empty_array_on_empty_db() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let r = h
                .server
                .dispatch_tool("memory_list_documents", json!({}))
                .await
                .expect("list succeeds");
            let text = first_text(&r);
            let v: serde_json::Value =
                serde_json::from_str(&text).expect("parses as json");
            assert!(v.is_array(), "expected array, got: {text}");
            assert_eq!(v.as_array().unwrap().len(), 0);
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn list_documents_passes_through_limit_offset_include_args() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let r = h
                .server
                .dispatch_tool(
                    "memory_list_documents",
                    json!({ "limit": 5, "offset": 10, "include_forgotten": true }),
                )
                .await
                .expect("list with args succeeds");
            let text = first_text(&r);
            let v: serde_json::Value =
                serde_json::from_str(&text).expect("parses as json");
            assert!(v.is_array());
        });
        h.shutdown(&runtime);
    }

    #[test]
    fn forget_document_rejects_malformed_id() {
        let runtime = rt();
        let h = Harness::new(&runtime);
        runtime.block_on(async {
            let err = h
                .server
                .dispatch_tool(
                    "memory_forget_document",
                    json!({ "doc_id": "not-a-uuid" }),
                )
                .await
                .expect_err("malformed doc_id must error");
            let s = format!("{err:?}");
            assert!(s.contains("invalid doc_id"), "got: {s}");
        });
        h.shutdown(&runtime);
    }
}

// fetch_recall_rows + RecallHit + RecallRow used to live here. Recall
// pipeline moved to solo_query::recall in commit (consolidate-recall);
// transports just call solo_query::run_recall and format the result.