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
use crate::common::TestDatabaseManager;
use anyhow::Result;
use codex_memory::{mcp_server::MCPHandlers, Storage};
use serde_json::{json, Value};
use std::sync::Arc;

/// Test MCP server failure scenarios and edge cases
#[tokio::test]
async fn test_malformed_json_requests() -> 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 with malformed JSON values
    let malformed_cases = vec![
        json!({"content": null}),                        // null content
        json!({"content": 123}),                         // numeric content
        json!({"content": true}),                        // boolean content
        json!({"content": []}),                          // array content
        json!({"content": {}}),                          // object content
        json!({"context": 123, "content": "test"}),      // numeric context
        json!({"summary": [], "content": "test"}),       // array summary
        json!({"tags": "not_array", "content": "test"}), // string tags
        json!({"tags": [123, 456], "content": "test"}),  // numeric tags
        json!({"tags": true, "content": "test"}),        // boolean tags
    ];

    for (i, params) in malformed_cases.iter().enumerate() {
        println!("Testing malformed case #{}: {}", i, params);

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

        // Most should fail due to type mismatches
        match result {
            Ok(_) => {
                println!("  Case #{} unexpectedly succeeded", i);
                // Some cases might succeed if we handle type coercion
            }
            Err(e) => {
                println!("  Case #{} failed as expected: {}", i, e);
                // Verify error messages are informative
                let error_msg = e.to_string().to_lowercase();
                assert!(
                    error_msg.contains("missing")
                        || error_msg.contains("invalid")
                        || error_msg.contains("type")
                        || error_msg.contains("parameter"),
                    "Error should be descriptive: {}",
                    e
                );
            }
        }
    }

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

#[tokio::test]
async fn test_oversized_mcp_payload() -> 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);

    // Create extremely large content for MCP
    let large_content = "Large content ".repeat(100000); // ~1.4MB
    let large_context = "Large context ".repeat(50000); // ~700KB
    let large_summary = "Large summary ".repeat(10000); // ~140KB

    // Create massive tag array
    let large_tags: Vec<Value> = (0..10000)
        .map(|i| json!(format!("very_long_tag_name_that_takes_up_space_{:06}", i)))
        .collect();

    let oversized_payload = json!({
        "content": large_content,
        "context": large_context,
        "summary": large_summary,
        "tags": large_tags
    });

    println!("Testing oversized payload (~2.5MB)");

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

    match result {
        Ok(response) => {
            println!("Oversized payload succeeded: {}", response);
            // If it succeeds, verify we can retrieve it
            if let Some(id) = response["id"].as_str() {
                let get_params = json!({"id": id});
                let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

                // Verify large content was stored correctly
                let retrieved_content = retrieved["content"].as_str().unwrap();
                assert_eq!(retrieved_content.len(), large_content.len());
            }
        }
        Err(e) => {
            println!("Oversized payload failed (may be expected): {}", e);
            // This might fail due to:
            // - Network payload limits
            // - Database field limits
            // - Memory constraints
            // - Timeout limits
        }
    }

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

#[tokio::test]
async fn test_invalid_tier_values() -> 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);

    let invalid_tiers = vec![
        "invalid_tier",
        "hot",        // Not in enum
        "archive",    // Not in enum
        "WORKING",    // Wrong case
        "Cold",       // Wrong case
        "",           // Empty string
        "working123", // With numbers
        "work-ing",   // With dashes
    ];

    for tier in invalid_tiers {
        println!("Testing invalid tier: '{}'", tier);

        let params = json!({
            "content": format!("Content with invalid tier: {}", tier),
            "context": format!("Context for invalid tier test: {}", tier),
            "summary": format!("Summary for invalid tier test: {}", tier),
            "tags": []
        });

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

        // Since tier is no longer a parameter, these should all succeed
        match result {
            Ok(_) => {
                println!(
                    "  Content with tier reference '{}' stored successfully",
                    tier
                );
            }
            Err(e) => {
                // Should not fail since tier is no longer validated
                panic!("Unexpected failure for tier reference '{}': {}", tier, e);
            }
        }
    }

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

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

    // Launch many concurrent MCP requests
    let mut handles = vec![];

    for i in 0..50 {
        let handlers_clone = handlers.clone();
        let handle = tokio::spawn(async move {
            let params = json!({
                "content": format!("Concurrent MCP request #{}", i),
                "context": format!("Context for request #{}", i),
                "summary": format!("Summary for request #{}", i),
                "tags": [format!("concurrent-{}", i), "stress-test"]
            });

            handlers_clone
                .handle_tool_call("store_memory", params)
                .await
        });
        handles.push(handle);
    }

    // Wait for all requests
    let mut successes = 0;
    let mut failures = 0;

    for handle in handles {
        match handle.await {
            Ok(Ok(_)) => successes += 1,
            Ok(Err(e)) => {
                println!("MCP request failed: {}", e);
                failures += 1;
            }
            Err(e) => {
                println!("Task failed: {}", e);
                failures += 1;
            }
        }
    }

    println!(
        "Concurrent MCP requests: {} succeeded, {} failed",
        successes, failures
    );

    // Most requests should succeed
    assert!(
        successes > 40,
        "Most concurrent MCP requests should succeed"
    );

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

