mentedb-mcp 0.4.3

MCP server for MenteDB, the cognition aware database for AI agent memory
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
// Integration tests for mentedb-mcp.
//
// Each test spawns the binary as a child process with stdio transport,
// sends JSON-RPC messages, and verifies responses. This exercises the
// full MCP protocol end-to-end.

use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};

use serde_json::{Value, json};

// -- Helpers --

fn binary_path() -> PathBuf {
    let path = env!("CARGO_BIN_EXE_mentedb-mcp");
    PathBuf::from(path)
}

fn temp_data_dir(test_name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "mentedb-mcp-test-{}-{}",
        test_name,
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

struct McpProcess {
    child: std::process::Child,
    stdin: std::process::ChildStdin,
    reader: BufReader<std::process::ChildStdout>,
    data_dir: PathBuf,
    next_id: u64,
}

impl McpProcess {
    fn spawn(test_name: &str) -> Self {
        let data_dir = temp_data_dir(test_name);
        let mut child = Command::new(binary_path())
            .arg("--data-dir")
            .arg(&data_dir)
            .arg("--embedding-dim")
            .arg("128")
            .arg("--llm-provider")
            .arg("mock")
            .arg("--full-tools")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .expect("failed to spawn mentedb-mcp");

        let stdin = child.stdin.take().unwrap();
        let stdout = child.stdout.take().unwrap();
        let reader = BufReader::new(stdout);

        McpProcess {
            child,
            stdin,
            reader,
            data_dir,
            next_id: 1,
        }
    }

    fn send(&mut self, msg: &Value) {
        let s = serde_json::to_string(msg).unwrap();
        writeln!(self.stdin, "{s}").unwrap();
        self.stdin.flush().unwrap();
    }

    fn recv(&mut self) -> Value {
        let mut line = String::new();
        self.reader.read_line(&mut line).unwrap();
        serde_json::from_str(line.trim()).unwrap_or_else(|e| {
            panic!("failed to parse JSON-RPC response: {e}\nraw: {line}");
        })
    }

    fn initialize(&mut self) -> Value {
        let id = self.next_id;
        self.next_id += 1;
        self.send(&json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": { "name": "integration-test", "version": "1.0.0" }
            }
        }));
        let resp = self.recv();

        // Send initialized notification (no response expected)
        self.send(&json!({
            "jsonrpc": "2.0",
            "method": "notifications/initialized"
        }));

        // Give the server time to process the notification
        std::thread::sleep(std::time::Duration::from_millis(100));

        resp
    }

    fn call_tool(&mut self, name: &str, arguments: Value) -> Value {
        let id = self.next_id;
        self.next_id += 1;
        self.send(&json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": "tools/call",
            "params": {
                "name": name,
                "arguments": arguments,
            }
        }));
        self.recv()
    }

    fn tool_result_text(&mut self, name: &str, arguments: Value) -> Value {
        let resp = self.call_tool(name, arguments);
        eprintln!("DEBUG [{name}]: {resp}");
        let content = resp["result"]["content"]
            .as_array()
            .expect("expected content array");
        assert!(!content.is_empty(), "expected at least one content item");
        let text = content[0]["text"].as_str().expect("expected text content");
        serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_string()))
    }
}

impl Drop for McpProcess {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
        let _ = std::fs::remove_dir_all(&self.data_dir);
    }
}

// -- Tests --

#[test]
fn test_initialize_returns_server_info() {
    let mut proc = McpProcess::spawn("init");
    let resp = proc.initialize();

    assert_eq!(resp["jsonrpc"], "2.0");
    assert!(resp["error"].is_null(), "unexpected error: {resp}");

    let result = &resp["result"];
    let info = &result["serverInfo"];
    assert_eq!(info["name"], "mentedb-mcp");
    assert!(!info["version"].as_str().unwrap().is_empty());

    let caps = &result["capabilities"];
    assert!(caps["tools"].is_object(), "expected tools capability");
}

#[test]
fn test_store_and_recall_memory() {
    let mut proc = McpProcess::spawn("store_recall");
    proc.initialize();

    let stored = proc.tool_result_text(
        "store_memory",
        json!({
            "content": "Rust ownership prevents data races at compile time",
            "memory_type": "semantic",
        }),
    );
    assert_eq!(stored["status"], "stored");
    let id = stored["id"].as_str().unwrap();
    assert!(!id.is_empty());

    let recalled = proc.tool_result_text("recall_memory", json!({ "id": id }));
    assert_eq!(
        recalled["content"],
        "Rust ownership prevents data races at compile time"
    );
    assert_eq!(recalled["memory_type"], "Semantic");
}

#[test]
fn test_store_and_search_memories() {
    let mut proc = McpProcess::spawn("store_search");
    proc.initialize();

    proc.tool_result_text(
        "store_memory",
        json!({
            "content": "Tokio is an async runtime for Rust",
            "memory_type": "semantic",
        }),
    );
    proc.tool_result_text(
        "store_memory",
        json!({
            "content": "Serde handles serialization in Rust",
            "memory_type": "semantic",
        }),
    );

    let results = proc.tool_result_text(
        "search_memories",
        json!({
            "query": "async runtime",
            "limit": 5,
        }),
    );
    let count = results["count"].as_u64().unwrap();
    assert!(count >= 1, "expected at least 1 search result, got {count}");
}

