codex-memory 3.0.15

A simple memory storage service with MCP interface for Claude Desktop
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
use crate::common::TestDatabaseManager;
use anyhow::Result;
use codex_memory::mcp_server::MCPHandlers;
use codex_memory::Storage;
use serde_json::json;
use serial_test::serial;
use std::sync::Arc;

#[tokio::test]
#[serial]
async fn test_mcp_store_with_all_fields() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Simulate MCP tool call with all fields
    let params = json!({
        "content": "Test content for MCP integration",
        "context": "Integration test context",
        "summary": "Testing MCP with all fields populated",
        "tags": ["mcp", "integration", "test"]
    });

    let result = handlers.handle_tool_call("store_memory", params).await?;

    // Verify response
    assert!(result["id"].is_string());
    assert_eq!(result["message"], "Memory stored successfully");

    // Retrieve and verify
    let id = result["id"].as_str().unwrap();
    let get_params = json!({"id": id});
    let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

    assert_eq!(retrieved["content"], "Test content for MCP integration");
    assert_eq!(retrieved["context"], "Integration test context");
    assert_eq!(
        retrieved["summary"],
        "Testing MCP with all fields populated"
    );
    assert_eq!(retrieved["tags"], json!(["mcp", "integration", "test"]));

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_store_content_only() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Simulate MCP tool call with minimal required fields
    let params = json!({
        "content": "Just the content, nothing else",
        "context": "Default context",
        "summary": "Default summary",
        "tags": []
    });

    let result = handlers.handle_tool_call("store_memory", params).await?;

    // Should succeed with minimal required fields
    assert!(result["id"].is_string());
    assert_eq!(result["message"], "Memory stored successfully");

    // Retrieve and verify fields
    let id = result["id"].as_str().unwrap();
    let get_params = json!({"id": id});
    let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

    assert_eq!(retrieved["content"], "Just the content, nothing else");
    assert_eq!(retrieved["context"], "Default context");
    assert_eq!(retrieved["summary"], "Default summary");
    assert_eq!(retrieved["tags"], json!([]));

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_store_with_partial_fields() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Test with context and summary provided
    let params = json!({
        "content": "Content with summary but minimal context",
        "context": "Partial test context",
        "summary": "A brief summary",
        "tags": ["partial"]
    });

    let result = handlers.handle_tool_call("store_memory", params).await?;
    assert!(result["id"].is_string());

    let id = result["id"].as_str().unwrap();
    let get_params = json!({"id": id});
    let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

    assert_eq!(retrieved["summary"], "A brief summary");
    assert_eq!(retrieved["context"], "Partial test context");
    assert_eq!(retrieved["tags"], json!(["partial"]));

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_delete_memory() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Store a memory
    let store_params = json!({
        "content": "Content to be deleted",
        "context": "Test delete context",
        "summary": "Test delete summary",
        "tags": []
    });
    let store_result = handlers
        .handle_tool_call("store_memory", store_params)
        .await?;
    let id = store_result["id"].as_str().unwrap();

    // Delete it
    let delete_params = json!({"id": id});
    let delete_result = handlers
        .handle_tool_call("delete_memory", delete_params)
        .await?;

    assert_eq!(delete_result["deleted"], true);
    assert_eq!(delete_result["message"], "Memory deleted successfully");

    // Try to get it - should fail
    let get_params = json!({"id": id});
    let get_result = handlers.handle_tool_call("get_memory", get_params).await;
    assert!(get_result.is_err());

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_get_statistics() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Get initial stats
    let stats = handlers
        .handle_tool_call("get_statistics", json!({}))
        .await?;
    assert_eq!(stats["total_memories"], 0);

    // Store some memories
    for i in 0..3 {
        let params = json!({
            "content": format!("Memory {}", i),
            "context": format!("Context for memory {}", i),
            "summary": format!("Summary for memory {}", i),
            "tags": []
        });
        handlers.handle_tool_call("store_memory", params).await?;
    }

    // Get updated stats
    let stats = handlers
        .handle_tool_call("get_statistics", json!({}))
        .await?;
    assert_eq!(stats["total_memories"], 3);
    assert!(stats["last_memory_created"].is_string());

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_error_handling() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Test missing content parameter
    let params = json!({
        "summary": "Summary without content"
    });
    let result = handlers.handle_tool_call("store_memory", params).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Missing content"));

    // Test invalid UUID
    let params = json!({"id": "not-a-uuid"});
    let result = handlers.handle_tool_call("get_memory", params).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Invalid UUID"));

    // Test non-existent memory
    let params = json!({"id": "00000000-0000-0000-0000-000000000000"});
    let result = handlers.handle_tool_call("get_memory", params).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Memory not found"));

    // Test unknown tool
    let result = handlers.handle_tool_call("unknown_tool", json!({})).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Unknown tool"));

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_content_not_modified() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Test various content that should be stored exactly as-is
    let test_contents = vec![
        "Plain text",
        "Text with 'single quotes'",
        r#"Text with "double quotes""#,
        "Multi\nline\ntext",
        "Text with special chars: !@#$%^&*()",
        "   Spaces at start and end   ",
        "Text\twith\ttabs",
        "Emoji content 🎉 🚀 💾",
    ];

    for content in test_contents {
        let params = json!({
            "content": content,
            "context": "Content preservation test",
            "summary": "Testing content storage without modification",
            "tags": []
        });

        let result = handlers.handle_tool_call("store_memory", params).await?;
        let id = result["id"].as_str().unwrap();

        let get_params = json!({"id": id});
        let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

        assert_eq!(
            retrieved["content"].as_str().unwrap(),
            content,
            "Content should be stored without modification"
        );
    }

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_multiple_storage_operations() -> Result<()> {
    // Use TestDatabaseManager for proper isolation
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Test multiple storage operations with different content
    let test_cases = [
        ("First test content", "programming", "testing"),
        ("Second test content", "debugging", "validation"),
        ("Third test content", "documentation", "writing"),
    ];

    for (i, (content, tag1, tag2)) in test_cases.iter().enumerate() {
        let params = json!({
            "content": format!("{} - {}", content, i),
            "context": format!("Test context for operation {}", i),
            "summary": format!("Test summary for operation {}", i),
            "tags": [tag1, tag2, "mcp-test"]
        });

        let result = handlers.handle_tool_call("store_memory", params).await?;
        let id = result["id"].as_str().unwrap();

        let get_params = json!({"id": id});
        let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

        // Verify content is stored correctly
        assert_eq!(retrieved["content"], format!("{} - {}", content, i));
        assert_eq!(retrieved["tags"], json!([tag1, tag2, "mcp-test"]));
    }

    // Cleanup
    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_search_memory_basic() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Store some test memories
    let memories = [
        (
            "Rust programming tutorial",
            "Programming guide",
            "Learn Rust basics",
            vec!["rust", "programming"],
        ),
        (
            "Python data analysis",
            "Data science context",
            "Analyze data with Python",
            vec!["python", "data-science"],
        ),
        (
            "Web development tips",
            "Frontend development",
            "Modern web development practices",
            vec!["web", "frontend"],
        ),
    ];

    for (content, context, summary, tags) in memories {
        let params = json!({
            "content": content,
            "context": context,
            "summary": summary,
            "tags": tags
        });
        handlers.handle_tool_call("store_memory", params).await?;
    }

    // Test basic search
    let search_params = json!({
        "query": "programming"
    });

    let results = handlers
        .handle_tool_call("search_memory", search_params)
        .await?;

    // Search results are returned as a direct array for Claude Desktop compatibility
    assert!(results.is_array(), "Search should return array of results");

    let results_array = results.as_array().unwrap();
    assert!(
        !results_array.is_empty(),
        "Should find programming-related results"
    );

    // Verify first result has expected structure
    let first_result = &results_array[0];
    assert!(first_result["id"].is_string());
    assert!(first_result["content"].is_string());
    assert!(first_result["combined_score"].is_number());

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_search_memory_with_filters() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Store memories with different tags
    let memories = [
        (
            "Rust web framework",
            "Web development",
            "Building web apps with Rust",
            vec!["rust", "web"],
        ),
        (
            "Python web framework",
            "Web development",
            "Building web apps with Python",
            vec!["python", "web"],
        ),
        (
            "Database design",
            "Backend development",
            "Database schema design principles",
            vec!["database", "backend"],
        ),
    ];

    for (content, context, summary, tags) in memories {
        let params = json!({
            "content": content,
            "context": context,
            "summary": summary,
            "tags": tags
        });
        handlers.handle_tool_call("store_memory", params).await?;
    }

    // Search with tag filter
    let search_params = json!({
        "query": "web",
        "tag_filter": ["rust"],
        "max_results": 5
    });

    let results = handlers
        .handle_tool_call("search_memory", search_params)
        .await?;
    let results_array = results.as_array().unwrap();

    // Should only return Rust-related results
    for result in results_array {
        let tags = result["tags"].as_array().unwrap();
        let tag_strings: Vec<String> = tags
            .iter()
            .map(|t| t.as_str().unwrap().to_string())
            .collect();
        assert!(
            tag_strings.contains(&"rust".to_string()),
            "Result should contain rust tag"
        );
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_search_memory_different_strategies() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Store test memory
    let params = json!({
        "content": "Machine learning algorithms and techniques",
        "context": "AI research context",
        "summary": "Overview of ML algorithms",
        "tags": ["machine-learning", "ai", "algorithms"]
    });
    handlers.handle_tool_call("store_memory", params).await?;

    // Test different search strategies
    let strategies = ["TagsFirst", "ContentFirst", "Hybrid"];

    for strategy in strategies {
        let search_params = json!({
            "query": "machine learning",
            "search_strategy": strategy,
            "similarity_threshold": 0.1
        });

        let result = handlers
            .handle_tool_call("search_memory", search_params)
            .await;
        assert!(
            result.is_ok(),
            "Search should succeed for strategy: {}",
            strategy
        );

        let results = result.unwrap();
        assert!(
            results["search_metadata"]["search_strategy"]
                .as_str()
                .unwrap()
                == strategy
        );
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_search_memory_parameters() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Store multiple memories
    for i in 1..=10 {
        let params = json!({
            "content": format!("Test memory content number {}", i),
            "context": "Test context",
            "summary": "Test summary",
            "tags": ["test"]
        });
        handlers.handle_tool_call("store_memory", params).await?;
    }

    // Test max_results parameter
    let search_params = json!({
        "query": "test memory",
        "max_results": 3
    });

    let results = handlers
        .handle_tool_call("search_memory", search_params)
        .await?;
    let results_array = results.as_array().unwrap();
    assert!(results_array.len() <= 3, "Should respect max_results limit");

    // Test similarity_threshold parameter
    let search_params = json!({
        "query": "test memory",
        "similarity_threshold": 0.9
    });

    let results = handlers
        .handle_tool_call("search_memory", search_params)
        .await?;
    assert!(results["search_metadata"]["similarity_threshold"] == 0.9);

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_search_memory_error_handling() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Test missing query parameter
    let params = json!({
        "max_results": 10
    });
    let result = handlers.handle_tool_call("search_memory", params).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("query"));

    // Test invalid similarity threshold
    let params = json!({
        "query": "test",
        "similarity_threshold": 1.5 // Invalid - should be 0.0-1.0
    });
    let result = handlers.handle_tool_call("search_memory", params).await;
    assert!(result.is_err());

    // Test invalid max_results
    let params = json!({
        "query": "test",
        "max_results": -1
    });
    let result = handlers.handle_tool_call("search_memory", params).await;
    assert!(result.is_err());

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_mcp_search_memory_empty_results() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage);

    // Store specific content
    let params = json!({
        "content": "Blockchain technology overview",
        "context": "Crypto context",
        "summary": "Understanding blockchain",
        "tags": ["blockchain", "crypto"]
    });
    handlers.handle_tool_call("store_memory", params).await?;

    // Search for completely unrelated content
    let search_params = json!({
        "query": "cooking recipes pasta italian cuisine",
        "similarity_threshold": 0.8
    });

    let results = handlers
        .handle_tool_call("search_memory", search_params)
        .await?;
    let results_array = results.as_array().unwrap();

    // Should return empty or very few results
    assert!(
        results_array.len() < 2,
        "Should return few results for unrelated search"
    );
    assert_eq!(
        results["search_metadata"]["total_results"],
        results_array.len()
    );

    manager.cleanup().await?;
    Ok(())
}