pulseengine-mcp-server 0.17.1

[DEPRECATED] Use rmcp instead. MCP server framework.
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! Tests for MCP server implementation

use crate::backend::{BackendError, McpBackend};
use crate::observability::MonitoringConfig;
use crate::server::{HealthStatus, McpServer, ServerConfig, ServerError};
use async_trait::async_trait;
use pulseengine_auth::{AuthConfig, config::StorageConfig};
use pulseengine_mcp_protocol::*;
use pulseengine_mcp_security::SecurityConfig;
use pulseengine_mcp_transport::TransportConfig;
use std::error::Error as StdError;
use std::fmt;
use std::time::Duration;
use tokio::time::timeout;

// Mock backend for server testing
#[derive(Clone)]
struct MockServerBackend {
    should_fail_health: bool,
    should_fail_startup: bool,
    should_fail_shutdown: bool,
    server_name: String,
}

#[derive(Debug)]
struct MockServerError(String);

impl fmt::Display for MockServerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Mock server error: {}", self.0)
    }
}

impl StdError for MockServerError {}

impl From<BackendError> for MockServerError {
    fn from(err: BackendError) -> Self {
        MockServerError(err.to_string())
    }
}

impl From<MockServerError> for Error {
    fn from(err: MockServerError) -> Self {
        Error::internal_error(err.to_string())
    }
}

#[async_trait]
impl McpBackend for MockServerBackend {
    type Error = MockServerError;
    type Config = (bool, bool, bool, String);

    async fn initialize(
        (should_fail_health, should_fail_startup, should_fail_shutdown, server_name): Self::Config,
    ) -> std::result::Result<Self, Self::Error> {
        Ok(Self {
            should_fail_health,
            should_fail_startup,
            should_fail_shutdown,
            server_name,
        })
    }

    fn get_server_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::default(),
            capabilities: ServerCapabilities::default(),
            server_info: Implementation::new(self.server_name.clone(), "1.0.0"),
            instructions: Some("Mock server backend for testing".to_string()),
        }
    }

    async fn health_check(&self) -> std::result::Result<(), Self::Error> {
        if self.should_fail_health {
            Err(MockServerError("Backend health check failed".to_string()))
        } else {
            Ok(())
        }
    }

    async fn on_startup(&self) -> std::result::Result<(), Self::Error> {
        if self.should_fail_startup {
            Err(MockServerError("Backend startup failed".to_string()))
        } else {
            Ok(())
        }
    }

    async fn on_shutdown(&self) -> std::result::Result<(), Self::Error> {
        if self.should_fail_shutdown {
            Err(MockServerError("Backend shutdown failed".to_string()))
        } else {
            Ok(())
        }
    }

    async fn list_tools(
        &self,
        _request: PaginatedRequestParam,
    ) -> std::result::Result<ListToolsResult, Self::Error> {
        Ok(ListToolsResult {
            tools: vec![],
            next_cursor: None,
        })
    }

    async fn call_tool(
        &self,
        _request: CallToolRequestParam,
    ) -> std::result::Result<CallToolResult, Self::Error> {
        Ok(CallToolResult {
            content: vec![],
            is_error: Some(false),
            structured_content: None,
            _meta: None,
        })
    }

    async fn list_resources(
        &self,
        _request: PaginatedRequestParam,
    ) -> std::result::Result<ListResourcesResult, Self::Error> {
        Ok(ListResourcesResult {
            resources: vec![],
            next_cursor: None,
        })
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParam,
    ) -> std::result::Result<ReadResourceResult, Self::Error> {
        Err(BackendError::not_supported(format!("Resource not found: {}", request.uri)).into())
    }

    async fn list_prompts(
        &self,
        _request: PaginatedRequestParam,
    ) -> std::result::Result<ListPromptsResult, Self::Error> {
        Ok(ListPromptsResult {
            prompts: vec![],
            next_cursor: None,
        })
    }

    async fn get_prompt(
        &self,
        request: GetPromptRequestParam,
    ) -> std::result::Result<GetPromptResult, Self::Error> {
        Err(BackendError::not_supported(format!("Prompt not found: {}", request.name)).into())
    }
}

