inventory.rs 19 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
// MCP Tool Inventory with TTL-based Caching
//
// This module provides TTL-based caching for MCP tools, prompts, and resources.
// Tools are cached with timestamps and automatically expire after the configured TTL.
// Background refresh tasks can proactively update the inventory.

use std::time::{Duration, Instant};

use dashmap::DashMap;

11
use crate::mcp::config::{Prompt, RawResource, Tool};
12
13
14
15
16

/// Cached tool with metadata
#[derive(Clone)]
pub struct CachedTool {
    pub server_name: String,
17
    pub tool: Tool,
18
19
20
21
22
23
24
    pub cached_at: Instant,
}

/// Cached prompt with metadata
#[derive(Clone)]
pub struct CachedPrompt {
    pub server_name: String,
25
    pub prompt: Prompt,
26
27
28
29
30
31
32
    pub cached_at: Instant,
}

/// Cached resource with metadata
#[derive(Clone)]
pub struct CachedResource {
    pub server_name: String,
33
    pub resource: RawResource,
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
    pub cached_at: Instant,
}

/// Tool inventory with TTL-based caching
///
/// Provides thread-safe caching of MCP tools, prompts, and resources with automatic expiration.
/// Entries are timestamped and can be queried with TTL validation.
pub struct ToolInventory {
    /// Map of tool_name -> cached tool
    tools: DashMap<String, CachedTool>,

    /// Map of prompt_name -> cached prompt
    prompts: DashMap<String, CachedPrompt>,

    /// Map of resource_uri -> cached resource
    resources: DashMap<String, CachedResource>,

    /// Tool cache TTL
    tool_ttl: Duration,

    /// Last refresh time per server
    server_refresh_times: DashMap<String, Instant>,
}

impl ToolInventory {
    /// Create a new tool inventory with the specified TTL
    pub fn new(tool_ttl: Duration) -> Self {
        Self {
            tools: DashMap::new(),
            prompts: DashMap::new(),
            resources: DashMap::new(),
            tool_ttl,
            server_refresh_times: DashMap::new(),
        }
    }

    // ============================================================================
    // Tool Methods
    // ============================================================================

    /// Get a tool if it exists and is fresh (within TTL)
    ///
    /// Returns None if the tool doesn't exist or has expired.
77
    pub fn get_tool(&self, tool_name: &str) -> Option<(String, Tool)> {
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        self.tools.get(tool_name).and_then(|entry| {
            let cached = entry.value();

            // Check if still fresh
            if cached.cached_at.elapsed() < self.tool_ttl {
                Some((cached.server_name.clone(), cached.tool.clone()))
            } else {
                // Expired - will be removed by cleanup
                None
            }
        })
    }

    /// Check if tool exists (regardless of TTL)
    pub fn has_tool(&self, tool_name: &str) -> bool {
        self.tools.contains_key(tool_name)
    }

    /// Insert or update a tool
97
    pub fn insert_tool(&self, tool_name: String, server_name: String, tool: Tool) {
98
99
100
101
102
103
104
105
106
107
108
        self.tools.insert(
            tool_name,
            CachedTool {
                server_name,
                tool,
                cached_at: Instant::now(),
            },
        );
    }

    /// Get all tools (fresh only)
109
    pub fn list_tools(&self) -> Vec<(String, String, Tool)> {
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        let now = Instant::now();
        self.tools
            .iter()
            .filter_map(|entry| {
                let (name, cached) = entry.pair();
                if now.duration_since(cached.cached_at) < self.tool_ttl {
                    Some((
                        name.clone(),
                        cached.server_name.clone(),
                        cached.tool.clone(),
                    ))
                } else {
                    None
                }
            })
            .collect()
    }

    // ============================================================================
    // Prompt Methods
    // ============================================================================

    /// Get a prompt if it exists and is fresh (within TTL)
133
    pub fn get_prompt(&self, prompt_name: &str) -> Option<(String, Prompt)> {
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        self.prompts.get(prompt_name).and_then(|entry| {
            let cached = entry.value();

            // Check if still fresh
            if cached.cached_at.elapsed() < self.tool_ttl {
                Some((cached.server_name.clone(), cached.prompt.clone()))
            } else {
                None
            }
        })
    }

    /// Check if prompt exists (regardless of TTL)
    pub fn has_prompt(&self, prompt_name: &str) -> bool {
        self.prompts.contains_key(prompt_name)
    }

