pmcp 2.1.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
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
//! Dynamic server management for runtime configuration changes.
//!
//! This module provides functionality to dynamically:
//! - Add/remove tools, prompts, and resources at runtime
//! - Update server capabilities
//! - Manage handler lifecycle
//! - Hot-reload configurations

use crate::error::{Error, ErrorCode, Result};
use crate::server::{PromptHandler, ResourceHandler, SamplingHandler, Server, ToolHandler};
use crate::types::capabilities::SamplingCapabilities;
use crate::types::{PromptInfo, ServerCapabilities, ToolInfo};
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use tokio::sync::RwLock;
use tracing::info;

/// Type alias for capability update listeners
type CapabilityListener = Box<dyn Fn(&ServerCapabilities) + Send + Sync>;

/// Dynamic server manager for runtime configuration
///
/// # Examples
///
/// ```rust,no_run
/// use pmcp::server::dynamic::DynamicServerManager;
/// use pmcp::server::Server;
/// use std::sync::Arc;
///
/// # async fn example() -> pmcp::Result<()> {
/// let server = Server::builder()
///     .name("dynamic-server")
///     .version("1.0.0")
///     .build()?;
/// let server = Arc::new(server);
///
/// let manager = DynamicServerManager::new(server.clone());
/// // Now you can add/remove tools, prompts, resources at runtime
/// # Ok(())
/// # }
/// ```
pub struct DynamicServerManager {
    /// The server instance
    server: Arc<Server>,

    /// Dynamic tool registry
    dynamic_tools: Arc<RwLock<HashMap<String, Arc<dyn ToolHandler>>>>,

    /// Dynamic prompt registry
    dynamic_prompts: Arc<RwLock<HashMap<String, Arc<dyn PromptHandler>>>>,

    /// Dynamic resource handler
    dynamic_resources: Arc<RwLock<Option<Arc<dyn ResourceHandler>>>>,

    /// Dynamic sampling handler
    dynamic_sampling: Arc<RwLock<Option<Arc<dyn SamplingHandler>>>>,

    /// Capability update callbacks
    #[allow(dead_code)]
    capability_listeners: Arc<RwLock<Vec<CapabilityListener>>>,
}

impl DynamicServerManager {
    /// Create a new dynamic server manager
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use pmcp::server::dynamic::DynamicServerManager;
    /// use pmcp::server::Server;
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> pmcp::Result<()> {
    /// let server = Server::builder()
    ///     .name("test-server")
    ///     .version("1.0.0")
    ///     .build()?;
    /// let server_arc = Arc::new(server);
    ///
    /// let manager = DynamicServerManager::new(server_arc);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(server: Arc<Server>) -> Self {
        Self {
            server,
            dynamic_tools: Arc::new(RwLock::new(HashMap::new())),
            dynamic_prompts: Arc::new(RwLock::new(HashMap::new())),
            dynamic_resources: Arc::new(RwLock::new(None)),
            dynamic_sampling: Arc::new(RwLock::new(None)),
            capability_listeners: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Add a tool at runtime
    ///
    /// Adds a tool handler to the dynamic registry for runtime tool availability.
    pub async fn add_tool(
        &self,
        name: impl Into<String>,
        handler: Arc<dyn ToolHandler>,
        _info: ToolInfo,
    ) -> Result<()> {
        let name = name.into();
        info!("Adding dynamic tool: {}", name);

        // Add to dynamic registry
        self.dynamic_tools
            .write()
            .await
            .insert(name.clone(), handler);

        // Update server capabilities to indicate tools are available
        self.update_capabilities(|caps| {
            caps.tools = Some(crate::types::ToolCapabilities {
                list_changed: Some(true),
            });
        })
        .await;

        Ok(())
    }

    /// Remove a tool at runtime
    pub async fn remove_tool(&self, name: &str) -> Result<()> {
        info!("Removing dynamic tool: {}", name);

        // Remove from dynamic registry
        if self.dynamic_tools.write().await.remove(name).is_none() {
            return Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                format!("Tool '{}' not found", name),
            ));
        }

        // Update server capabilities
        self.update_capabilities(|_caps| {
            // Dynamic tools are managed separately, capabilities stay the same
        })
        .await;

        Ok(())
    }