#[test]
fn test_server_error_types() {
    let config_err = ServerError::Configuration("Config failed".to_string());
    assert!(
        config_err
            .to_string()
            .contains("Server configuration error: Config failed")
    );

    let transport_err = ServerError::Transport("Transport failed".to_string());
    assert!(
        transport_err
            .to_string()
            .contains("Transport error: Transport failed")
    );

    let auth_err = ServerError::Authentication("Auth failed".to_string());
    assert!(
        auth_err
            .to_string()
            .contains("Authentication error: Auth failed")
    );

    let backend_err = ServerError::Backend("Backend failed".to_string());
    assert!(
        backend_err
            .to_string()
            .contains("Backend error: Backend failed")
    );

    assert!(
        ServerError::AlreadyRunning
            .to_string()
            .contains("Server already running")
    );
    assert!(
        ServerError::NotRunning
            .to_string()
            .contains("Server not running")
    );
    assert!(
        ServerError::ShutdownTimeout
            .to_string()
            .contains("Shutdown timeout")
    );
}

#[test]
fn test_server_config_default() {
    let config = ServerConfig::default();

    assert_eq!(config.server_info.server_info.name, "MCP Server");
    assert_eq!(config.server_info.server_info.version, "1.0.0");
    assert!(config.graceful_shutdown);
    assert_eq!(config.shutdown_timeout_secs, 30);
}

#[test]
fn test_server_config_custom() {
    let mut config = ServerConfig::default();
    config.server_info.server_info.name = "Custom Server".to_string();
    config.graceful_shutdown = false;
    config.shutdown_timeout_secs = 60;

    assert_eq!(config.server_info.server_info.name, "Custom Server");
    assert!(!config.graceful_shutdown);
    assert_eq!(config.shutdown_timeout_secs, 60);
}

#[tokio::test]
async fn test_server_creation() {
    let backend = MockServerBackend::initialize((false, false, false, "Test Server".to_string()))
        .await
        .unwrap();
    let config = ServerConfig {
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    if let Err(e) = &server {
        println!("Server creation failed: {e:?}");
    }
    assert!(server.is_ok());

    let server = server.unwrap();
    assert_eq!(server.get_server_info().server_info.name, "MCP Server"); // Uses config, not backend
    assert!(!server.is_running().await);
}

#[tokio::test]
async fn test_server_creation_with_custom_config() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Backend Server".to_string()))
            .await
            .unwrap();

    let mut config = ServerConfig::default();
    config.server_info.server_info.name = "Custom Server".to_string();
    config.server_info.server_info.version = "2.0.0".to_string();
    config.auth_config = AuthConfig {
        storage: StorageConfig::Memory,
        enabled: false,
        cache_size: 100,
        session_timeout_secs: 3600,
        max_failed_attempts: 5,
        rate_limit_window_secs: 900,
    };

    let server = McpServer::new(backend, config).await.unwrap();

    let server_info = server.get_server_info();
    assert_eq!(server_info.server_info.name, "Custom Server");
    assert_eq!(server_info.server_info.version, "2.0.0");
}

#[tokio::test]
async fn test_server_health_check() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Healthy Server".to_string()))
            .await
            .unwrap();
    let config = ServerConfig {
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await.unwrap();

    let health = server.health_check().await.unwrap();
    // Transport health check may fail for stdio - that's expected
    // As long as we get a health response with all components, that's good
    assert!(health.components.contains_key("backend"));
    assert!(health.components.contains_key("transport"));
    assert!(health.components.contains_key("auth"));

    // Backend should be healthy since we created it with should_fail=false
    assert_eq!(health.components.get("backend"), Some(&true));

    // Auth should be healthy since it's disabled
    assert_eq!(health.components.get("auth"), Some(&true));
}

#[tokio::test]
async fn test_server_health_check_unhealthy_backend() {
    let backend =
        MockServerBackend::initialize((true, false, false, "Unhealthy Server".to_string()))
            .await
            .unwrap();
    let config = ServerConfig {
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await.unwrap();

    let health = server.health_check().await.unwrap();
    assert_eq!(health.status, "unhealthy");
    assert_eq!(health.components.get("backend"), Some(&false));
}

#[tokio::test]
async fn test_server_get_metrics() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Metrics Server".to_string()))
            .await
            .unwrap();
    let config = ServerConfig {
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await.unwrap();

    let metrics = server.get_metrics().await;
    // Just verify we can get metrics without error
    // Just verify we can get metrics without error (remove redundant comparison)
    let _ = metrics.requests_total;
}

#[tokio::test]
async fn test_server_start_stop() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Start Stop Server".to_string()))
            .await
            .unwrap();
    // Use stdio transport to avoid port conflicts
    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        graceful_shutdown: false, // Disable signal handling for test
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let mut server = McpServer::new(backend, config).await.unwrap();

    // Server should not be running initially
    assert!(!server.is_running().await);

    // Start the server
    let start_result = server.start().await;
    assert!(start_result.is_ok());
    assert!(server.is_running().await);

    // Try to start again - should fail
    let start_again_result = server.start().await;
    assert!(start_again_result.is_err());
    assert!(matches!(
        start_again_result.unwrap_err(),
        ServerError::AlreadyRunning
    ));

    // Stop the server
    let stop_result = server.stop().await;
    assert!(stop_result.is_ok());
    assert!(!server.is_running().await);

    // Try to stop again - should fail
    let stop_again_result = server.stop().await;
    assert!(stop_again_result.is_err());
    assert!(matches!(
        stop_again_result.unwrap_err(),
        ServerError::NotRunning
    ));
}

