cortex-mem-rig 1.0.0

Rig framework integration for Rust agent memory system
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
use cortex_mem_config::Config;
use cortex_mem_core::MemoryManager;
use cortex_mem_tools::{MemoryOperations, get_mcp_tool_definitions, map_mcp_arguments_to_payload};
use rig::{completion::ToolDefinition, tool::Tool};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use std::sync::Arc;
use tracing::{error, info};

// Re-export the error type from cortex-mem-tools for backward compatibility
pub use cortex_mem_tools::MemoryToolsError as MemoryToolError;

/// Memory tool configuration
pub struct MemoryToolConfig {
    pub default_user_id: Option<String>,
    pub default_agent_id: Option<String>,
    pub max_search_results: Option<usize>,
    pub auto_enhance: Option<bool>,
    pub search_similarity_threshold: Option<f32>,
}

/// Store Memory tool arguments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoreMemoryArgs {
    pub content: String,
    pub user_id: Option<String>,
    pub agent_id: Option<String>,
    pub memory_type: Option<String>,
    pub topics: Option<Vec<String>>,
}

/// Query Memory tool arguments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryMemoryArgs {
    pub query: String,
    pub k: Option<usize>,
    pub memory_type: Option<String>,
    pub min_salience: Option<f64>,
    pub topics: Option<Vec<String>>,
    pub user_id: Option<String>,
    pub agent_id: Option<String>,
}

/// List Memories tool arguments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListMemoriesArgs {
    pub limit: Option<usize>,
    pub memory_type: Option<String>,
    pub user_id: Option<String>,
    pub agent_id: Option<String>,
}

/// Get Memory tool arguments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetMemoryArgs {
    pub memory_id: String,
}

/// Common tool output
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryToolOutput {
    pub success: bool,
    pub message: String,
    pub data: Option<Value>,
}

/// Base struct for memory tools that shares common functionality
pub struct MemoryToolsBase {
    operations: MemoryOperations,
    config: MemoryToolConfig,
}

impl MemoryToolsBase {
    /// Create a new memory tools base with the provided memory manager and configuration
    pub fn new(
        memory_manager: Arc<MemoryManager>,
        global_config: &Config,
        custom_config: Option<MemoryToolConfig>,
    ) -> Self {
        let mut config = MemoryToolConfig::default();

        // Apply custom config overrides if provided
        if let Some(custom) = custom_config {
            config.default_user_id = custom.default_user_id.or(config.default_user_id);
            config.default_agent_id = custom.default_agent_id.or(config.default_agent_id);
            config.max_search_results = custom.max_search_results.or(config.max_search_results);
            config.auto_enhance = custom.auto_enhance.or(config.auto_enhance);
            config.search_similarity_threshold = custom
                .search_similarity_threshold
                .or(config.search_similarity_threshold);
        }

        // Fallback to values from global config if not set in custom
        if config.max_search_results.is_none() {
            config.max_search_results = Some(global_config.memory.max_search_results);
        }
        if config.auto_enhance.is_none() {
            config.auto_enhance = Some(global_config.memory.auto_enhance);
        }
        if config.search_similarity_threshold.is_none() {
            config.search_similarity_threshold = global_config.memory.search_similarity_threshold;
        }

        // Create operations handler
        let operations = MemoryOperations::new(
            memory_manager.clone(),
            config.default_user_id.clone(),
            config.default_agent_id.clone(),
            config.max_search_results.unwrap_or(10),
        );

        Self { operations, config }
    }

    /// Convert JSON values to a Map for the map_mcp_arguments_to_payload function
    fn args_to_map(&self, args: &serde_json::Value) -> Map<String, Value> {
        if let Value::Object(map) = args {
            map.clone()
        } else {
            Map::new()
        }
    }
}

/// Store Memory Tool
pub struct StoreMemoryTool {
    base: Arc<MemoryToolsBase>,
}

impl StoreMemoryTool {
    pub fn new(base: Arc<MemoryToolsBase>) -> Self {
        Self { base }
    }
}

impl Tool for StoreMemoryTool {
    const NAME: &'static str = "store_memory";