    /// Add a prompt at runtime
    pub async fn add_prompt(
        &self,
        name: impl Into<String>,
        handler: Arc<dyn PromptHandler>,
        _info: PromptInfo,
    ) -> Result<()> {
        let name = name.into();
        info!("Adding dynamic prompt: {}", name);

        // Add to dynamic registry
        self.dynamic_prompts
            .write()
            .await
            .insert(name.clone(), handler);

        // Update server capabilities to indicate prompts are available
        self.update_capabilities(|caps| {
            caps.prompts = Some(crate::types::PromptCapabilities {
                list_changed: Some(true),
            });
        })
        .await;

        Ok(())
    }

    /// Remove a prompt at runtime
    pub async fn remove_prompt(&self, name: &str) -> Result<()> {
        info!("Removing dynamic prompt: {}", name);

        // Remove from dynamic registry
        if self.dynamic_prompts.write().await.remove(name).is_none() {
            return Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                format!("Prompt '{}' not found", name),
            ));
        }

        // Update server capabilities
        self.update_capabilities(|_caps| {
            // Dynamic prompts are managed separately, capabilities stay the same
        })
        .await;

        Ok(())
    }

    /// Set resource handler at runtime
    pub async fn set_resource_handler(&self, handler: Arc<dyn ResourceHandler>) -> Result<()> {
        info!("Setting dynamic resource handler");

        *self.dynamic_resources.write().await = Some(handler);

        // Update server capabilities
        self.update_capabilities(|caps| {
            caps.resources = Some(crate::types::ResourceCapabilities {
                subscribe: Some(true),
                list_changed: Some(true),
            });
        })
        .await;

        Ok(())
    }

    /// Remove resource handler at runtime
    pub async fn remove_resource_handler(&self) -> Result<()> {
        info!("Removing dynamic resource handler");

        *self.dynamic_resources.write().await = None;

        // Update server capabilities
        self.update_capabilities(|caps| {
            caps.resources = None;
        })
        .await;

        Ok(())
    }

    /// Set sampling handler at runtime
    pub async fn set_sampling_handler(&self, handler: Arc<dyn SamplingHandler>) -> Result<()> {
        info!("Setting dynamic sampling handler");

        *self.dynamic_sampling.write().await = Some(handler);

        // Update server capabilities
        self.update_capabilities(|caps| {
            caps.sampling = Some(SamplingCapabilities::default());
        })
        .await;

        Ok(())
    }

    /// Remove sampling handler at runtime
    pub async fn remove_sampling_handler(&self) -> Result<()> {
        info!("Removing dynamic sampling handler");

        *self.dynamic_sampling.write().await = None;

        // Update server capabilities
        self.update_capabilities(|caps| {
            caps.sampling = None;
        })
        .await;

        Ok(())
    }

    /// Register a capability update listener
    pub async fn add_capability_listener<F>(&self, listener: F)
    where
        F: Fn(&ServerCapabilities) + Send + Sync + 'static,
    {
        self.capability_listeners
            .write()
            .await
            .push(Box::new(listener));
    }

    /// Get current dynamic tools
    pub async fn get_dynamic_tools(&self) -> HashMap<String, Arc<dyn ToolHandler>> {
        self.dynamic_tools.read().await.clone()
    }

    /// Get current dynamic prompts
    pub async fn get_dynamic_prompts(&self) -> HashMap<String, Arc<dyn PromptHandler>> {
        self.dynamic_prompts.read().await.clone()
    }

    /// Check if a tool exists (either static or dynamic)
    pub async fn has_tool(&self, name: &str) -> bool {
        self.dynamic_tools.read().await.contains_key(name) || self.server.has_tool(name)
    }

    /// Check if a prompt exists (either static or dynamic)
    pub async fn has_prompt(&self, name: &str) -> bool {
        self.dynamic_prompts.read().await.contains_key(name) || self.server.has_prompt(name)
    }

    /// Reload configuration from a source
    pub async fn reload_configuration(&self, config: DynamicConfig) -> Result<()> {
        info!("Reloading dynamic configuration");

        // Clear existing dynamic handlers
        self.dynamic_tools.write().await.clear();
        self.dynamic_prompts.write().await.clear();

        // Apply new configuration
        for (name, tool) in config.tools {
            self.add_tool(name, tool.handler, tool.info).await?;
        }

        for (name, prompt) in config.prompts {
            self.add_prompt(name, prompt.handler, prompt.info).await?;
        }

        if let Some(resources) = config.resources {
            self.set_resource_handler(resources).await?;
        }

        if let Some(sampling) = config.sampling {
            self.set_sampling_handler(sampling).await?;
        }

        Ok(())
    }

    /// Update server capabilities and notify listeners
    async fn update_capabilities<F>(&self, updater: F)
    where
        F: FnOnce(&mut ServerCapabilities),
    {
        // Note: In a real implementation, we'd need to update the actual
        // server capabilities and send notifications to connected clients
        let mut caps = self.server.capabilities.clone();
        updater(&mut caps);

        // Notify listeners
        let listeners = self.capability_listeners.read().await;
        for listener in listeners.iter() {
            listener(&caps);
        }
    }
}