#[tokio::test]
async fn test_server_startup_failure() {
    let backend =
        MockServerBackend::initialize((false, true, false, "Startup Fail Server".to_string()))
            .await
            .unwrap();
    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let mut server = McpServer::new(backend, config).await.unwrap();

    let start_result = server.start().await;
    assert!(start_result.is_err());
    assert!(matches!(start_result.unwrap_err(), ServerError::Backend(_)));
}

#[tokio::test]
async fn test_server_run_with_timeout() {
    let backend = MockServerBackend::initialize((false, false, false, "Run Server".to_string()))
        .await
        .unwrap();
    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        graceful_shutdown: false,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let mut server = McpServer::new(backend, config).await.unwrap();

    // Run the server with a timeout
    let run_result = timeout(Duration::from_millis(100), server.run()).await;

    // Should timeout since the server runs indefinitely
    assert!(run_result.is_err());
}

#[tokio::test]
async fn test_server_with_different_transports() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Transport Server".to_string()))
            .await
            .unwrap();

    // Test with Stdio transport
    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend.clone(), config).await;
    assert!(server.is_ok());

    // Test with HTTP transport (should work with default port)
    let config = ServerConfig {
        transport_config: TransportConfig::Http {
            host: Some("127.0.0.1".to_string()),
            port: 0, // Use random port
        },
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}

#[tokio::test]
async fn test_server_with_auth_config() {
    let backend = MockServerBackend::initialize((false, false, false, "Auth Server".to_string()))
        .await
        .unwrap();

    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false, // Keep disabled for tests
            cache_size: 1000,
            session_timeout_secs: 3600, // 60 minutes
            max_failed_attempts: 5,
            rate_limit_window_secs: 60,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}

#[tokio::test]
async fn test_server_with_security_config() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Security Server".to_string()))
            .await
            .unwrap();

    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        security_config: SecurityConfig {
            validate_requests: true,
            rate_limiting: true,
            max_requests_per_minute: 100,
            cors_enabled: true,
            cors_origins: vec!["http://localhost:3000".to_string()],
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}

#[tokio::test]
async fn test_server_with_monitoring_config() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Monitoring Server".to_string()))
            .await
            .unwrap();

    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        monitoring_config: MonitoringConfig {
            enabled: true,
            collection_interval_secs: 10,
            performance_monitoring: true,
            health_checks: true,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}

#[test]
fn test_health_status_serialization() {
    use std::collections::HashMap;

    let mut components = HashMap::new();
    components.insert("backend".to_string(), true);
    components.insert("transport".to_string(), false);

    let health = HealthStatus {
        status: "degraded".to_string(),
        components,
        uptime_seconds: 3600,
    };

    let serialized = serde_json::to_string(&health).unwrap();
    assert!(serialized.contains("degraded"));
    assert!(serialized.contains("backend"));
    assert!(serialized.contains("3600"));

    let deserialized: HealthStatus = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized.status, "degraded");
    assert_eq!(deserialized.uptime_seconds, 3600);
    assert_eq!(deserialized.components.len(), 2);
}

#[test]
fn test_server_config_debug() {
    let config = ServerConfig::default();
    let debug_str = format!("{config:?}");
    assert!(debug_str.contains("ServerConfig"));
    assert!(debug_str.contains("MCP Server"));
}

#[test]
fn test_server_config_clone() {
    let config = ServerConfig::default();
    let cloned = config.clone();

    assert_eq!(
        config.server_info.server_info.name,
        cloned.server_info.server_info.name
    );
    assert_eq!(config.graceful_shutdown, cloned.graceful_shutdown);
    assert_eq!(config.shutdown_timeout_secs, cloned.shutdown_timeout_secs);
}

