rust-memex 0.6.4

Operator CLI + MCP server: canonical corpus second: semantic index second to aicx
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
//! In-process helper functions for memory-oriented operations.
//!
//! These helpers are convenient for Rust callers embedding `rust-memex`
//! directly. The authoritative MCP tool contract exposed over stdio and
//! HTTP/SSE comes from `tool_definitions()`, which mirrors the shared runtime
//! surface instead of maintaining a second, drifting schema list here.
//!
//! # Example
//!
//! ```rust,ignore
//! use rust_memex::{MemexEngine, MemexConfig};
//! use rust_memex::tools::{store_document, search_documents, tool_definitions, ToolResult};
//! use serde_json::json;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let engine = MemexEngine::for_app("my-app", "documents").await?;
//!
//!     // Store a document using the local helper API
//!     let result = store_document(
//!         &engine,
//!         "doc-1".to_string(),
//!         "Important patient notes about feline diabetes".to_string(),
//!         json!({"patient_id": "P-123", "doc_type": "notes"}),
//!     ).await?;
//!     assert!(result.success);
//!
//!     // Search for documents
//!     let results = search_documents(&engine, "diabetes".to_string(), 5, None).await?;
//!     println!("Found {} documents", results.len());
//!
//!     // Get the canonical MCP tool definitions exposed by rust-memex
//!     let tools = tool_definitions();
//!     println!("Available tools: {:?}", tools.iter().map(|t| &t.name).collect::<Vec<_>>());
//!
//!     Ok(())
//! }
//! ```

use crate::engine::{BatchResult, MemexEngine, MetaFilter, StoreItem};
use crate::rag::SearchResult;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

// =============================================================================
// TOOL RESULT
// =============================================================================

/// Result type for tool operations.
///
/// Provides a consistent response format for all tool operations,
/// suitable for MCP tool call responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// Whether the operation succeeded
    pub success: bool,
    /// Human-readable message describing the result
    pub message: String,
    /// Optional data payload (operation-specific)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

impl ToolResult {
    /// Create a success result with just a message
    pub fn ok(message: impl Into<String>) -> Self {
        Self {
            success: true,
            message: message.into(),
            data: None,
        }
    }

    /// Create a success result with data
    pub fn ok_with_data(message: impl Into<String>, data: Value) -> Self {
        Self {
            success: true,
            message: message.into(),
            data: Some(data),
        }
    }

    /// Create an error result
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            success: false,
            message: message.into(),
            data: None,
        }
    }
}

// =============================================================================
// TOOL FUNCTIONS
// =============================================================================

/// Store text in memory with automatic embedding generation.
///
/// # Arguments
/// * `engine` - The MemexEngine instance
/// * `id` - Unique document identifier
/// * `text` - Text content to embed and store
/// * `metadata` - Additional metadata (JSON object)
///
/// # Returns
/// `ToolResult` indicating success or failure
///
/// # Example
///
/// ```rust,ignore
/// let result = store_document(
///     &engine,
///     "visit-123".to_string(),
///     "Patient presented with lethargy...".to_string(),
///     json!({"patient_id": "P-456", "visit_type": "checkup"}),
/// ).await?;
/// ```
pub async fn store_document(
    engine: &MemexEngine,
    id: String,
    text: String,
    metadata: Value,
) -> Result<ToolResult> {
    match engine.store(&id, &text, metadata).await {
        Ok(()) => Ok(ToolResult::ok(format!(
            "Document '{}' stored successfully",
            id
        ))),
        Err(e) => Ok(ToolResult::error(format!(
            "Failed to store document '{}': {}",
            id, e
        ))),
    }
}

/// Search memory semantically using vector similarity.
///
/// # Arguments
/// * `engine` - The MemexEngine instance
/// * `query` - Search query text
/// * `limit` - Maximum number of results to return
/// * `filter` - Optional metadata filter for narrowing results
///
/// # Returns
/// Vector of `SearchResult` ordered by relevance (highest score first)
///
/// # Example
///
/// ```rust,ignore
/// // Simple search
/// let results = search_documents(&engine, "diabetes symptoms".to_string(), 10, None).await?;
///
/// // Filtered search
/// let filter = MetaFilter::for_patient("P-456");
/// let results = search_documents(&engine, "diabetes".to_string(), 10, Some(filter)).await?;
/// ```
pub async fn search_documents(
    engine: &MemexEngine,
    query: String,
    limit: usize,
    filter: Option<MetaFilter>,
) -> Result<Vec<SearchResult>> {
    match filter {
        Some(f) => engine.search_filtered(&query, f, limit).await,
        None => engine.search(&query, limit).await,
    }
}