    /// Insert or update a prompt
152
    pub fn insert_prompt(&self, prompt_name: String, server_name: String, prompt: Prompt) {
153
154
155
156
157
158
159
160
161
162
163
        self.prompts.insert(
            prompt_name,
            CachedPrompt {
                server_name,
                prompt,
                cached_at: Instant::now(),
            },
        );
    }

    /// Get all prompts (fresh only)
164
    pub fn list_prompts(&self) -> Vec<(String, String, Prompt)> {
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        let now = Instant::now();
        self.prompts
            .iter()
            .filter_map(|entry| {
                let (name, cached) = entry.pair();
                if now.duration_since(cached.cached_at) < self.tool_ttl {
                    Some((
                        name.clone(),
                        cached.server_name.clone(),
                        cached.prompt.clone(),
                    ))
                } else {
                    None
                }
            })
            .collect()
    }

    // ============================================================================
    // Resource Methods
    // ============================================================================

    /// Get a resource if it exists and is fresh (within TTL)
188
    pub fn get_resource(&self, resource_uri: &str) -> Option<(String, RawResource)> {
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
        self.resources.get(resource_uri).and_then(|entry| {
            let cached = entry.value();

            // Check if still fresh
            if cached.cached_at.elapsed() < self.tool_ttl {
                Some((cached.server_name.clone(), cached.resource.clone()))
            } else {
                None
            }
        })
    }

    /// Check if resource exists (regardless of TTL)
    pub fn has_resource(&self, resource_uri: &str) -> bool {
        self.resources.contains_key(resource_uri)
    }

    /// Insert or update a resource
    pub fn insert_resource(
        &self,
        resource_uri: String,
        server_name: String,
211
        resource: RawResource,
212
213
214
215
216
217
218
219
220
221
222
223
    ) {
        self.resources.insert(
            resource_uri,
            CachedResource {
                server_name,
                resource,
                cached_at: Instant::now(),
            },
        );
    }

    /// Get all resources (fresh only)
224
    pub fn list_resources(&self) -> Vec<(String, String, RawResource)> {
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
        let now = Instant::now();
        self.resources
            .iter()
            .filter_map(|entry| {
                let (uri, cached) = entry.pair();
                if now.duration_since(cached.cached_at) < self.tool_ttl {
                    Some((
                        uri.clone(),
                        cached.server_name.clone(),
                        cached.resource.clone(),
                    ))
                } else {
                    None
                }
            })
            .collect()
    }

    // ============================================================================
    // Server Management Methods
    // ============================================================================

    /// Clear all cached items for a specific server (before refresh)
    pub fn clear_server_tools(&self, server_name: &str) {
        self.tools
            .retain(|_, cached| cached.server_name != server_name);
        self.prompts
            .retain(|_, cached| cached.server_name != server_name);
        self.resources
            .retain(|_, cached| cached.server_name != server_name);
    }

    /// Mark server as refreshed
    pub fn mark_refreshed(&self, server_name: &str) {
        self.server_refresh_times
            .insert(server_name.to_string(), Instant::now());
    }

    /// Check if server needs refresh based on refresh interval
    pub fn needs_refresh(&self, server_name: &str, refresh_interval: Duration) -> bool {
        self.server_refresh_times
            .get(server_name)
            .map(|t| t.elapsed() > refresh_interval)
            .unwrap_or(true) // Never refreshed = needs refresh
    }

    /// Get last refresh time for a server
    pub fn last_refresh(&self, server_name: &str) -> Option<Instant> {
        self.server_refresh_times
            .get(server_name)
            .map(|t| *t.value())
    }

    // ============================================================================
    // Cleanup Methods
    // ============================================================================

    /// Cleanup expired entries
    ///
    /// Removes all tools, prompts, and resources that have exceeded their TTL.
    /// Should be called periodically by a background task.
    pub fn cleanup_expired(&self) {
        let now = Instant::now();

        // Remove expired tools
        self.tools
            .retain(|_, cached| now.duration_since(cached.cached_at) < self.tool_ttl);

        // Remove expired prompts
        self.prompts
            .retain(|_, cached| now.duration_since(cached.cached_at) < self.tool_ttl);

        // Remove expired resources
        self.resources
            .retain(|_, cached| now.duration_since(cached.cached_at) < self.tool_ttl);
    }

    /// Get count of cached items
    pub fn counts(&self) -> (usize, usize, usize) {
        (self.tools.len(), self.prompts.len(), self.resources.len())
    }

