mcp-protocol-sdk 0.5.1

Production-ready Rust SDK for the Model Context Protocol (MCP) with multiple transport support
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
//! Additional server lifecycle types for comprehensive testing

use crate::core::error::{McpError, McpResult};
use async_trait::async_trait;
use std::collections::HashMap;
use std::time::Duration;

// Missing lifecycle manager types
#[derive(Debug, Clone, PartialEq)]
pub enum ServerState {
    Stopped,
    Starting,
    Running,
    Stopping,
}

pub struct LifecycleManager {
    state: ServerState,
}

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

impl LifecycleManager {
    pub fn new() -> Self {
        Self {
            state: ServerState::Stopped,
        }
    }

    pub fn get_state(&self) -> ServerState {
        self.state.clone()
    }

    pub async fn transition_to(&mut self, state: ServerState) {
        self.state = state;
    }

    pub async fn start(&mut self) -> McpResult<()> {
        self.transition_to(ServerState::Starting).await;
        self.transition_to(ServerState::Running).await;
        Ok(())
    }

    pub async fn stop(&mut self) -> McpResult<()> {
        self.transition_to(ServerState::Stopping).await;
        self.transition_to(ServerState::Stopped).await;
        Ok(())
    }

    pub fn get_listener_count(&self, _event: &str) -> usize {
        0
    }
    pub fn get_hook_count(&self, _hook: &str) -> usize {
        0
    }

    pub fn on_start(&mut self, _callback: Box<dyn Fn() -> McpResult<()> + Send + Sync>) {}
    pub fn on_stop(&mut self, _callback: Box<dyn Fn() -> McpResult<()> + Send + Sync>) {}
    pub fn add_pre_start_hook(&mut self, _callback: Box<dyn Fn() -> McpResult<()> + Send + Sync>) {}
    pub fn add_post_start_hook(&mut self, _callback: Box<dyn Fn() -> McpResult<()> + Send + Sync>) {
    }
    pub fn add_pre_stop_hook(&mut self, _callback: Box<dyn Fn() -> McpResult<()> + Send + Sync>) {}
    pub fn add_post_stop_hook(&mut self, _callback: Box<dyn Fn() -> McpResult<()> + Send + Sync>) {}
}

// Missing configuration types
#[derive(Debug, Clone)]
pub struct ServerConfig {
    pub name: String,
    pub version: String,
    pub max_connections: usize,
    pub request_timeout: Duration,
    pub enable_logging: bool,
    pub log_level: String,
    pub graceful_shutdown_timeout: Duration,
}

#[derive(Debug, Clone)]
pub struct GracefulShutdownConfig {
    pub timeout: Duration,
    pub force_after_timeout: bool,
    pub notify_clients: bool,
    pub save_state: bool,
}

#[derive(Debug, Clone)]
pub struct SecurityConfig {
    pub require_authentication: bool,
    pub rate_limiting: RateLimitConfig,
    pub input_validation: ValidationConfig,
    pub allowed_methods: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct RateLimitConfig {
    pub requests_per_minute: u32,
    pub burst_size: u32,
    pub per_client: bool,
}

#[derive(Debug, Clone)]
pub struct ValidationConfig {
    pub max_request_size: usize,
    pub max_string_length: usize,
    pub max_array_length: usize,
    pub sanitize_input: bool,
}

// Missing health and management types
#[derive(Debug, Clone)]
pub enum HealthStatus {
    Healthy,
    Unhealthy(String),
    Warning(String),
}

pub struct ServerRunner {
    config: ServerConfig,
}

impl ServerRunner {
    pub fn new(config: ServerConfig) -> McpResult<Self> {
        Ok(Self { config })
    }