/// Get a document by ID.
///
/// # Arguments
/// * `engine` - The MemexEngine instance
/// * `id` - Document identifier to retrieve
///
/// # Returns
/// `Option<SearchResult>` - The document if found, None otherwise
///
/// # Example
///
/// ```rust,ignore
/// if let Some(doc) = get_document(&engine, "visit-123".to_string()).await? {
///     println!("Found: {}", doc.text);
/// }
/// ```
pub async fn get_document(engine: &MemexEngine, id: String) -> Result<Option<SearchResult>> {
    engine.get(&id).await
}

/// Delete a document by ID.
///
/// # Arguments
/// * `engine` - The MemexEngine instance
/// * `id` - Document identifier to delete
///
/// # Returns
/// `ToolResult` indicating success or failure, with deletion status
///
/// # Example
///
/// ```rust,ignore
/// let result = delete_document(&engine, "visit-123".to_string()).await?;
/// if result.success {
///     println!("Document deleted");
/// }
/// ```
pub async fn delete_document(engine: &MemexEngine, id: String) -> Result<ToolResult> {
    match engine.delete(&id).await {
        Ok(true) => Ok(ToolResult::ok(format!(
            "Document '{}' deleted successfully",
            id
        ))),
        Ok(false) => Ok(ToolResult::ok_with_data(
            format!("Document '{}' not found", id),
            json!({"deleted": false}),
        )),
        Err(e) => Ok(ToolResult::error(format!(
            "Failed to delete document '{}': {}",
            id, e
        ))),
    }
}

/// Batch store multiple documents efficiently.
///
/// More efficient than calling `store_document()` multiple times as embeddings
/// are generated in batches.
///
/// # Arguments
/// * `engine` - The MemexEngine instance
/// * `items` - Vector of items to store
///
/// # Returns
/// `BatchResult` with success/failure counts
///
/// # Example
///
/// ```rust,ignore
/// let items = vec![
///     StoreItem::new("doc-1", "First document").with_metadata(json!({"type": "note"})),
///     StoreItem::new("doc-2", "Second document").with_metadata(json!({"type": "note"})),
/// ];
/// let result = store_documents_batch(&engine, items).await?;
/// println!("Stored {} documents", result.success_count);
/// ```
pub async fn store_documents_batch(
    engine: &MemexEngine,
    items: Vec<StoreItem>,
) -> Result<BatchResult> {
    engine.store_batch(items).await
}

/// Delete all documents matching a metadata filter.
///
/// This is the primary method for GDPR-compliant data deletion.
///
/// # Arguments
/// * `engine` - The MemexEngine instance
/// * `filter` - Metadata filter specifying which documents to delete
///
/// # Returns
/// `ToolResult` with count of deleted documents
///
/// # Example
///
/// ```rust,ignore
/// // GDPR request - delete all patient data
/// let filter = MetaFilter::for_patient("P-456");
/// let result = delete_documents_by_filter(&engine, filter).await?;
/// if let Some(data) = result.data {
///     println!("Deleted {} documents", data["deleted_count"]);
/// }
/// ```
pub async fn delete_documents_by_filter(
    engine: &MemexEngine,
    filter: MetaFilter,
) -> Result<ToolResult> {
    match engine.delete_by_filter(filter.clone()).await {
        Ok(count) => Ok(ToolResult::ok_with_data(
            format!("Deleted {} documents matching filter", count),
            json!({
                "deleted_count": count,
                "filter": filter,
            }),
        )),
        Err(e) => Ok(ToolResult::error(format!(
            "Failed to delete by filter: {}",
            e
        ))),
    }
}

// =============================================================================
// TOOL DEFINITIONS FOR MCP
// =============================================================================

/// MCP tool definition schema.
///
/// This structure mirrors the canonical MCP tool metadata emitted by the shared
/// rust-memex transport layer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// Tool name (used for invocation)
    pub name: String,
    /// Human-readable description of what the tool does
    pub description: String,
    /// JSON Schema for the tool's input parameters
    #[serde(rename = "inputSchema", alias = "input_schema")]
    pub input_schema: Value,
}

impl ToolDefinition {
    /// Create a new tool definition
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        input_schema: Value,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            input_schema,
        }
    }
}

