inventory.rs 12.5 KB
Newer Older
1
2
3
//! MCP tool, prompt, and resource inventory.
//!
//! Thread-safe cache for MCP capabilities across all connected servers.
4
5
6

use dashmap::DashMap;

7
use crate::mcp::config::{Prompt, RawResource, Tool};
8
9
10
11
12

/// Cached tool with metadata
#[derive(Clone)]
pub struct CachedTool {
    pub server_name: String,
13
    pub tool: Tool,
14
15
16
17
18
19
}

/// Cached prompt with metadata
#[derive(Clone)]
pub struct CachedPrompt {
    pub server_name: String,
20
    pub prompt: Prompt,
21
22
23
24
25
26
}

/// Cached resource with metadata
#[derive(Clone)]
pub struct CachedResource {
    pub server_name: String,
27
    pub resource: RawResource,
28
29
}

30
/// Tool inventory with periodic refresh
31
///
32
33
/// Provides thread-safe caching of MCP tools, prompts, and resources.
/// Entries are refreshed periodically by background tasks.
34
35
36
37
38
39
40
41
42
43
44
45
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>,
}

impl ToolInventory {
46
47
    /// Create a new tool inventory
    pub fn new() -> Self {
48
49
50
51
52
53
        Self {
            tools: DashMap::new(),
            prompts: DashMap::new(),
            resources: DashMap::new(),
        }
    }
54
}
55

56
57
58
59
60
61
62
impl Default for ToolInventory {
    fn default() -> Self {
        Self::new()
    }
}

impl ToolInventory {
63
64
65
66
    // ============================================================================
    // Tool Methods
    // ============================================================================

67
    /// Get a tool if it exists
68
    pub fn get_tool(&self, tool_name: &str) -> Option<(String, Tool)> {
69
70
71
        self.tools
            .get(tool_name)
            .map(|entry| (entry.server_name.clone(), entry.tool.clone()))
72
73
    }

74
    /// Check if tool exists
75
76
77
78
79
    pub fn has_tool(&self, tool_name: &str) -> bool {
        self.tools.contains_key(tool_name)
    }

    /// Insert or update a tool
80
    pub fn insert_tool(&self, tool_name: String, server_name: String, tool: Tool) {
81
82
        self.tools
            .insert(tool_name, CachedTool { server_name, tool });
83
84
    }

85
    /// Get all tools
86
    pub fn list_tools(&self) -> Vec<(String, String, Tool)> {
87
88
        self.tools
            .iter()
89
            .map(|entry| {
90
                let (name, cached) = entry.pair();
91
92
93
94
95
                (
                    name.clone(),
                    cached.server_name.clone(),
                    cached.tool.clone(),
                )
96
97
98
99
100
101
102
103
            })
            .collect()
    }

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

104
    /// Get a prompt if it exists
105
    pub fn get_prompt(&self, prompt_name: &str) -> Option<(String, Prompt)> {
106
107
108
        self.prompts
            .get(prompt_name)
            .map(|entry| (entry.server_name.clone(), entry.prompt.clone()))
109
110
    }

111
    /// Check if prompt exists
112
113
114
115
116
    pub fn has_prompt(&self, prompt_name: &str) -> bool {
        self.prompts.contains_key(prompt_name)
    }

    /// Insert or update a prompt
117
    pub fn insert_prompt(&self, prompt_name: String, server_name: String, prompt: Prompt) {
118
119
120
121
122
123
124
125
126
        self.prompts.insert(
            prompt_name,
            CachedPrompt {
                server_name,
                prompt,
            },
        );
    }

127
    /// Get all prompts
128
    pub fn list_prompts(&self) -> Vec<(String, String, Prompt)> {
129
130
        self.prompts
            .iter()
131
            .map(|entry| {
132
                let (name, cached) = entry.pair();
133
134
135
136
137
                (
                    name.clone(),
                    cached.server_name.clone(),
                    cached.prompt.clone(),
                )
138
139
140
141
142
143
144
145
            })
            .collect()
    }

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

146
    /// Get a resource if it exists
147
    pub fn get_resource(&self, resource_uri: &str) -> Option<(String, RawResource)> {
148
149
150
        self.resources
            .get(resource_uri)
            .map(|entry| (entry.server_name.clone(), entry.resource.clone()))
151
152
    }

153
    /// Check if resource exists
154
155
156
157
158
159
160
161
162
    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,
163
        resource: RawResource,
164
165
166
167
168
169
170
171
172
173
    ) {
        self.resources.insert(
            resource_uri,
            CachedResource {
                server_name,
                resource,
            },
        );
    }

174
    /// Get all resources
175
    pub fn list_resources(&self) -> Vec<(String, String, RawResource)> {
176
177
        self.resources
            .iter()
178
            .map(|entry| {
179
                let (uri, cached) = entry.pair();
180
181
182
183
184
                (
                    uri.clone(),
                    cached.server_name.clone(),
                    cached.resource.clone(),
                )
185
186
187
188
189
190
191
192
            })
            .collect()
    }

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

193
    /// Clear all cached items for a specific server (called when LRU evicts client)
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
    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);
    }

    /// 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();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
219
    use crate::mcp::config::{Prompt, RawResource, Tool};
220
221

    // Helper to create a test tool
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    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,
244
245
246
247
        }
    }

    // Helper to create a test prompt
248
249
    fn create_test_prompt(name: &str) -> Prompt {
        Prompt {
250
            name: name.to_string(),
251
            title: None,
252
253
            description: Some(format!("Test prompt: {}", name)),
            arguments: None,
254
            icons: None,
255
256
257
258
        }
    }

    // Helper to create a test resource
259
260
    fn create_test_resource(uri: &str) -> RawResource {
        RawResource {
261
262
            uri: uri.to_string(),
            name: uri.to_string(),
263
            title: None,
264
265
            description: Some(format!("Test resource: {}", uri)),
            mime_type: Some("text/plain".to_string()),
266
267
            size: None,
            icons: None,
268
269
270
271
272
        }
    }

    #[test]
    fn test_tool_insert_and_get() {
273
        let inventory = ToolInventory::new();
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        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_has_tool() {
288
        let inventory = ToolInventory::new();
289
290
291
292
293
294
295
296
297
298
299
        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() {
300
        let inventory = ToolInventory::new();
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

        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_clear_server_tools() {
324
        let inventory = ToolInventory::new();
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347

        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_prompt_operations() {
348
        let inventory = ToolInventory::new();
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        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() {
369
        let inventory = ToolInventory::new();
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
        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;

392
        let inventory = Arc::new(ToolInventory::new());
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416

        // 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() {
417
        let inventory = ToolInventory::new();
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

        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"),
        );

        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);
    }
}