turul-mcp-server 0.3.34

High-level framework for building Model Context Protocol (MCP) servers
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
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
638
639
640
641
642
643
644
//! Comprehensive Notification Broadcasting Tests
//!
//! This module tests all aspects of notification broadcasting including:
//! - Session event broadcasting to individual sessions
//! - System-wide broadcast capabilities
//! - MCP-compliant notification types (progress, logging, resources, tools)
//! - Real-time notification delivery and SSE integration
//! - Error handling and edge cases for notification systems

use std::sync::Arc;

use serde_json::json;

use crate::session::{SessionEvent, SessionManager};
use turul_mcp_protocol::{ServerCapabilities, logging::LoggingLevel};

/// Helper function to convert string level to LoggingLevel enum for tests
fn str_to_logging_level(level: &str) -> LoggingLevel {
    match level.to_lowercase().as_str() {
        "debug" => LoggingLevel::Debug,
        "info" => LoggingLevel::Info,
        "notice" => LoggingLevel::Notice,
        "warning" => LoggingLevel::Warning,
        "error" => LoggingLevel::Error,
        "critical" => LoggingLevel::Critical,
        "alert" => LoggingLevel::Alert,
        "emergency" => LoggingLevel::Emergency,
        _ => LoggingLevel::Info, // Default fallback
    }
}

/// Test basic notification sending to specific sessions
#[cfg(test)]
mod session_notification_tests {
    use super::*;

    #[tokio::test]
    async fn test_send_notification_to_existing_session() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        let session_id = manager.create_session().await;

        // Test different notification types
        let notifications = vec![
            SessionEvent::KeepAlive,
            SessionEvent::Notification(json!({
                "jsonrpc": "2.0",
                "method": "notifications/message",
                "params": {
                    "level": "info",
                    "message": "Test notification"
                }
            })),
            SessionEvent::Custom {
                event_type: "test_event".to_string(),
                data: json!({"custom": "data"}),
            },
        ];

        for notification in notifications {
            let result = manager
                .send_event_to_session(&session_id, notification)
                .await;
            // Note: Result may be Ok or Err depending on whether there are active receivers
            // This is normal behavior for broadcast channels
            if let Err(e) = result {
                println!(
                    "Note: Notification may fail without active receivers: {:?}",
                    e
                );
            }
        }
    }

    #[tokio::test]
    async fn test_send_notification_to_nonexistent_session() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        let nonexistent_session = "non-existent-session-id";
        let notification = SessionEvent::KeepAlive;

        let result = manager
            .send_event_to_session(nonexistent_session, notification)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[tokio::test]
    async fn test_notification_delivery_with_session_context() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // Test different context notification methods
        context
            .notify_log(
                turul_mcp_protocol::logging::LoggingLevel::Info,
                serde_json::json!("Test log message"),
                Some("test".to_string()),
                None,
            )
            .await;
        context.notify_progress("test-token", 25).await;
        context
            .notify_progress_with_total("test-token", 50, 100)
            .await;
        context.notify_resources_changed().await;
        context.notify_resource_updated("test://resource").await;
        context.notify_tools_changed().await;

        let custom_event = SessionEvent::Custom {
            event_type: "test_custom".to_string(),
            data: json!({"message": "custom notification"}),
        };
        context.notify(custom_event).await;

        // These should not panic - notifications are fire-and-forget
    }
}

/// Test system-wide broadcast capabilities
#[cfg(test)]
mod broadcast_notification_tests {
    use super::*;

    #[tokio::test]
    async fn test_broadcast_to_multiple_sessions() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        // Create multiple sessions
        let session1 = manager.create_session().await;
        let session2 = manager.create_session().await;
        let session3 = manager.create_session().await;

        assert_eq!(manager.session_count().await, 3);

        // Broadcast a message to all sessions
        let broadcast_event = SessionEvent::Custom {
            event_type: "system_announcement".to_string(),
            data: json!({
                "message": "System maintenance scheduled",
                "priority": "high"
            }),
        };

        manager.broadcast_event(broadcast_event).await;

        // Verify sessions still exist (broadcast shouldn't affect session lifecycle)
        assert!(manager.session_exists(&session1).await);
        assert!(manager.session_exists(&session2).await);
        assert!(manager.session_exists(&session3).await);
        assert_eq!(manager.session_count().await, 3);
    }

    #[tokio::test]
    async fn test_broadcast_to_empty_session_list() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        // No sessions created
        assert_eq!(manager.session_count().await, 0);

        let broadcast_event = SessionEvent::KeepAlive;

        // Broadcasting to no sessions should not panic or error
        manager.broadcast_event(broadcast_event).await;
    }

    #[tokio::test]
    async fn test_broadcast_with_session_removal_during_broadcast() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        // Create sessions
        let session1 = manager.create_session().await;
        let session2 = manager.create_session().await;
        let session3 = manager.create_session().await;

        // Remove one session
        let removed = manager.remove_session(&session2).await;
        assert!(removed);
        assert_eq!(manager.session_count().await, 2);

        // Broadcast should work with remaining sessions
        let broadcast_event = SessionEvent::Custom {
            event_type: "partial_broadcast".to_string(),
            data: json!({"remaining_sessions": 2}),
        };

        manager.broadcast_event(broadcast_event).await;

        // Verify remaining sessions
        assert!(manager.session_exists(&session1).await);
        assert!(!manager.session_exists(&session2).await);
        assert!(manager.session_exists(&session3).await);
    }
}