impl std::fmt::Debug for DynamicServerManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DynamicServerManager")
            .field("server", &"Arc<Server>")
            .field("dynamic_tools", &"Arc<RwLock<HashMap<...>>>")
            .field("dynamic_prompts", &"Arc<RwLock<HashMap<...>>>")
            .field("dynamic_resources", &"Arc<RwLock<Option<...>>>")
            .field("dynamic_sampling", &"Arc<RwLock<Option<...>>>")
            .field("capability_listeners", &"Arc<RwLock<Vec<...>>>")
            .finish()
    }
}

/// Configuration for dynamic server updates
#[derive(Default)]
pub struct DynamicConfig {
    /// Dynamic tools to add
    pub tools: HashMap<String, DynamicTool>,

    /// Dynamic prompts to add
    pub prompts: HashMap<String, DynamicPrompt>,

    /// Dynamic resource handler
    pub resources: Option<Arc<dyn ResourceHandler>>,

    /// Dynamic sampling handler
    pub sampling: Option<Arc<dyn SamplingHandler>>,
}

impl std::fmt::Debug for DynamicConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DynamicConfig")
            .field("tools", &self.tools.keys().collect::<Vec<_>>())
            .field("prompts", &self.prompts.keys().collect::<Vec<_>>())
            .field("resources", &self.resources.is_some())
            .field("sampling", &self.sampling.is_some())
            .finish()
    }
}

/// Dynamic tool configuration
pub struct DynamicTool {
    /// Tool handler
    pub handler: Arc<dyn ToolHandler>,

    /// Tool information
    pub info: ToolInfo,
}

impl std::fmt::Debug for DynamicTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DynamicTool")
            .field("handler", &"Arc<dyn ToolHandler>")
            .field("info", &self.info)
            .finish()
    }
}

/// Dynamic prompt configuration
pub struct DynamicPrompt {
    /// Prompt handler
    pub handler: Arc<dyn PromptHandler>,

    /// Prompt information
    pub info: PromptInfo,
}

impl std::fmt::Debug for DynamicPrompt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DynamicPrompt")
            .field("handler", &"Arc<dyn PromptHandler>")
            .field("info", &self.info)
            .finish()
    }
}

