pmcp 2.4.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
//! Session management for HTTP-based transports.
//!
//! This module provides session lifecycle management for HTTP and SSE transports,
//! including session creation, persistence, and termination.

use crate::error::{Error, ErrorCode, Result};
use chrono::{DateTime, Duration, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tracing::{debug, info};
use uuid::Uuid;

/// Session configuration options.
#[derive(Debug, Clone)]
pub struct SessionConfig {
    /// Session timeout duration.
    pub timeout: Duration,

    /// Maximum number of concurrent sessions.
    pub max_sessions: usize,

    /// Whether to persist sessions across restarts.
    pub persistent: bool,

    /// Session cookie name.
    pub cookie_name: String,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::hours(24),
            max_sessions: 1000,
            persistent: false,
            cookie_name: "mcp-session-id".to_string(),
        }
    }
}

/// Session metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    /// Unique session identifier.
    pub id: String,

    /// Creation timestamp.
    pub created_at: DateTime<Utc>,

    /// Last activity timestamp.
    pub last_activity: DateTime<Utc>,

    /// Session expiry timestamp.
    pub expires_at: DateTime<Utc>,

    /// Client information.
    pub client_info: Option<ClientInfo>,

    /// Custom session data.
    pub data: serde_json::Value,

    /// Whether the session is authenticated.
    pub authenticated: bool,

    /// Authentication info if authenticated.
    pub auth_info: Option<String>,
}

/// Client information stored in session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientInfo {
    /// User agent string.
    pub user_agent: Option<String>,

    /// Client IP address.
    pub ip_address: Option<String>,

    /// Client protocol version.
    pub protocol_version: String,
}

/// Session manager for handling session lifecycle.
pub struct SessionManager {
    /// Session storage.
    sessions: Arc<DashMap<String, Session>>,

    /// Configuration.
    config: SessionConfig,

    /// Session event callbacks.
    callbacks: Arc<SessionCallbacks>,
}

impl std::fmt::Debug for SessionManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SessionManager")
            .field("sessions", &self.sessions.len())
            .field("config", &self.config)
            .field("callbacks", &"Arc<SessionCallbacks>")
            .finish()
    }
}

/// Session callback type.
pub type SessionCallback = Box<dyn Fn(&Session) + Send + Sync>;

/// Callbacks for session lifecycle events.
#[derive(Default)]
pub struct SessionCallbacks {
    /// Called when a session is created.
    pub on_create: Option<SessionCallback>,

    /// Called when a session is destroyed.
    pub on_destroy: Option<SessionCallback>,

    /// Called when a session expires.
    pub on_expire: Option<SessionCallback>,
}

impl std::fmt::Debug for SessionCallbacks {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SessionCallbacks")
            .field("on_create", &self.on_create.is_some())
            .field("on_destroy", &self.on_destroy.is_some())
            .field("on_expire", &self.on_expire.is_some())
            .finish()
    }
}

impl SessionManager {
    /// Create a new session manager.
    pub fn new(config: SessionConfig) -> Self {
        Self {
            sessions: Arc::new(DashMap::new()),
            config,
            callbacks: Arc::new(SessionCallbacks::default()),
        }
    }

    /// Create a new session.
    pub fn create_session(&self, client_info: Option<ClientInfo>) -> Result<Session> {
        // Check session limit
        if self.sessions.len() >= self.config.max_sessions {
            return Err(Error::protocol(
                ErrorCode::INTERNAL_ERROR,
                "Maximum session limit reached",
            ));
        }

        let now = Utc::now();
        let session = Session {
            id: Uuid::new_v4().to_string(),
            created_at: now,
            last_activity: now,
            expires_at: now + self.config.timeout,
            client_info,
            data: serde_json::Value::Object(serde_json::Map::new()),
            authenticated: false,
            auth_info: None,
        };

        self.sessions.insert(session.id.clone(), session.clone());

        // Call creation callback
        if let Some(callback) = &self.callbacks.on_create {
            callback(&session);
        }

        info!("Created new session: {}", session.id);
        Ok(session)
    }

