semantic-memory-mcp 0.3.0

MCP server wrapping semantic-memory — local-first knowledge management with evidence-scored retrieval, contradiction detection, and adaptive routing
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
//! Integration tests for semantic-memory-mcp.
//!
//! These tests exercise the MemoryBridge + HTTP server end-to-end using
//! the mock embedder (no model download, no Ollama, no network).
//! Each test gets a fresh temp directory so there is no cross-test state.

use semantic_memory_mcp::bridge::{BridgeConfig, EmbedderBackend, MemoryBridge};
use semantic_memory::GraphEdgeType;

/// Open a MemoryBridge with the mock embedder in a temp directory.
fn open_bridge(dir: &std::path::Path) -> MemoryBridge {
    let config = BridgeConfig {
        memory_dir: dir.to_path_buf(),
        embedder_backend: EmbedderBackend::Mock,
        embedding_url: "http://localhost:11434".to_string(),
        embedding_model: "nomic-embed-text".to_string(),
        embedding_dims: 768,
        turbo_quant_enabled: false,
        turbo_quant_bits: None,
        turbo_quant_projections: None,
    };
    MemoryBridge::open(config).expect("bridge should open")
}

/// Helper: add a fact via the underlying store and return its fact_id.
fn add_fact(bridge: &MemoryBridge, content: &str, namespace: &str) -> String {
    let store = &bridge.store;
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(store.add_fact(namespace, content, None, None))
        .expect("add_fact should succeed")
}

mod bridge_tests {
    use super::*;

    #[test]
    fn bridge_opens_with_mock_embedder() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        assert!(dir.path().join("memory.db").exists());
        let _ = &bridge.store;
    }

    #[test]
    fn bridge_rejects_unknown_embedder_string() {
        let result: Result<EmbedderBackend, _> = "garbage".parse();
        assert!(result.is_err());
    }

    #[test]
    fn bridge_parses_embedder_variants() {
        assert_eq!(
            "candle".parse::<EmbedderBackend>().unwrap(),
            EmbedderBackend::Candle
        );
        assert_eq!(
            "CANDLE".parse::<EmbedderBackend>().unwrap(),
            EmbedderBackend::Candle
        );
        assert_eq!(
            "ollama".parse::<EmbedderBackend>().unwrap(),
            EmbedderBackend::Ollama
        );
        assert_eq!(
            "mock".parse::<EmbedderBackend>().unwrap(),
            EmbedderBackend::Mock
        );
    }
}

mod lifecycle_tests {
    use super::*;

    #[test]
    fn add_and_search_fact() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let id = add_fact(
            &bridge,
            "Rust is a systems programming language focused on safety and performance.",
            "coding",
        );
        assert!(!id.is_empty(), "fact_id should be non-empty");