    type Error = MemoryToolError;
    type Args = StoreMemoryArgs;
    type Output = MemoryToolOutput;

    fn definition(
        &self,
        _prompt: String,
    ) -> impl std::future::Future<Output = ToolDefinition> + Send + Sync {
        async move {
            // Get tool definition from MCP definitions
            let tool_definitions = get_mcp_tool_definitions();
            let def = tool_definitions
                .iter()
                .find(|d| d.name == "store_memory")
                .expect(" store_memory tool definition should exist");

            ToolDefinition {
                name: Self::NAME.to_string(),
                description: def.description.clone().unwrap_or_default(),
                parameters: def.input_schema.clone(),
            }
        }
    }

    fn call(
        &self,
        args: Self::Args,
    ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send {
        async move {
            // Convert args to JSON Value
            let args_json = json!(args);
            let arguments = self.base.args_to_map(&args_json);

            // Map to payload using shared function
            let payload =
                map_mcp_arguments_to_payload(&arguments, &self.base.config.default_agent_id);

            match self.base.operations.store_memory(payload).await {
                Ok(response) => {
                    info!("Memory stored via rig tool");
                    Ok(MemoryToolOutput {
                        success: response.success,
                        message: response.message,
                        data: response.data,
                    })
                }
                Err(e) => {
                    error!("Failed to store memory via rig tool: {}", e);
                    Err(e)
                }
            }
        }
    }
}

/// Query Memory Tool
pub struct QueryMemoryTool {
    base: Arc<MemoryToolsBase>,
}

impl QueryMemoryTool {
    pub fn new(base: Arc<MemoryToolsBase>) -> Self {
        Self { base }
    }
}

impl Tool for QueryMemoryTool {
    const NAME: &'static str = "query_memory";

    type Error = MemoryToolError;
    type Args = QueryMemoryArgs;
    type Output = MemoryToolOutput;

    fn definition(
        &self,
        _prompt: String,
    ) -> impl std::future::Future<Output = ToolDefinition> + Send + Sync {
        async move {
            // Get tool definition from MCP definitions
            let tool_definitions = get_mcp_tool_definitions();
            let def = tool_definitions
                .iter()
                .find(|d| d.name == "query_memory")
                .expect("query_memory tool definition should exist");

            ToolDefinition {
                name: Self::NAME.to_string(),
                description: def.description.clone().unwrap_or_default(),
                parameters: def.input_schema.clone(),
            }
        }
    }

    fn call(
        &self,
        args: Self::Args,
    ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send {
        async move {
            // Convert args to JSON Value
            let args_json = json!(args);
            let arguments = self.base.args_to_map(&args_json);

            // Map to payload using shared function
            let payload =
                map_mcp_arguments_to_payload(&arguments, &self.base.config.default_agent_id);

            match self.base.operations.query_memory(payload).await {
                Ok(response) => Ok(MemoryToolOutput {
                    success: response.success,
                    message: response.message,
                    data: response.data,
                }),
                Err(e) => {
                    error!("Failed to query memories via rig tool: {}", e);
                    Err(e)
                }
            }
        }
    }
}

/// List Memories Tool
pub struct ListMemoriesTool {
    base: Arc<MemoryToolsBase>,
}

impl ListMemoriesTool {
    pub fn new(base: Arc<MemoryToolsBase>) -> Self {
        Self { base }
    }
}

impl Tool for ListMemoriesTool {
    const NAME: &'static str = "list_memories";

    type Error = MemoryToolError;
    type Args = ListMemoriesArgs;
    type Output = MemoryToolOutput;

    fn definition(
        &self,
        _prompt: String,
    ) -> impl std::future::Future<Output = ToolDefinition> + Send + Sync {
        async move {
            // Get tool definition from MCP definitions
            let tool_definitions = get_mcp_tool_definitions();
            let def = tool_definitions
                .iter()
                .find(|d| d.name == "list_memories")
                .expect("list_memories tool definition should exist");

            ToolDefinition {
                name: Self::NAME.to_string(),
                description: def.description.clone().unwrap_or_default(),
                parameters: def.input_schema.clone(),
            }
        }
    }