    /// Clear all cached items
    pub fn clear_all(&self) {
        self.tools.clear();
        self.prompts.clear();
        self.resources.clear();
        self.server_refresh_times.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
319
    use crate::mcp::config::{Prompt, RawResource, Tool};
320
321

    // Helper to create a test tool
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    fn create_test_tool(name: &str) -> Tool {
        use std::{borrow::Cow, sync::Arc};

        let schema_obj = serde_json::json!({
            "type": "object",
            "properties": {}
        });

        let schema_map = if let serde_json::Value::Object(m) = schema_obj {
            m
        } else {
            serde_json::Map::new()
        };

        Tool {
            name: Cow::Owned(name.to_string()),
            title: None,
            description: Some(Cow::Owned(format!("Test tool: {}", name))),
            input_schema: Arc::new(schema_map),
            output_schema: None,
            annotations: None,
            icons: None,
344
345
346
347
        }
    }

    // Helper to create a test prompt
348
349
    fn create_test_prompt(name: &str) -> Prompt {
        Prompt {
350
            name: name.to_string(),
351
            title: None,
352
353
            description: Some(format!("Test prompt: {}", name)),
            arguments: None,
354
            icons: None,
355
356
357
358
        }
    }

    // Helper to create a test resource
359
360
    fn create_test_resource(uri: &str) -> RawResource {
        RawResource {
361
362
            uri: uri.to_string(),
            name: uri.to_string(),
363
            title: None,
364
365
            description: Some(format!("Test resource: {}", uri)),
            mime_type: Some("text/plain".to_string()),
366
367
            size: None,
            icons: None,
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
634
635
636
637
        }
    }

    #[test]
    fn test_tool_insert_and_get() {
        let inventory = ToolInventory::new(Duration::from_secs(60));
        let tool = create_test_tool("test_tool");

        inventory.insert_tool("test_tool".to_string(), "server1".to_string(), tool.clone());

        let result = inventory.get_tool("test_tool");
        assert!(result.is_some());

        let (server_name, retrieved_tool) = result.unwrap();
        assert_eq!(server_name, "server1");
        assert_eq!(retrieved_tool.name, "test_tool");
    }

    #[test]
    fn test_tool_expiration() {
        let inventory = ToolInventory::new(Duration::from_millis(100));
        let tool = create_test_tool("expiring_tool");

        inventory.insert_tool(
            "expiring_tool".to_string(),
            "server1".to_string(),
            tool.clone(),
        );

        // Should be available immediately
        assert!(inventory.get_tool("expiring_tool").is_some());

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(150));

        // Should be expired now
        assert!(inventory.get_tool("expiring_tool").is_none());
    }

    #[test]
    fn test_has_tool() {
        let inventory = ToolInventory::new(Duration::from_secs(60));
        let tool = create_test_tool("check_tool");

        assert!(!inventory.has_tool("check_tool"));

        inventory.insert_tool("check_tool".to_string(), "server1".to_string(), tool);

        assert!(inventory.has_tool("check_tool"));
    }

    #[test]
    fn test_list_tools() {
        let inventory = ToolInventory::new(Duration::from_secs(60));

        inventory.insert_tool(
            "tool1".to_string(),
            "server1".to_string(),
            create_test_tool("tool1"),
        );
        inventory.insert_tool(
            "tool2".to_string(),
            "server1".to_string(),
            create_test_tool("tool2"),
        );
        inventory.insert_tool(
            "tool3".to_string(),
            "server2".to_string(),
            create_test_tool("tool3"),
        );

        let tools = inventory.list_tools();
        assert_eq!(tools.len(), 3);
    }

    #[test]
    fn test_list_tools_filters_expired() {
        let inventory = ToolInventory::new(Duration::from_millis(100));

        inventory.insert_tool(
            "tool1".to_string(),
            "server1".to_string(),
            create_test_tool("tool1"),
        );

        // Should have 1 tool
        assert_eq!(inventory.list_tools().len(), 1);

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(150));