    /// Get a session by ID.
    pub fn get_session(&self, session_id: &str) -> Option<Session> {
        self.sessions.get(session_id).map(|entry| {
            let mut session = entry.clone();

            // Update last activity
            session.last_activity = Utc::now();

            // Update in storage
            drop(entry);
            self.sessions
                .insert(session_id.to_string(), session.clone());

            session
        })
    }

    /// Validate and refresh a session.
    pub fn validate_session(&self, session_id: &str) -> Result<Session> {
        let session = self
            .get_session(session_id)
            .ok_or_else(|| Error::protocol(ErrorCode::INVALID_REQUEST, "Invalid session ID"))?;

        // Check if expired
        if session.expires_at < Utc::now() {
            self.destroy_session(session_id)?;
            return Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                "Session expired",
            ));
        }

        Ok(session)
    }

    /// Update session data.
    pub fn update_session<F>(&self, session_id: &str, updater: F) -> Result<()>
    where
        F: FnOnce(&mut Session),
    {
        let mut session = self
            .sessions
            .get_mut(session_id)
            .ok_or_else(|| Error::protocol(ErrorCode::INVALID_REQUEST, "Invalid session ID"))?;

        updater(&mut session);
        session.last_activity = Utc::now();

        Ok(())
    }

    /// Authenticate a session.
    pub fn authenticate_session(&self, session_id: &str, auth_info: String) -> Result<()> {
        self.update_session(session_id, |session| {
            session.authenticated = true;
            session.auth_info = Some(auth_info);
        })
    }

    /// Destroy a session.
    pub fn destroy_session(&self, session_id: &str) -> Result<()> {
        let session = self.sessions.remove(session_id).map(|(_, session)| session);

        if let Some(session) = session {
            // Call destruction callback
            if let Some(callback) = &self.callbacks.on_destroy {
                callback(&session);
            }

            info!("Destroyed session: {}", session_id);
            Ok(())
        } else {
            Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                "Session not found",
            ))
        }
    }

    /// Clean up expired sessions.
    pub fn cleanup_expired(&self) {
        let now = Utc::now();
        let expired: Vec<String> = self
            .sessions
            .iter()
            .filter(|entry| entry.expires_at < now)
            .map(|entry| entry.key().clone())
            .collect();

        for session_id in expired {
            if let Some((_, session)) = self.sessions.remove(&session_id) {
                // Call expiry callback
                if let Some(callback) = &self.callbacks.on_expire {
                    callback(&session);
                }

                debug!("Expired session: {}", session_id);
            }
        }
    }

    /// Get all active sessions.
    pub fn active_sessions(&self) -> Vec<Session> {
        self.sessions
            .iter()
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Get session count.
    pub fn session_count(&self) -> usize {
        self.sessions.len()
    }

    /// Set session callbacks.
    pub fn set_callbacks(&mut self, callbacks: SessionCallbacks) {
        self.callbacks = Arc::new(callbacks);
    }
}

/// Session cleanup task that runs periodically.
#[cfg(not(target_arch = "wasm32"))]
pub async fn session_cleanup_task(manager: Arc<SessionManager>, interval: Duration) {
    let mut interval = tokio::time::interval(
        interval
            .to_std()
            .unwrap_or(std::time::Duration::from_secs(300)),
    );

    loop {
        interval.tick().await;
        manager.cleanup_expired();
    }
}

/// Extract session ID from HTTP headers.
pub fn extract_session_id(headers: &std::collections::HashMap<String, String>) -> Option<String> {
    // Try cookie first
    if let Some(cookie_header) = headers.get("cookie").or_else(|| headers.get("Cookie")) {
        for cookie in cookie_header.split(';') {
            let parts: Vec<&str> = cookie.trim().splitn(2, '=').collect();
            if parts.len() == 2 && parts[0] == "mcp-session-id" {
                return Some(parts[1].to_string());
            }
        }
    }

    // Try X-Session-ID header
    headers
        .get("X-Session-ID")
        .or_else(|| headers.get("x-session-id"))
        .cloned()
}