        let store = &bridge.store;
        let rt = tokio::runtime::Runtime::new().unwrap();
        let results = rt
            .block_on(store.search("Rust programming safety", Some(10), None, None))
            .expect("search should succeed");
        assert!(!results.is_empty(), "search should return results");
        let found = results.iter().any(|r| r.content.contains("Rust"));
        assert!(found, "search should find the Rust fact");
    }

    #[test]
    fn add_facts_in_multiple_namespaces_and_filter() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        add_fact(
            &bridge,
            "Python is great for data science and ML pipelines.",
            "coding",
        );
        add_fact(
            &bridge,
            "The cat sat on the mat in Albertville Alabama.",
            "personal",
        );

        let store = &bridge.store;
        let rt = tokio::runtime::Runtime::new().unwrap();

        // Search without filter
        let all = rt
            .block_on(store.search("cat mat Albertville", Some(10), None, None))
            .expect("search should succeed");
        assert!(!all.is_empty());

        // Search with namespace filter
        let filtered = rt
            .block_on(store.search("cat mat", Some(10), Some(&["personal"]), None))
            .expect("search should succeed");
        assert!(!filtered.is_empty());
        let all_personal = filtered
            .iter()
            .all(|r| r.content.contains("cat") || r.content.contains("Albertville"));
        assert!(
            all_personal,
            "filtered results should all be from personal namespace"
        );
    }

    #[test]
    fn supersede_fact_via_graph_edge() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let old_id = add_fact(&bridge, "turbo-quant has 1000 downloads.", "libraries");

        let store = &bridge.store;
        let rt = tokio::runtime::Runtime::new().unwrap();

        // Supersede: add new fact, create supersedes edge
        let new_id = rt
            .block_on(store.add_fact("libraries", "turbo-quant has 4000 downloads.", None, None))
            .expect("add replacement should succeed");
        let old_node = format!("fact:{}", old_id);
        let new_node = format!("fact:{}", new_id);
        rt.block_on(store.add_graph_edge(
            &new_node,
            &old_node,
            GraphEdgeType::Entity {
                relation: "supersedes".to_string(),
            },
            1.0,
            None,
        ))
        .expect("add supersedes edge should succeed");

        // Search should filter superseded facts
        let results = rt
            .block_on(store.search("turbo-quant downloads", Some(10), None, None))
            .expect("search should succeed");
        let has_old = results
            .iter()
            .any(|r| r.content.contains("1000 downloads"));
        let has_new = results
            .iter()
            .any(|r| r.content.contains("4000 downloads"));
        assert!(has_new, "new fact should appear in search");
        // Old fact may or may not be filtered depending on search filter logic,
        // but the edge should exist
    }

    #[test]
    fn delete_fact_removes_it() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let id = add_fact(&bridge, "Temporary fact to be deleted.", "test");
        let store = &bridge.store;
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(store.delete_fact(&id))
            .expect("delete should succeed");
        let fact = rt.block_on(store.get_fact(&id));
        assert!(
            fact.is_err() || fact.is_ok_and(|f| f.is_none()),
            "deleted fact should not be retrievable"
        );
    }

    #[test]
    fn list_namespaces_returns_all() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        add_fact(&bridge, "Fact in namespace alpha.", "alpha");
        add_fact(&bridge, "Fact in namespace beta.", "beta");
        add_fact(&bridge, "Fact in namespace gamma.", "gamma");

        let store = &bridge.store;
        let rt = tokio::runtime::Runtime::new().unwrap();
        let namespaces = rt
            .block_on(store.list_fact_namespaces())
            .expect("list_fact_namespaces should succeed");
        assert!(
            namespaces.len() >= 3,
            "should have at least 3 namespaces, got: {:?}",
            namespaces
        );
        assert!(namespaces.contains(&"alpha".to_string()));
        assert!(namespaces.contains(&"beta".to_string()));
        assert!(namespaces.contains(&"gamma".to_string()));
    }

    #[test]
    fn add_and_list_graph_edges() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let id_a = add_fact(&bridge, "Fact A about semantic search.", "graph");
        let id_b = add_fact(&bridge, "Fact B about vector databases.", "graph");

        let store = &bridge.store;
        let rt = tokio::runtime::Runtime::new().unwrap();

        let source = format!("fact:{}", id_a);
        let target = format!("fact:{}", id_b);
        rt.block_on(store.add_graph_edge(
            &source,
            &target,
            GraphEdgeType::Semantic {
                cosine_similarity: 0.85,
            },
            1.0,
            None,
        ))
        .expect("add_graph_edge should succeed");

        let edges = rt
            .block_on(store.list_graph_edges_for_node(&source))
            .expect("list_graph_edges should succeed");
        assert!(
            !edges.is_empty(),
            "should have at least one edge from A"
        );
        let found = edges.iter().any(|e| e.target == target);
        assert!(found, "should find the edge A->B");
    }

    #[test]
    fn stats_returns_counts() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        add_fact(&bridge, "Fact for stats test.", "stats_ns");
        let store = &bridge.store;
        let rt = tokio::runtime::Runtime::new().unwrap();
        let stats = rt
            .block_on(store.stats())
            .expect("stats should succeed");
        assert!(
            stats.total_facts >= 1,
            "should have at least 1 fact, got: {}",
            stats.total_facts
        );
    }
}

mod http_server_tests {
    use super::*;
    use std::io::{Read, Write};
    use std::net::TcpStream;

    /// Start the HTTP server on a random port and return the port.
    /// Returns (port, runtime) — the runtime must stay alive while making requests.
    fn start_http(bridge: MemoryBridge) -> (u16, tokio::runtime::Runtime) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        drop(listener);

        let rt = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .worker_threads(2)
            .build()
            .unwrap();

        let handle = rt.handle().clone();
        let _enter = rt.enter();
        std::thread::spawn(move || {
            let _guard = handle.enter();
            semantic_memory_mcp::http_server::start_http_server(port, bridge, handle);
        });