        // Should have 0 tools (filtered out)
        assert_eq!(inventory.list_tools().len(), 0);
    }

    #[test]
    fn test_clear_server_tools() {
        let inventory = ToolInventory::new(Duration::from_secs(60));

        inventory.insert_tool(
            "tool1".to_string(),
            "server1".to_string(),
            create_test_tool("tool1"),
        );
        inventory.insert_tool(
            "tool2".to_string(),
            "server2".to_string(),
            create_test_tool("tool2"),
        );

        assert_eq!(inventory.list_tools().len(), 2);

        inventory.clear_server_tools("server1");

        let tools = inventory.list_tools();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].0, "tool2");
    }

    #[test]
    fn test_server_refresh_tracking() {
        let inventory = ToolInventory::new(Duration::from_secs(60));

        // Never refreshed
        assert!(inventory.needs_refresh("server1", Duration::from_secs(10)));

        // Mark as refreshed
        inventory.mark_refreshed("server1");

        // Should not need refresh immediately
        assert!(!inventory.needs_refresh("server1", Duration::from_secs(10)));

        // Wait and check again
        std::thread::sleep(Duration::from_millis(100));
        assert!(inventory.needs_refresh("server1", Duration::from_millis(50)));
    }

    #[test]
    fn test_cleanup_expired() {
        let inventory = ToolInventory::new(Duration::from_millis(100));

        inventory.insert_tool(
            "tool1".to_string(),
            "server1".to_string(),
            create_test_tool("tool1"),
        );
        inventory.insert_tool(
            "tool2".to_string(),
            "server1".to_string(),
            create_test_tool("tool2"),
        );

        let (tools, _, _) = inventory.counts();
        assert_eq!(tools, 2);

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(150));

        // Cleanup expired entries
        inventory.cleanup_expired();

        let (tools, _, _) = inventory.counts();
        assert_eq!(tools, 0);
    }

    #[test]
    fn test_prompt_operations() {
        let inventory = ToolInventory::new(Duration::from_secs(60));
        let prompt = create_test_prompt("test_prompt");

        inventory.insert_prompt(
            "test_prompt".to_string(),
            "server1".to_string(),
            prompt.clone(),
        );

        assert!(inventory.has_prompt("test_prompt"));

        let result = inventory.get_prompt("test_prompt");
        assert!(result.is_some());

        let (server_name, retrieved_prompt) = result.unwrap();
        assert_eq!(server_name, "server1");
        assert_eq!(retrieved_prompt.name, "test_prompt");
    }

    #[test]
    fn test_resource_operations() {
        let inventory = ToolInventory::new(Duration::from_secs(60));
        let resource = create_test_resource("file:///test.txt");

        inventory.insert_resource(
            "file:///test.txt".to_string(),
            "server1".to_string(),
            resource.clone(),
        );

        assert!(inventory.has_resource("file:///test.txt"));

        let result = inventory.get_resource("file:///test.txt");
        assert!(result.is_some());

        let (server_name, retrieved_resource) = result.unwrap();
        assert_eq!(server_name, "server1");
        assert_eq!(retrieved_resource.uri, "file:///test.txt");
    }

    #[tokio::test]
    async fn test_concurrent_access() {
        use std::sync::Arc;

        let inventory = Arc::new(ToolInventory::new(Duration::from_secs(60)));

        // Spawn multiple tasks that insert tools concurrently
        let mut handles = vec![];
        for i in 0..10 {
            let inv = Arc::clone(&inventory);
            let handle = tokio::spawn(async move {
                let tool = create_test_tool(&format!("tool_{}", i));
                inv.insert_tool(format!("tool_{}", i), format!("server_{}", i % 3), tool);
            });
            handles.push(handle);
        }

        // Wait for all tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }

        // Should have 10 tools
        let (tools, _, _) = inventory.counts();
        assert_eq!(tools, 10);
    }

    #[test]
    fn test_clear_all() {
        let inventory = ToolInventory::new(Duration::from_secs(60));

        inventory.insert_tool(
            "tool1".to_string(),
            "server1".to_string(),
            create_test_tool("tool1"),
        );
        inventory.insert_prompt(
            "prompt1".to_string(),
            "server1".to_string(),
            create_test_prompt("prompt1"),
        );
        inventory.insert_resource(
            "res1".to_string(),
            "server1".to_string(),
            create_test_resource("res1"),
        );

        inventory.mark_refreshed("server1");

        let (tools, prompts, resources) = inventory.counts();
        assert_eq!(tools, 1);
        assert_eq!(prompts, 1);
        assert_eq!(resources, 1);

        inventory.clear_all();

        let (tools, prompts, resources) = inventory.counts();
        assert_eq!(tools, 0);
        assert_eq!(prompts, 0);
        assert_eq!(resources, 0);
        assert!(inventory.last_refresh("server1").is_none());
    }
}