/// Test MCP-compliant notification types
#[cfg(test)]
mod mcp_notification_tests {
    use super::*;

    #[tokio::test]
    async fn test_progress_notifications() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // Test progress notifications with different patterns
        let progress_tokens = ["upload", "download", "processing", "analysis"];

        for (i, token) in progress_tokens.iter().enumerate() {
            let progress = (i as u64 + 1) * 25;
            context.notify_progress(*token, progress).await;

            // Also test with total
            context
                .notify_progress_with_total(*token, progress, 100)
                .await;
        }

        // Test edge cases
        context.notify_progress("zero-progress", 0).await;
        context
            .notify_progress_with_total("complete", 100, 100)
            .await;
        context.notify_progress("over-100", 150).await; // Should still work
    }

    #[tokio::test]
    async fn test_logging_notifications() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // Test different log levels
        let log_levels = vec!["debug", "info", "warn", "error"];

        for level in log_levels {
            context
                .notify_log(
                    str_to_logging_level(level),
                    serde_json::json!(format!("Test {} message", level)),
                    Some("test".to_string()),
                    None,
                )
                .await;
        }

        // Test with complex messages
        context
            .notify_log(
                str_to_logging_level("info"),
                serde_json::json!("Multi-line\nmessage\nwith special chars: 🚀"),
                Some("test".to_string()),
                None,
            )
            .await;
        context
            .notify_log(
                str_to_logging_level("error"),
                json!({"structured": "log", "error_code": 500}),
                Some("test".to_string()),
                None,
            )
            .await;
    }

    #[tokio::test]
    async fn test_resource_notifications() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // Test resource list changed notification
        context.notify_resources_changed().await;

        // Test specific resource updates
        let resource_uris = vec![
            "file:///path/to/resource.txt",
            "http://example.com/api/resource",
            "custom://schema/resource/123",
            "mem://temporary/resource",
        ];

        for uri in resource_uris {
            context.notify_resource_updated(uri).await;
        }
    }

    #[tokio::test]
    async fn test_tool_notifications() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // Test tools list changed notification
        context.notify_tools_changed().await;

        // Tool notifications should be fire-and-forget
        // Multiple calls should not cause issues
        for _ in 0..5 {
            context.notify_tools_changed().await;
        }
    }

    #[tokio::test]
    async fn test_custom_notifications() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // Test various custom notification types
        let custom_notifications = vec![
            SessionEvent::Custom {
                event_type: "user_interaction".to_string(),
                data: json!({
                    "action": "click",
                    "element": "button",
                    "timestamp": "2024-01-01T00:00:00Z"
                }),
            },
            SessionEvent::Custom {
                event_type: "system_alert".to_string(),
                data: json!({
                    "severity": "warning",
                    "message": "High memory usage detected",
                    "threshold": 85.5
                }),
            },
            SessionEvent::Custom {
                event_type: "data_update".to_string(),
                data: json!({
                    "table": "users",
                    "operation": "insert",
                    "count": 1
                }),
            },
        ];

        for notification in custom_notifications {
            context.notify(notification).await;
        }
    }
}

/// Test notification delivery and SSE integration
#[cfg(test)]
mod notification_delivery_tests {
    use super::*;

    #[tokio::test]
    async fn test_session_event_subscription() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        let session_id = manager.create_session().await;

        // Note: For testing SSE subscription, we need access to session internals
        // In a real implementation, this would be handled by the HTTP/SSE layer
        // For now, we'll test the manager's event sending capability

        // Send a test event
        let test_event = SessionEvent::Custom {
            event_type: "test".to_string(),
            data: json!({"test": "data"}),
        };

        let send_result = manager
            .send_event_to_session(&session_id, test_event.clone())
            .await;
        // Result depends on whether there are active receivers
        if send_result.is_ok() {
            println!("Event sent successfully");
        } else {
            println!(
                "Event send failed (no active receivers): {:?}",
                send_result.err()
            );
        }
    }

    #[tokio::test]
    async fn test_multiple_subscribers_per_session() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        let session_id = manager.create_session().await;

        // Test sending multiple events to the same session
        let events = vec![
            SessionEvent::KeepAlive,
            SessionEvent::Custom {
                event_type: "test1".to_string(),
                data: json!({"id": 1}),
            },
            SessionEvent::Custom {
                event_type: "test2".to_string(),
                data: json!({"id": 2}),
            },
        ];

        for event in events {
            let result = manager.send_event_to_session(&session_id, event).await;
            // Results may vary based on receiver availability
            if result.is_err() {
                println!("Event send failed (no active receivers)");
            }
        }

        // Session should still exist
        assert!(manager.session_exists(&session_id).await);
    }

    #[tokio::test]
    async fn test_session_disconnect_event() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        let session_id = manager.create_session().await;
        assert!(manager.session_exists(&session_id).await);

        // Remove session (should trigger disconnect event internally)
        let removed = manager.remove_session(&session_id).await;
        assert!(removed);

        // Verify session no longer exists
        assert!(!manager.session_exists(&session_id).await);

        // Try to send event to removed session (should fail)
        let result = manager
            .send_event_to_session(&session_id, SessionEvent::KeepAlive)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }
}