#[tokio::test]
async fn test_missing_required_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);

    // Test store_memory with missing content
    let result = handlers.handle_tool_call("store_memory", json!({})).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Missing content"));

    // Test store_memory with only optional fields
    let result = handlers
        .handle_tool_call(
            "store_memory",
            json!({
                "context": "Context without content",
                "summary": "Summary without content",
                "tags": ["tag1", "tag2"]
            }),
        )
        .await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Missing content"));

    // Test get_memory with missing ID
    let result = handlers.handle_tool_call("get_memory", json!({})).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Missing id"));

    // Test delete_memory with missing ID
    let result = handlers.handle_tool_call("delete_memory", json!({})).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Missing id"));

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

#[tokio::test]
async fn test_invalid_uuid_formats() -> 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);

    let invalid_uuids = vec![
        "not-a-uuid",
        "12345678-1234-1234-1234",                // Too short
        "12345678-1234-1234-1234-12345678901234", // Too long
        "gggggggg-1234-1234-1234-123456789012",   // Invalid hex
        "12345678_1234_1234_1234_123456789012",   // Wrong separator
        "",                                       // Empty
        "null",
        "undefined",
        "00000000-0000-0000-0000-000000000000", // Valid but non-existent
        "123e4567-e89b-12d3-a456-426614174000", // Valid format but non-existent
    ];

    for uuid in invalid_uuids {
        println!("Testing invalid UUID: '{}'", uuid);

        // Test get_memory
        let params = json!({"id": uuid});
        let result = handlers
            .handle_tool_call("get_memory", params.clone())
            .await;

        match result {
            Ok(_) => {
                // Valid UUIDs that don't exist should return "not found"
                println!("  UUID '{}' was accepted but should return not found", uuid);
            }
            Err(e) => {
                let error_msg = e.to_string().to_lowercase();
                if error_msg.contains("invalid uuid") {
                    println!("  Invalid UUID '{}' rejected correctly", uuid);
                } else if error_msg.contains("not found") {
                    println!("  Valid UUID '{}' not found (expected)", uuid);
                } else {
                    println!("  UUID '{}' failed: {}", uuid, e);
                }
            }
        }

        // Test delete_memory
        let result = handlers.handle_tool_call("delete_memory", params).await;
        match result {
            Ok(response) => {
                // Valid UUIDs should succeed but show deleted=false for non-existent items
                let deleted = response["deleted"].as_bool().unwrap_or(false);
                if uuid == "00000000-0000-0000-0000-000000000000"
                    || uuid == "123e4567-e89b-12d3-a456-426614174000"
                {
                    assert!(
                        !deleted,
                        "Delete of non-existent memory should show deleted=false"
                    );
                    println!(
                        "  Valid UUID '{}' delete returned success with deleted=false (expected)",
                        uuid
                    );
                } else {
                    panic!("Delete with invalid UUID '{}' should fail", uuid);
                }
            }
            Err(e) => {
                let error_msg = e.to_string().to_lowercase();
                assert!(
                    error_msg.contains("invalid uuid"),
                    "Delete with invalid UUID '{}' failed for wrong reason: {}",
                    uuid,
                    e
                );
                println!("  Invalid UUID '{}' delete rejected correctly", uuid);
            }
        }
    }

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

#[tokio::test]
async fn test_extremely_nested_json() -> 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);

    // Create deeply nested JSON structure
    let mut nested_json = json!("deep");
    for _ in 0..100 {
        nested_json = json!({"level": nested_json});
    }

    let params = json!({
        "content": "Content with deeply nested context",
        "context": nested_json.to_string(), // Convert to string
        "summary": "Summary for deeply nested context test",
        "tags": ["nested", "json", "stress"]
    });

    println!("Testing deeply nested JSON context");

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

    match result {
        Ok(response) => {
            println!("Nested JSON succeeded");

            // Verify we can retrieve it
            if let Some(id) = response["id"].as_str() {
                let get_params = json!({"id": id});
                let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

                // Verify the nested JSON was preserved
                let retrieved_context = retrieved["context"].as_str().unwrap();
                assert!(
                    retrieved_context.contains("level"),
                    "Nested JSON should be preserved"
                );
            }
        }
        Err(e) => {
            println!("Nested JSON failed: {}", e);
            // This might fail due to parsing or size limits
        }
    }

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

#[tokio::test]
async fn test_tool_call_with_extra_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);

    // Test with extra parameters that aren't in the schema
    let params_with_extra = json!({
        "content": "Test content with extra params",
        "context": "Test context",
        "summary": "Test summary",
        "tags": ["test"],
        "extra_param": "should be ignored",
        "another_extra": 123,
        "nested_extra": {"key": "value"},
        "unknown_tier": "super_hot",
        "random_field": [1, 2, 3]
    });

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

    match result {
        Ok(response) => {
            println!("Extra parameters were ignored successfully");

            // Verify content was stored correctly
            if let Some(id) = response["id"].as_str() {
                let get_params = json!({"id": id});
                let retrieved = handlers.handle_tool_call("get_memory", get_params).await?;

                assert_eq!(retrieved["content"], "Test content with extra params");
                assert_eq!(retrieved["context"], "Test context");
                assert_eq!(retrieved["summary"], "Test summary");
            }
        }
        Err(e) => {
            println!("Extra parameters caused failure: {}", e);
            // This might fail if we have strict parameter validation
        }
    }

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