solo-api 0.4.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
// SPDX-License-Identifier: Apache-2.0

//! MCP (Model Context Protocol) server for Solo.
//!
//! Exposes four tools to MCP clients (Claude Desktop, Cursor, etc.):
//!
//!   - `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.
//!
//! ## 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, 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>,
}

impl SoloMcpServer {
    pub fn new(
        write: WriteHandle,
        pool: ReaderPool,
        embedder: Arc<dyn Embedder>,
        hnsw: Arc<dyn VectorIndex + Send + Sync>,
    ) -> Self {
        Self {
            inner: Arc::new(Inner {
                write,
                pool,
                embedder,
                hnsw,
            }),
        }
    }
}

/// 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>,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

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

// ---------------------------------------------------------------------------
// 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: local-first personal memory for LLMs. \
                 Episode tools: memory.remember (store), \
                 memory.recall (vector search), memory.forget \
                 (soft-delete), memory.inspect (full record by id). \
                 Derived-layer tools (queries against the Steward's \
                 outputs from `solo consolidate`): memory.themes \
                 (cluster abstractions), memory.facts_about \
                 (subject-predicate-object knowledge graph), \
                 memory.contradictions (flagged disagreements between \
                 facts)."
                    .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
            }
            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",
            "Store a new episodic memory. Returns the new MemoryId (UUID v7).",
            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",
            "Vector-search the memory store. Returns up to `limit` results \
             ordered by cosine distance (smaller = more similar). Excludes \
             forgotten memories.",
            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",
            "Soft-delete a memory by id. The HNSW vector stays in the graph \
             but the SQL row's status flips to 'forgotten' so future recalls \
             exclude it.",
            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",
            "Return the full record for a memory_id (timestamps, source, \
             status, scoring values, content).",
            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",
            "List recent cluster themes (the Steward's grouping of \
             related episodes) with their LLM-generated abstractions. \
             Use this to ask 'what has the user been thinking about \
             lately' before deciding whether to drill into specific \
             episodes via memory.recall. Returns up to `limit` results \
             ordered by most-recent cluster first; pass `window_days` \
             to scope to e.g. the last week.",
            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",
            "Query the structured-fact knowledge graph (subject-\
             predicate-object triples extracted by the Steward) by \
             subject + optional predicate + optional time window. Use \
             this to ground answers on distilled facts rather than raw \
             episodes. Subject is required; predicate-only scans are \
             not supported.",
            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.",
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results (default 5).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                },
                "required": ["subject"],
            })),
        ),
        Tool::new(
            "memory.contradictions",
            "List Steward-flagged contradictions (pairs of triples that \
             disagree). Each result includes both sides' triple SPO via \
             LEFT JOIN for context. Use this to surface conflicts and \
             ask the user to disambiguate before relying on memory \
             content.",
            json_schema_object(serde_json::json!({
                "type": "object",
                "properties": {
                    "limit": {
                        "type": "integer",
                        "description": "Maximum results (default 5).",
                        "minimum": 1,
                        "maximum": 100,
                    },
                },
            })),
        ),
    ]
}

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"),
    }
}

// ---------------------------------------------------------------------------
// 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,
            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)]))
    }
}

#[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_seven_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",
            ]
        );
        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 (all args optional with defaults).
            // memory.facts_about does have required = ["subject"].
            // 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 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);
    }
}

// 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.