/// Test error handling and edge cases
#[cfg(test)]
mod notification_error_tests {
    use super::*;

    #[tokio::test]
    async fn test_notification_with_invalid_json() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // These should not panic even with unusual inputs
        context
            .notify_log(
                str_to_logging_level("info"),
                serde_json::json!(""),
                Some("test".to_string()),
                None,
            )
            .await; // Empty strings
        context
            .notify_log(
                str_to_logging_level("invalid_level"),
                serde_json::json!("Test message"),
                Some("test".to_string()),
                None,
            )
            .await;
        context.notify_progress("", 0).await;
        context.notify_resource_updated("").await;

        // Test with very long strings
        let long_string = "x".repeat(10000);
        context
            .notify_log(
                str_to_logging_level("info"),
                serde_json::json!(long_string.clone()),
                Some("test".to_string()),
                None,
            )
            .await;
        context.notify_progress(&long_string, 50).await;
    }

    #[tokio::test]
    async fn test_notification_during_session_expiry() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = manager.create_session_context(&session_id).unwrap();

        // Remove session to simulate expiry
        manager.remove_session(&session_id).await;

        // Attempt to send notifications to expired session
        context
            .notify_log(
                str_to_logging_level("info"),
                serde_json::json!("Message to expired session"),
                Some("test".to_string()),
                None,
            )
            .await;
        context.notify_progress("test", 50).await;

        // These should not panic, even though session may be expired
    }

    #[tokio::test]
    async fn test_concurrent_notification_sending() {
        let capabilities = ServerCapabilities::default();
        let manager = Arc::new(SessionManager::new(capabilities));

        let session_id = manager.create_session().await;
        let context = Arc::new(manager.create_session_context(&session_id).unwrap());

        let num_concurrent = 20;
        let mut handles = Vec::new();

        // Send notifications concurrently
        for i in 0..num_concurrent {
            let context_clone = context.clone();
            let handle = tokio::spawn(async move {
                context_clone
                    .notify_log(
                        str_to_logging_level("info"),
                        serde_json::json!(format!("Concurrent message {}", i)),
                        Some("test".to_string()),
                        None,
                    )
                    .await;
                context_clone.notify_progress("concurrent", i as u64).await;

                let custom_event = SessionEvent::Custom {
                    event_type: "concurrent_test".to_string(),
                    data: json!({"id": i}),
                };
                context_clone.notify(custom_event).await;
            });
            handles.push(handle);
        }

        // Wait for all notifications to complete
        futures::future::join_all(handles).await;

        // Session should still be valid
        assert!(manager.session_exists(&session_id).await);
    }

    #[tokio::test]
    async fn test_notification_channel_capacity_limits() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        let session_id = manager.create_session().await;

        // Send many events rapidly to test channel capacity
        // Default channel capacity is 128, so we'll send more than that
        let num_events = 200;

        for i in 0..num_events {
            let event = SessionEvent::Custom {
                event_type: "capacity_test".to_string(),
                data: json!({"index": i}),
            };

            let result = manager.send_event_to_session(&session_id, event).await;
            // Some may fail if channel is full, which is expected behavior
            if result.is_err() {
                println!("Event {} failed to send (channel may be full)", i);
            }
        }

        // Session should still exist
        assert!(manager.session_exists(&session_id).await);
    }
}

/// Performance tests for notification systems
#[cfg(test)]
mod notification_performance_tests {
    use super::*;
    // Removed AtomicUsize, Ordering imports - no longer needed after removing performance tests

    // test_notification_throughput removed - caused async deadlocks in unit tests
    // Performance tests should be integration tests with separate server/client processes

    #[tokio::test]
    async fn test_broadcast_performance() {
        let capabilities = ServerCapabilities::default();
        let manager = SessionManager::new(capabilities);

        let num_sessions = 50; // Reduced for faster test execution
        let mut session_ids = Vec::new();

        // Create multiple sessions
        for _ in 0..num_sessions {
            let session_id = manager.create_session().await;
            session_ids.push(session_id);
        }

        assert_eq!(manager.session_count().await, num_sessions);

        let num_broadcasts = 10; // Reduced for faster test execution
        let start = std::time::Instant::now();

        // Perform broadcasts
        for i in 0..num_broadcasts {
            let event = SessionEvent::Custom {
                event_type: "broadcast_performance".to_string(),
                data: json!({"broadcast_id": i}),
            };
            manager.broadcast_event(event).await;
        }

        let duration = start.elapsed();

        println!(
            "Completed {} broadcasts to {} sessions in {:?}",
            num_broadcasts, num_sessions, duration
        );

        // All sessions should still exist
        assert_eq!(manager.session_count().await, num_sessions);
    }
}