/// Builder for dynamic configuration
#[derive(Debug)]
pub struct DynamicConfigBuilder {
    config: DynamicConfig,
}

impl DynamicConfigBuilder {
    /// Create a new dynamic configuration builder
    pub fn new() -> Self {
        Self {
            config: DynamicConfig::default(),
        }
    }

    /// Add a tool to the configuration
    pub fn tool(
        mut self,
        name: impl Into<String>,
        handler: Arc<dyn ToolHandler>,
        info: ToolInfo,
    ) -> Self {
        self.config
            .tools
            .insert(name.into(), DynamicTool { handler, info });
        self
    }

    /// Add a prompt to the configuration
    pub fn prompt(
        mut self,
        name: impl Into<String>,
        handler: Arc<dyn PromptHandler>,
        info: PromptInfo,
    ) -> Self {
        self.config
            .prompts
            .insert(name.into(), DynamicPrompt { handler, info });
        self
    }

    /// Set the resource handler
    pub fn resources(mut self, handler: Arc<dyn ResourceHandler>) -> Self {
        self.config.resources = Some(handler);
        self
    }

    /// Set the sampling handler
    pub fn sampling(mut self, handler: Arc<dyn SamplingHandler>) -> Self {
        self.config.sampling = Some(handler);
        self
    }

    /// Build the configuration
    pub fn build(self) -> DynamicConfig {
        self.config
    }
}

impl Default for DynamicConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::server::cancellation::RequestHandlerExtra;
    use crate::server::ServerBuilder;
    use crate::types::GetPromptResult;
    use async_trait::async_trait;
    use serde_json::json;

    struct TestTool;

    #[async_trait]
    impl ToolHandler for TestTool {
        async fn handle(
            &self,
            _args: serde_json::Value,
            _extra: RequestHandlerExtra,
        ) -> Result<serde_json::Value> {
            Ok(json!({"result": "test"}))
        }
    }

    struct TestPrompt;

    #[async_trait]
    impl PromptHandler for TestPrompt {
        async fn handle(
            &self,
            _args: HashMap<String, String>,
            _extra: RequestHandlerExtra,
        ) -> Result<GetPromptResult> {
            Ok(GetPromptResult {
                description: Some("Test prompt".to_string()),
                messages: vec![],
                _meta: None,
            })
        }
    }

    #[tokio::test]
    async fn test_dynamic_tool_management() {
        let server = Arc::new(
            ServerBuilder::new()
                .name("test")
                .version("1.0.0")
                .build()
                .unwrap(),
        );

        let manager = DynamicServerManager::new(server);

        // Add a tool
        let tool_info = ToolInfo::new(
            "dynamic_test",
            Some("Dynamic test tool".to_string()),
            json!({}),
        );

        manager
            .add_tool("dynamic_test", Arc::new(TestTool), tool_info.clone())
            .await
            .unwrap();

        assert!(manager.has_tool("dynamic_test").await);

        // Remove the tool
        manager.remove_tool("dynamic_test").await.unwrap();

        assert!(!manager.has_tool("dynamic_test").await);
    }

    #[tokio::test]
    async fn test_dynamic_configuration() {
        let server = Arc::new(
            ServerBuilder::new()
                .name("test")
                .version("1.0.0")
                .build()
                .unwrap(),
        );

        let manager = DynamicServerManager::new(server);

        // Build a configuration
        let config = DynamicConfigBuilder::new()
            .tool(
                "tool1",
                Arc::new(TestTool),
                ToolInfo::new("tool1", Some("Tool 1".to_string()), json!({})),
            )
            .prompt(
                "prompt1",
                Arc::new(TestPrompt),
                PromptInfo::new("prompt1").with_description("Prompt 1"),
            )
            .build();

        // Reload configuration
        manager.reload_configuration(config).await.unwrap();

        assert!(manager.has_tool("tool1").await);
        assert!(manager.has_prompt("prompt1").await);
    }
}