    pub fn get_config(&self) -> &ServerConfig {
        &self.config
    }
}

pub struct ShutdownSignalHandler;

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

impl ShutdownSignalHandler {
    pub fn new() -> Self {
        Self
    }
    pub fn register_signal_handler(&mut self, _signal: SignalType) {}
    pub fn set_shutdown_config(&mut self, _config: GracefulShutdownConfig) {}
    pub fn get_shutdown_config(&self) -> GracefulShutdownConfig {
        GracefulShutdownConfig {
            timeout: Duration::from_secs(5),
            force_after_timeout: true,
            notify_clients: true,
            save_state: true,
        }
    }
}

#[derive(Debug, Clone)]
pub enum SignalType {
    Interrupt,
    Terminate,
}

// Additional placeholder types for tests
pub struct HealthChecker;

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

impl HealthChecker {
    pub fn new() -> Self {
        Self
    }
    pub fn add_check(&mut self, _name: &str, _check: Box<dyn Fn() -> McpResult<HealthStatus>>) {}
    pub async fn check_health(&self) -> OverallHealth {
        OverallHealth {
            status: HealthStatus::Healthy,
            checks: HashMap::new(),
        }
    }
}

pub struct OverallHealth {
    pub status: HealthStatus,
    pub checks: HashMap<String, HealthStatus>,
}

pub struct ResourceCleanupManager;

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

impl ResourceCleanupManager {
    pub fn new() -> Self {
        Self
    }
    pub fn register_cleanup(&mut self, _name: &str, _cleanup: Box<dyn Fn() -> McpResult<()>>) {}
    pub async fn cleanup_all(&self) -> McpResult<()> {
        Ok(())
    }
    pub fn get_cleanup_task_count(&self) -> usize {
        0
    }
}

pub struct ServerMetrics;

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

impl ServerMetrics {
    pub fn new() -> Self {
        Self
    }
    pub fn record_request(&mut self, _method: &str) {}
    pub fn record_response_time(&mut self, _method: &str, _duration: Duration) {}
    pub fn record_error(&mut self, _method: &str, _error: &str) {}
    pub fn record_connection(&mut self) {}
    pub fn record_disconnection(&mut self) {}
    pub fn get_stats(&self) -> ServerStats {
        ServerStats {
            total_requests: 0,
            request_counts: HashMap::new(),
            error_count: 0,
            active_connections: 0,
            average_response_time: Duration::ZERO,
        }
    }
    pub fn get_most_popular_endpoints(&self, _limit: usize) -> Vec<(String, usize)> {
        vec![]
    }
}

pub struct ServerStats {
    pub total_requests: usize,
    pub request_counts: HashMap<String, usize>,
    pub error_count: usize,
    pub active_connections: usize,
    pub average_response_time: Duration,
}

pub struct ConfigurationManager;

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

impl ConfigurationManager {
    pub fn new() -> Self {
        Self
    }
    pub async fn load_config(&mut self, _config: ServerConfig) -> McpResult<()> {
        Ok(())
    }
    pub fn get_config(&self) -> ServerConfig {
        ServerConfig {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            max_connections: 50,
            request_timeout: Duration::from_secs(30),
            enable_logging: true,
            log_level: "info".to_string(),
            graceful_shutdown_timeout: Duration::from_secs(10),
        }
    }
    pub async fn hot_reload(&mut self, _config: ServerConfig) -> McpResult<()> {
        Ok(())
    }
}

pub struct StatePersistenceManager;

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

impl StatePersistenceManager {
    pub fn new() -> Self {
        Self
    }
    pub async fn save_state(&self, _state: &ServerPersistentState) -> McpResult<()> {
        Ok(())
    }
    pub async fn load_state(&self) -> McpResult<ServerPersistentState> {
        Ok(ServerPersistentState {
            active_connections: vec![],
            registered_tools: vec![],
            cached_resources: HashMap::new(),
            metrics: ServerMetricsSnapshot {
                total_requests: 0,
                total_errors: 0,
                uptime: Duration::ZERO,
                last_restart: std::time::SystemTime::now(),
            },
        })
    }
}

pub struct ServerPersistentState {
    pub active_connections: Vec<String>,
    pub registered_tools: Vec<String>,
    pub cached_resources: HashMap<String, String>,
    pub metrics: ServerMetricsSnapshot,
}

pub struct ServerMetricsSnapshot {
    pub total_requests: usize,
    pub total_errors: usize,
    pub uptime: Duration,
    pub last_restart: std::time::SystemTime,
}

pub struct PluginManager {
    plugins: Vec<Box<dyn Plugin>>,
}

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

impl PluginManager {
    pub fn new() -> Self {
        Self {
            plugins: Vec::new(),
        }
    }

    pub fn register_plugin(&mut self, plugin: Box<dyn Plugin>) {
        self.plugins.push(plugin);
    }

    pub fn get_plugin_count(&self) -> usize {
        self.plugins.len()
    }

    pub async fn initialize_all(&mut self) -> McpResult<()> {
        for plugin in &mut self.plugins {
            plugin.initialize().await?;
        }
        Ok(())
    }

    pub async fn shutdown_all(&mut self) -> McpResult<()> {
        for plugin in &mut self.plugins {
            plugin.shutdown().await?;
        }
        Ok(())
    }

    pub fn get_enabled_plugins(&self) -> Vec<String> {
        self.plugins
            .iter()
            .filter(|p| p.is_enabled())
            .map(|p| p.name().to_string())
            .collect()
    }
}

#[async_trait]
pub trait Plugin: Send + Sync {
    fn name(&self) -> &str;
    fn version(&self) -> &str;
    fn is_enabled(&self) -> bool;
    async fn initialize(&mut self) -> Result<(), McpError>;
    async fn shutdown(&mut self) -> Result<(), McpError>;
}

pub struct AsyncTaskManager;

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

impl AsyncTaskManager {
    pub fn new() -> Self {
        Self
    }
    pub fn spawn_task<F>(&mut self, _name: &str, _task: F) -> tokio::task::JoinHandle<()>
    where
        F: std::future::Future<Output = ()> + Send + 'static,
    {
        tokio::spawn(async {})
    }
    pub fn get_active_task_count(&self) -> usize {
        0
    }
    pub fn is_task_running(&self, _name: &str) -> bool {
        false
    }
    pub async fn cancel_task(&mut self, _name: &str) {}
    pub async fn wait_for_task_completion(&self, _name: &str) {}
    pub async fn shutdown_all_tasks(&self, _timeout: Duration) -> McpResult<()> {
        Ok(())
    }
}