#[test]
fn test_store_relate_and_get_related() {
    let mut proc = McpProcess::spawn("relate");
    proc.initialize();

    let a = proc.tool_result_text(
        "store_memory",
        json!({
            "content": "HTTP is a request-response protocol",
            "memory_type": "semantic",
        }),
    );
    let b = proc.tool_result_text(
        "store_memory",
        json!({
            "content": "REST APIs typically use HTTP",
            "memory_type": "semantic",
        }),
    );

    let id_a = a["id"].as_str().unwrap();
    let id_b = b["id"].as_str().unwrap();

    let rel = proc.tool_result_text(
        "relate_memories",
        json!({
            "from_id": id_a,
            "to_id": id_b,
            "edge_type": "related",
        }),
    );
    assert_eq!(rel["status"], "related");

    let related = proc.tool_result_text(
        "get_related",
        json!({
            "id": id_a,
            "depth": 1,
        }),
    );
    let items = related["related"].as_array().unwrap();
    assert!(!items.is_empty(), "expected related memories");
    let found = items.iter().any(|r| r["id"].as_str().unwrap() == id_b);
    assert!(found, "expected to find memory B in related results");
}

#[test]
fn test_store_and_forget_memory() {
    let mut proc = McpProcess::spawn("forget");
    proc.initialize();

    let stored = proc.tool_result_text(
        "store_memory",
        json!({
            "content": "Temporary note to be deleted",
            "memory_type": "episodic",
        }),
    );
    let id = stored["id"].as_str().unwrap();

    let forgot = proc.tool_result_text(
        "forget_memory",
        json!({
            "id": id,
            "reason": "test cleanup",
        }),
    );
    assert_eq!(forgot["status"], "forgotten");

    // Recall should fail after forget
    let recalled = proc.tool_result_text("recall_memory", json!({ "id": id }));
    let text = recalled.as_str().unwrap_or("");
    let is_err = text.contains("not found") || text.contains("Not found");
    // Also check for isError in the raw response
    let raw = proc.call_tool("recall_memory", json!({ "id": id }));
    let is_error_flag = raw["result"]["isError"].as_bool().unwrap_or(false);
    assert!(
        is_err || is_error_flag,
        "expected recall to fail after forget, got: {recalled}"
    );
}

#[test]
fn test_search_with_type_filter() {
    let mut proc = McpProcess::spawn("type_filter");
    proc.initialize();

    proc.tool_result_text(
        "store_memory",
        json!({
            "content": "Today I learned about pattern matching",
            "memory_type": "episodic",
        }),
    );
    proc.tool_result_text(
        "store_memory",
        json!({
            "content": "Pattern matching is a control flow construct",
            "memory_type": "semantic",
        }),
    );

    let results = proc.tool_result_text(
        "search_memories",
        json!({
            "query": "pattern matching",
            "limit": 10,
            "memory_type": "semantic",
        }),
    );
    let items = results["results"].as_array().unwrap();
    for item in items {
        assert_eq!(
            item["memory_type"], "Semantic",
            "expected only Semantic memories with type filter"
        );
    }
}

#[test]
fn test_record_pain_and_cognitive_state() {
    let mut proc = McpProcess::spawn("pain");
    proc.initialize();

    let stored = proc.tool_result_text(
        "store_memory",
        json!({
            "content": "Accidentally deleted production database",
            "memory_type": "episodic",
        }),
    );
    let memory_id = stored["id"].as_str().unwrap();

    let pain = proc.tool_result_text(
        "record_pain",
        json!({
            "memory_id": memory_id,
            "intensity": 0.9,
            "trigger_keywords": ["delete", "production", "database"],
            "description": "Never run destructive commands on production without backup",
        }),
    );
    assert_eq!(pain["status"], "recorded");

    let state = proc.tool_result_text("get_cognitive_state", json!({}));
    let pain_signals = state["pain_signals"].as_array().unwrap();
    assert!(
        !pain_signals.is_empty(),
        "expected at least one pain signal"
    );
    let found = pain_signals
        .iter()
        .any(|s| s["memory_id"].as_str().unwrap() == memory_id);
    assert!(found, "expected pain signal for the stored memory");
}

#[test]
fn test_detect_phantoms() {
    let mut proc = McpProcess::spawn("phantoms");
    proc.initialize();

    let result = proc.tool_result_text("detect_phantoms", json!({
        "content": "The FrobnicatorService handles all frobbing operations and communicates with the BarManager",
        "known_entities": ["BarManager"],
    }));
    // The detector should identify FrobnicatorService as a phantom (unknown entity)
    assert!(
        result["count"].is_number(),
        "expected count field in phantom response"
    );
}

#[test]
fn test_process_turn() {
    let mut proc = McpProcess::spawn("process_turn");
    proc.initialize();

    let result = proc.tool_result_text(
        "process_turn",
        json!({
            "user_message": "I prefer using Rust for all backend services",
            "assistant_response": "Noted, I will use Rust for backend work going forward.",
            "turn_id": 1,
            "project_context": "my-project",
        }),
    );

    assert!(result["ok"].as_bool().unwrap());
    assert!(result["context"].is_array());
    assert!(result["stored"].is_number());
    assert!(result["pain_warnings"].is_array());
    assert!(result["inference_applied"].is_number());
    assert!(result["contradictions"].is_number());
    assert!(result["phantoms"].is_number());
    assert!(result["predictions"].is_array());
}

#[test]
fn test_forget_all() {
    let mut proc = McpProcess::spawn("forget_all");
    proc.initialize();

    // Forget all without confirmation should fail (isError response)
    let resp = proc.call_tool("forget_all", json!({ "confirm": "nope" }));
    let content = resp["result"]["content"].as_array().unwrap();
    let text = content[0]["text"].as_str().unwrap();
    assert!(text.contains("Safety check"), "expected safety check error");

    // Forget all with confirmation should succeed
    let result = proc.tool_result_text(
        "forget_all",
        json!({ "confirm": "CONFIRM", "reason": "test reset" }),
    );
    assert_eq!(result["status"], "reset_complete");
}