        // Give the server a moment to bind
        std::thread::sleep(std::time::Duration::from_millis(100));
        (port, rt)
    }

    fn http_get(port: u16, path: &str) -> (String, String) {
        let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
        let request = format!(
            "GET {} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
            path
        );
        stream.write_all(request.as_bytes()).unwrap();
        let mut response = String::new();
        stream.read_to_string(&mut response).unwrap();
        let body_start = response
            .find("\r\n\r\n")
            .map(|i| response[i + 4..].to_string())
            .unwrap_or_default();
        (response, body_start)
    }

    fn http_post(port: u16, path: &str, body: &str) -> (String, String) {
        let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
        let request = format!(
            "POST {} HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            path,
            body.len(),
            body
        );
        stream.write_all(request.as_bytes()).unwrap();
        let mut response = String::new();
        stream.read_to_string(&mut response).unwrap();
        let body_start = response
            .find("\r\n\r\n")
            .map(|i| response[i + 4..].to_string())
            .unwrap_or_default();
        (response, body_start)
    }

    #[test]
    fn health_endpoint_returns_ok() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let (port, _rt) = start_http(bridge);
        let (response, body) = http_get(port, "/health");
        assert!(
            response.contains("200 OK"),
            "health should return 200, got: {}",
            response
        );
        let json: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
        assert_eq!(json["ok"], serde_json::Value::Bool(true));
        assert_eq!(json["service"], "semantic-memory-mcp");
    }

    #[test]
    fn add_and_search_via_http() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let (port, _rt) = start_http(bridge);

        // Add a fact
        let (_, add_body) = http_post(
            port,
            "/add",
            r#"{"content": "Hermes Agent is a CLI AI agent by Nous Research.", "namespace": "test"}"#,
        );
        let add_json: serde_json::Value = serde_json::from_str(&add_body).expect("valid JSON");
        assert!(
            add_json["ok"] == serde_json::Value::Bool(true),
            "add should return ok=true, got: {}",
            add_body
        );
        assert!(
            add_json["fact_id"].is_string(),
            "fact_id should be a string"
        );

        // Search for it
        let (_, search_body) = http_post(
            port,
            "/search",
            r#"{"query": "Hermes Agent CLI", "top_k": 5}"#,
        );
        let search_json: serde_json::Value =
            serde_json::from_str(&search_body).expect("valid JSON");
        assert_eq!(search_json["ok"], serde_json::Value::Bool(true));
        let results = search_json["results"]
            .as_array()
            .expect("results should be array");
        assert!(!results.is_empty(), "search should return results");
        let found = results.iter().any(|r| {
            r["content"]
                .as_str()
                .map(|c| c.contains("Hermes"))
                .unwrap_or(false)
        });
        assert!(found, "should find the Hermes fact in search results");
    }

    #[test]
    fn stats_endpoint_returns_counts() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let (port, _rt) = start_http(bridge);

        let (add_response, add_body) = http_post(
            port,
            "/add",
            r#"{"content": "Test fact for stats.", "namespace": "stats"}"#,
        );
        assert!(add_response.contains("200 OK"), "add should succeed: {}", add_body);

        let (_, body) = http_post(port, "/stats", "{}");
        let json: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
        assert_eq!(json["ok"], serde_json::Value::Bool(true));
        assert!(
            json["facts"].as_u64().unwrap_or(0) >= 1,
            "should have >= 1 fact, got: {}",
            body
        );
    }

    #[test]
    fn unknown_path_returns_404() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let (port, _rt) = start_http(bridge);
        let (response, body) = http_get(port, "/nonexistent");
        assert!(
            response.contains("404 Not Found"),
            "unknown path should 404"
        );
        let json: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
        assert_eq!(json["error"], "not found");
    }

    #[test]
    fn search_with_empty_query_returns_400() {
        let dir = tempfile::tempdir().unwrap();
        let bridge = open_bridge(dir.path());
        let (port, _rt) = start_http(bridge);
        let (response, body) = http_post(port, "/search", r#"{"query": ""}"#);
        assert!(
            response.contains("400 Bad Request"),
            "empty query should 400"
        );
        let json: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
        assert_eq!(json["ok"], serde_json::Value::Bool(false));
    }
}