/// Get the canonical MCP tool definitions exposed by rust-memex transports.
///
/// This is derived from the shared transport contract so stdio, HTTP/SSE, and
/// library consumers all see the same tool metadata.
///
/// # Example
///
/// ```rust,ignore
/// let tools = tool_definitions();
/// for tool in &tools {
///     println!("Tool: {} - {}", tool.name, tool.description);
/// }
/// ```
pub fn tool_definitions() -> Vec<ToolDefinition> {
    crate::mcp_protocol::shared_tools_list_result()["tools"]
        .as_array()
        .expect("shared_tools_list_result().tools must be an array")
        .iter()
        .map(|tool| {
            ToolDefinition::new(
                tool["name"]
                    .as_str()
                    .expect("shared MCP tool definition missing name"),
                tool["description"]
                    .as_str()
                    .expect("shared MCP tool definition missing description"),
                tool.get("inputSchema")
                    .cloned()
                    .expect("shared MCP tool definition missing inputSchema"),
            )
        })
        .collect()
}

// =============================================================================
// TESTS
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tool_result_ok() {
        let result = ToolResult::ok("Success");
        assert!(result.success);
        assert_eq!(result.message, "Success");
        assert!(result.data.is_none());
    }

    #[test]
    fn test_tool_result_ok_with_data() {
        let result = ToolResult::ok_with_data("Success", json!({"count": 42}));
        assert!(result.success);
        assert_eq!(result.message, "Success");
        assert_eq!(result.data.unwrap()["count"], 42);
    }

    #[test]
    fn test_tool_result_error() {
        let result = ToolResult::error("Something went wrong");
        assert!(!result.success);
        assert_eq!(result.message, "Something went wrong");
        assert!(result.data.is_none());
    }

    #[test]
    fn test_tool_definitions_count() {
        let tools = tool_definitions();
        assert_eq!(tools.len(), 12);
    }

    #[test]
    fn test_tool_definitions_names() {
        let tools = tool_definitions();
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();

        assert!(names.contains(&"health"));
        assert!(names.contains(&"rag_index"));
        assert!(names.contains(&"memory_upsert"));
        assert!(names.contains(&"memory_search"));
        assert!(names.contains(&"memory_get"));
        assert!(names.contains(&"memory_delete"));
        assert!(names.contains(&"memory_purge_namespace"));
        assert!(names.contains(&"namespace_create_token"));
        assert!(names.contains(&"namespace_revoke_token"));
        assert!(names.contains(&"namespace_list_protected"));
        assert!(names.contains(&"namespace_security_status"));
        assert!(names.contains(&"dive"));
    }

    #[test]
    fn test_tool_definitions_have_required_fields() {
        let tools = tool_definitions();

        for tool in tools {
            assert!(!tool.name.is_empty(), "Tool name should not be empty");
            assert!(
                !tool.description.is_empty(),
                "Tool description should not be empty"
            );
            assert!(
                tool.input_schema.is_object(),
                "Input schema should be an object"
            );
            assert!(
                tool.input_schema.get("type").is_some(),
                "Input schema should have a type field"
            );
            assert!(
                tool.input_schema.get("properties").is_some(),
                "Input schema should have properties"
            );
        }
    }

    #[test]
    fn test_tool_definitions_match_shared_mcp_contract() {
        let serialized = serde_json::to_value(tool_definitions()).unwrap();
        assert_eq!(
            serialized,
            crate::mcp_protocol::shared_tools_list_result()["tools"]
        );
    }

    #[test]
    fn test_tool_result_serialization() {
        let result = ToolResult::ok_with_data("Success", json!({"id": "doc-1"}));
        let json_str = serde_json::to_string(&result).unwrap();

        assert!(json_str.contains("\"success\":true"));
        assert!(json_str.contains("\"message\":\"Success\""));
        assert!(json_str.contains("\"data\""));
    }

    #[test]
    fn test_tool_definition_creation() {
        let tool = ToolDefinition::new(
            "test_tool",
            "A test tool",
            json!({
                "type": "object",
                "properties": {
                    "input": { "type": "string" }
                }
            }),
        );

        assert_eq!(tool.name, "test_tool");
        assert_eq!(tool.description, "A test tool");
        assert!(tool.input_schema["properties"]["input"].is_object());
    }

    #[test]
    fn test_tool_definition_serializes_with_mcp_field_name() {
        let tool = ToolDefinition::new(
            "test_tool",
            "A test tool",
            json!({
                "type": "object",
                "properties": {}
            }),
        );

        let value = serde_json::to_value(tool).unwrap();
        assert!(value.get("inputSchema").is_some());
        assert!(value.get("input_schema").is_none());
    }
}