/// Session middleware for HTTP requests.
pub struct SessionMiddleware {
    manager: Arc<SessionManager>,
}

impl std::fmt::Debug for SessionMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SessionMiddleware")
            .field("manager", &"Arc<SessionManager>")
            .finish()
    }
}

impl SessionMiddleware {
    /// Create new session middleware.
    pub fn new(manager: Arc<SessionManager>) -> Self {
        Self { manager }
    }

    /// Process request with session handling.
    pub async fn process<F, R>(
        &self,
        headers: &std::collections::HashMap<String, String>,
        handler: F,
    ) -> Result<(Option<Session>, R)>
    where
        F: FnOnce(Option<Session>) -> R,
    {
        let session = if let Some(session_id) = extract_session_id(headers) {
            self.manager.get_session(&session_id)
        } else {
            None
        };

        let result = handler(session.clone());
        Ok((session, result))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_session_creation() {
        let manager = SessionManager::new(SessionConfig::default());

        let session = manager.create_session(None).unwrap();
        assert!(!session.id.is_empty());
        assert!(!session.authenticated);
        assert_eq!(manager.session_count(), 1);
    }

    #[test]
    fn test_session_validation() {
        let manager = SessionManager::new(SessionConfig::default());

        let session = manager.create_session(None).unwrap();
        let validated = manager.validate_session(&session.id).unwrap();
        assert_eq!(session.id, validated.id);

        // Invalid session
        let result = manager.validate_session("invalid-id");
        assert!(result.is_err());
    }

    #[test]
    fn test_session_authentication() {
        let manager = SessionManager::new(SessionConfig::default());

        let session = manager.create_session(None).unwrap();
        manager
            .authenticate_session(&session.id, "user123".to_string())
            .unwrap();

        let updated = manager.get_session(&session.id).unwrap();
        assert!(updated.authenticated);
        assert_eq!(updated.auth_info, Some("user123".to_string()));
    }

    #[test]
    fn test_session_destruction() {
        let manager = SessionManager::new(SessionConfig::default());

        let session = manager.create_session(None).unwrap();
        assert_eq!(manager.session_count(), 1);

        manager.destroy_session(&session.id).unwrap();
        assert_eq!(manager.session_count(), 0);

        // Should fail to get destroyed session
        assert!(manager.get_session(&session.id).is_none());
    }

    #[test]
    fn test_session_expiry() {
        let config = SessionConfig {
            timeout: Duration::milliseconds(100), // Very short timeout
            ..Default::default()
        };
        let manager = SessionManager::new(config);

        let session = manager.create_session(None).unwrap();

        // Manually set expiry to past
        manager
            .update_session(&session.id, |s| {
                s.expires_at = Utc::now() - Duration::seconds(1);
            })
            .unwrap();

        manager.cleanup_expired();
        assert_eq!(manager.session_count(), 0);
    }

    #[test]
    fn test_session_limit() {
        let config = SessionConfig {
            max_sessions: 2,
            ..Default::default()
        };
        let manager = SessionManager::new(config);

        // Create max sessions
        manager.create_session(None).unwrap();
        manager.create_session(None).unwrap();

        // Should fail to create more
        let result = manager.create_session(None);
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_session_id() {
        let mut headers = std::collections::HashMap::new();

        // Test cookie extraction
        headers.insert(
            "Cookie".to_string(),
            "mcp-session-id=test123; other=value".to_string(),
        );
        assert_eq!(extract_session_id(&headers), Some("test123".to_string()));

        // Test header extraction
        headers.clear();
        headers.insert("X-Session-ID".to_string(), "test456".to_string());
        assert_eq!(extract_session_id(&headers), Some("test456".to_string()));

        // Test no session
        headers.clear();
        assert_eq!(extract_session_id(&headers), None);
    }
}