    fn call(
        &self,
        args: Self::Args,
    ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send {
        async move {
            // Convert args to JSON Value
            let args_json = json!(args);
            let arguments = self.base.args_to_map(&args_json);

            // Map to payload using shared function
            let payload =
                map_mcp_arguments_to_payload(&arguments, &self.base.config.default_agent_id);

            match self.base.operations.list_memories(payload).await {
                Ok(response) => Ok(MemoryToolOutput {
                    success: response.success,
                    message: response.message,
                    data: response.data,
                }),
                Err(e) => {
                    error!("Failed to list memories via rig tool: {}", e);
                    Err(e)
                }
            }
        }
    }
}

/// Get Memory Tool
pub struct GetMemoryTool {
    base: Arc<MemoryToolsBase>,
}

impl GetMemoryTool {
    pub fn new(base: Arc<MemoryToolsBase>) -> Self {
        Self { base }
    }
}

impl Tool for GetMemoryTool {
    const NAME: &'static str = "get_memory";

    type Error = MemoryToolError;
    type Args = GetMemoryArgs;
    type Output = MemoryToolOutput;

    fn definition(
        &self,
        _prompt: String,
    ) -> impl std::future::Future<Output = ToolDefinition> + Send + Sync {
        async move {
            // Get tool definition from MCP definitions
            let tool_definitions = get_mcp_tool_definitions();
            let def = tool_definitions
                .iter()
                .find(|d| d.name == "get_memory")
                .expect("get_memory tool definition should exist");

            ToolDefinition {
                name: Self::NAME.to_string(),
                description: def.description.clone().unwrap_or_default(),
                parameters: def.input_schema.clone(),
            }
        }
    }

    fn call(
        &self,
        args: Self::Args,
    ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send {
        async move {
            // Convert args to JSON Value
            let args_json = json!(args);
            let arguments = self.base.args_to_map(&args_json);

            // Map to payload using shared function
            let payload =
                map_mcp_arguments_to_payload(&arguments, &self.base.config.default_agent_id);

            match self.base.operations.get_memory(payload).await {
                Ok(response) => Ok(MemoryToolOutput {
                    success: response.success,
                    message: response.message,
                    data: response.data,
                }),
                Err(e) => {
                    error!("Failed to get memory via rig tool: {}", e);
                    Err(e)
                }
            }
        }
    }
}

/// MemoryTools struct that provides all memory tools
pub struct MemoryTools {
    base: Arc<MemoryToolsBase>,
}

impl MemoryTools {
    /// Create new memory tools with the provided memory manager and configuration
    pub fn new(
        memory_manager: Arc<MemoryManager>,
        global_config: &Config,
        custom_config: Option<MemoryToolConfig>,
    ) -> Self {
        let base = Arc::new(MemoryToolsBase::new(
            memory_manager,
            global_config,
            custom_config,
        ));
        Self { base }
    }

    /// Get the store memory tool
    pub fn store_memory(&self) -> StoreMemoryTool {
        StoreMemoryTool::new(self.base.clone())
    }

    /// Get the query memory tool
    pub fn query_memory(&self) -> QueryMemoryTool {
        QueryMemoryTool::new(self.base.clone())
    }

    /// Get the list memories tool
    pub fn list_memories(&self) -> ListMemoriesTool {
        ListMemoriesTool::new(self.base.clone())
    }

    /// Get the get memory tool
    pub fn get_memory(&self) -> GetMemoryTool {
        GetMemoryTool::new(self.base.clone())
    }
}

impl Default for MemoryToolConfig {
    fn default() -> Self {
        Self {
            default_user_id: None,
            default_agent_id: None,
            max_search_results: None, // Will be taken from global config
            auto_enhance: None,       // Will be taken from global config
            search_similarity_threshold: None, // Will be taken from global config
        }
    }
}

/// Create memory tools with default configuration
pub fn create_memory_tools(
    memory_manager: Arc<MemoryManager>,
    global_config: &Config,
    custom_config: Option<MemoryToolConfig>,
) -> MemoryTools {
    MemoryTools::new(memory_manager, global_config, custom_config)
}