// Test thread safety
#[test]
fn test_server_types_send_sync() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    assert_send::<ServerError>();
    assert_sync::<ServerError>();
    assert_send::<ServerConfig>();
    assert_sync::<ServerConfig>();
    assert_send::<HealthStatus>();
    assert_sync::<HealthStatus>();
}

#[test]
fn test_server_error_debug() {
    let err = ServerError::Backend("test".to_string());
    let debug_str = format!("{err:?}");
    assert!(debug_str.contains("Backend"));
    assert!(debug_str.contains("test"));
}

// ============================================================================
// Additional Server Error Tests
// ============================================================================

#[test]
fn test_server_error_all_variants() {
    // Test each variant for coverage
    let errors = vec![
        ServerError::Configuration("config error".to_string()),
        ServerError::Transport("transport error".to_string()),
        ServerError::Authentication("auth error".to_string()),
        ServerError::Backend("backend error".to_string()),
        ServerError::AlreadyRunning,
        ServerError::NotRunning,
        ServerError::ShutdownTimeout,
    ];

    for error in errors {
        // All should implement Display
        let display = error.to_string();
        assert!(!display.is_empty());

        // All should implement Debug
        let debug = format!("{error:?}");
        assert!(!debug.is_empty());
    }
}

#[test]
fn test_server_error_std_error_trait() {
    // Verify ServerError implements std::error::Error
    let error: Box<dyn std::error::Error> =
        Box::new(ServerError::Configuration("test".to_string()));
    assert!(error.to_string().contains("Server configuration error"));
}

// ============================================================================
// Transport Configuration Tests
// ============================================================================

#[tokio::test]
async fn test_server_with_websocket_transport() {
    let backend =
        MockServerBackend::initialize((false, false, false, "WebSocket Server".to_string()))
            .await
            .unwrap();

    // Test with WebSocket transport
    let config = ServerConfig {
        transport_config: TransportConfig::WebSocket {
            host: Some("127.0.0.1".to_string()),
            port: 0, // Random port
        },
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}

#[tokio::test]
async fn test_server_with_streamable_http_transport() {
    let backend =
        MockServerBackend::initialize((false, false, false, "StreamableHTTP Server".to_string()))
            .await
            .unwrap();

    // Test with StreamableHttp transport
    let config = ServerConfig {
        transport_config: TransportConfig::StreamableHttp {
            host: Some("127.0.0.1".to_string()),
            port: 0, // Random port
        },
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}

// ============================================================================
// Config Edge Cases
// ============================================================================

#[tokio::test]
async fn test_server_with_profiling_enabled() {
    use pulseengine_logging::ProfilingConfig;

    let backend =
        MockServerBackend::initialize((false, false, false, "Profiling Server".to_string()))
            .await
            .unwrap();

    // Use a profiling config with enabled = true
    let profiling_config = ProfilingConfig {
        enabled: true,
        ..Default::default()
    };

    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        profiling_config,
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}

#[tokio::test]
async fn test_server_with_persistence_config() {
    use pulseengine_logging::PersistenceConfig;

    let backend =
        MockServerBackend::initialize((false, false, false, "Persistence Server".to_string()))
            .await
            .unwrap();

    let temp_dir = std::env::temp_dir().join("mcp_test_metrics");

    // Use default PersistenceConfig with modified data_dir
    let persistence = PersistenceConfig {
        data_dir: temp_dir.clone(),
        ..Default::default()
    };

    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: false,
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        persistence_config: Some(persistence),
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    // May fail if temp dir can't be created, but should not crash
    let _ = server;

    // Cleanup
    let _ = std::fs::remove_dir_all(temp_dir);
}

#[tokio::test]
async fn test_server_with_auth_enabled() {
    let backend =
        MockServerBackend::initialize((false, false, false, "Auth Enabled Server".to_string()))
            .await
            .unwrap();

    let config = ServerConfig {
        transport_config: TransportConfig::Stdio,
        auth_config: AuthConfig {
            storage: StorageConfig::Memory,
            enabled: true, // Enable auth
            cache_size: 100,
            session_timeout_secs: 3600,
            max_failed_attempts: 5,
            rate_limit_window_secs: 900,
        },
        ..Default::default()
    };

    let server = McpServer::new(backend, config).await;
    assert!(server.is_ok());
}