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
//! Tests for the main server library

use crate::*;
use async_trait::async_trait;
use pulseengine_auth::config::StorageConfig;
use pulseengine_mcp_protocol::error::ErrorCode;
use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;

// Test re-exports and main library functionality
#[test]
fn test_main_exports() {
    // Test that all main types are accessible
    let _: Option<BackendError> = None;
    let _: Option<RequestContext> = None;
    let _: Option<HandlerError> = None;
    let _: Option<MiddlewareStack> = None;
    let _: Option<ServerError> = None;
    let _: Option<ServerConfig> = None;
}

#[test]
fn test_protocol_re_exports() {
    // Test that protocol types are re-exported
    let _: Option<Request> = None;
    let _: Option<Response> = None;
    let _: Option<Error> = None;
    let _: Option<ServerInfo> = None;
    let _: Option<Implementation> = None;
}

#[test]
fn test_auth_re_exports() {
    // Test that auth types are re-exported
    let _: Option<AuthConfig> = None;
    let _: Option<AuthenticationManager> = None;
}

#[test]
fn test_transport_re_exports() {
    // Test that transport types are re-exported
    let _: Option<TransportConfig> = None;
}

#[test]
fn test_security_re_exports() {
    // Test that security types are re-exported
    let _: Option<SecurityConfig> = None;
    let _: Option<SecurityMiddleware> = None;
}

#[test]
fn test_monitoring_re_exports() {
    // Test that monitoring types are re-exported
    let _: Option<MetricsCollector> = None;
    let _: Option<MonitoringConfig> = None;
}

// Simple integration test with a minimal backend
#[derive(Clone)]
struct IntegrationTestBackend;

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

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

impl StdError for IntegrationError {}

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

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

#[async_trait]
impl McpBackend for IntegrationTestBackend {
    type Error = IntegrationError;
    type Config = ();

    async fn initialize(_config: Self::Config) -> std::result::Result<Self, Self::Error> {
        Ok(IntegrationTestBackend)
    }

    fn get_server_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::default(),
            capabilities: ServerCapabilities::default(),
            server_info: Implementation::new("Integration Test Backend", "1.0.0"),
            instructions: Some("Backend for integration testing".to_string()),
        }
    }

    async fn health_check(&self) -> std::result::Result<(), Self::Error> {
        Ok(())
    }

    async fn list_tools(
        &self,
        _request: PaginatedRequestParam,
    ) -> std::result::Result<ListToolsResult, Self::Error> {
        Ok(ListToolsResult {
            tools: vec![Tool {
                name: "integration_tool".to_string(),
                description: "A tool for integration testing".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "input": {"type": "string"}
                    },
                    "required": ["input"]
                }),
                output_schema: None,
                title: None,
                annotations: None,
                icons: None,
                execution: None,
                _meta: None,
            }],
            next_cursor: None,
        })
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParam,
    ) -> std::result::Result<CallToolResult, Self::Error> {
        if request.name == "integration_tool" {
            let args = request.arguments.unwrap_or_default();
            let input = args
                .get("input")
                .and_then(|v| v.as_str())
                .unwrap_or("no input");

            Ok(CallToolResult {
                content: vec![Content::Text {
                    text: format!("Processed: {input}"),
                    _meta: None,
                }],
                is_error: Some(false),
                structured_content: None,
                _meta: None,
            })
        } else {
            Err(BackendError::not_supported(format!("Tool not found: {}", request.name)).into())
        }
    }

    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())
    }
}

#[tokio::test]
async fn test_integration_backend_creation() {
    let backend = IntegrationTestBackend::initialize(()).await.unwrap();
    let server_info = backend.get_server_info();

    assert_eq!(server_info.server_info.name, "Integration Test Backend");
    assert_eq!(server_info.server_info.version, "1.0.0");
}

#[tokio::test]
async fn test_integration_server_creation() {
    let backend = IntegrationTestBackend::initialize(()).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 server = McpServer::new(backend, config).await;
    assert!(server.is_ok());

    let server = server.unwrap();
    assert!(!server.is_running().await);

    let health = server.health_check().await.unwrap();
    assert!(!health.status.is_empty());
}

#[tokio::test]
async fn test_integration_handler_flow() {
    let backend = IntegrationTestBackend::initialize(()).await.unwrap();
    let 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 auth_manager = std::sync::Arc::new(AuthenticationManager::new(auth_config).await.unwrap());
    let middleware = MiddlewareStack::new();

    let handler = GenericServerHandler::new(std::sync::Arc::new(backend), auth_manager, middleware);

    // Test initialize request
    let init_request = Request {
        jsonrpc: "2.0".to_string(),
        id: Some(pulseengine_mcp_protocol::NumberOrString::String(Arc::from(
            "init",
        ))),
        method: "initialize".to_string(),
        params: serde_json::json!({
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {
                "name": "Test Client",
                "version": "1.0.0"
            }
        }),
    };

    let response = handler.handle_request(init_request).await.unwrap();
    assert!(response.error.is_none());
    assert!(response.result.is_some());

    // Test list tools
    let tools_request = Request {
        jsonrpc: "2.0".to_string(),
        id: Some(pulseengine_mcp_protocol::NumberOrString::String(Arc::from(
            "tools",
        ))),
        method: "tools/list".to_string(),
        params: serde_json::json!({"cursor": null}),
    };

    let response = handler.handle_request(tools_request).await.unwrap();
    assert!(response.error.is_none());
    assert!(response.result.is_some());

    let tools_result: ListToolsResult = serde_json::from_value(response.result.unwrap()).unwrap();
    assert_eq!(tools_result.tools.len(), 1);
    assert_eq!(tools_result.tools[0].name, "integration_tool");

    // Test call tool
    let call_request = Request {
        jsonrpc: "2.0".to_string(),
        id: Some(pulseengine_mcp_protocol::NumberOrString::String(Arc::from(
            "call",
        ))),
        method: "tools/call".to_string(),
        params: serde_json::json!({
            "name": "integration_tool",
            "arguments": {
                "input": "test_input"
            }
        }),
    };

    let response = handler.handle_request(call_request).await.unwrap();
    assert!(response.error.is_none());
    assert!(response.result.is_some());

    let call_result: CallToolResult = serde_json::from_value(response.result.unwrap()).unwrap();
    assert_eq!(call_result.is_error, Some(false));
    match &call_result.content[0] {
        Content::Text { text, .. } => assert!(text.contains("test_input")),
        _ => panic!("Expected text content"),
    }
}

#[tokio::test]
async fn test_integration_context_flow() {
    let context = RequestContext::new()
        .with_user("integration_user")
        .with_role("tester")
        .with_metadata("test_run", "integration");

    assert!(context.is_authenticated());
    assert!(context.has_role("tester"));
    assert_eq!(
        context.get_metadata("test_run"),
        Some(&"integration".to_string())
    );
}

#[tokio::test]
async fn test_integration_middleware_flow() {
    let 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 auth_manager = std::sync::Arc::new(AuthenticationManager::new(auth_config).await.unwrap());
    let monitoring = std::sync::Arc::new(MetricsCollector::new(MonitoringConfig::default()));
    let security = SecurityMiddleware::new(SecurityConfig::default());

    let middleware = MiddlewareStack::new()
        .with_auth(auth_manager)
        .with_monitoring(monitoring)
        .with_security(security);

    let context = RequestContext::new().with_user("middleware_user");

    let request = Request {
        jsonrpc: "2.0".to_string(),
        id: Some(pulseengine_mcp_protocol::NumberOrString::String(Arc::from(
            "middleware_test",
        ))),
        method: "ping".to_string(),
        params: serde_json::Value::Null,
    };

    let processed_request = middleware.process_request(request, &context).await.unwrap();
    assert_eq!(processed_request.method, "ping");

    let response = Response {
        jsonrpc: "2.0".to_string(),
        id: Some(pulseengine_mcp_protocol::NumberOrString::String(Arc::from(
            "middleware_test",
        ))),
        result: Some(serde_json::Value::Null),
        error: None,
    };

    let processed_response = middleware
        .process_response(response, &context)
        .await
        .unwrap();
    assert!(processed_response.result.is_some());
}

#[test]
fn test_library_version_consistency() {
    // Test that the library maintains version consistency
    let server_info = ServerInfo {
        protocol_version: ProtocolVersion::default(),
        capabilities: ServerCapabilities::default(),
        server_info: Implementation::new("Test", env!("CARGO_PKG_VERSION")),
        instructions: None,
    };

    assert!(!server_info.server_info.version.is_empty());
    assert!(server_info.server_info.version.contains('.'));
}

#[test]
fn test_error_conversion_chain() {
    // Test error conversion from backend to protocol
    let backend_err = BackendError::configuration("test config error");
    let protocol_err: Error = backend_err.into();
    assert_eq!(protocol_err.code, ErrorCode::InvalidParams);

    let handler_err = HandlerError::Backend("test backend error".to_string());
    let protocol_err: Error = handler_err.into();
    assert_eq!(protocol_err.code, ErrorCode::InternalError);
}

// Test thread safety of main library types
#[test]
fn test_library_types_send_sync() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    // Test core types
    assert_send::<BackendError>();
    assert_sync::<BackendError>();
    assert_send::<RequestContext>();
    assert_sync::<RequestContext>();
    assert_send::<HandlerError>();
    assert_sync::<HandlerError>();
    assert_send::<MiddlewareStack>();
    assert_sync::<MiddlewareStack>();
    assert_send::<ServerError>();
    assert_sync::<ServerError>();
    assert_send::<ServerConfig>();
    assert_sync::<ServerConfig>();

    // Test integration backend
    assert_send::<IntegrationTestBackend>();
    assert_sync::<IntegrationTestBackend>();
}

#[test]
fn test_namespace_organization() {
    // Test that different modules don't conflict

    // backend module
    let _backend_error = crate::backend::BackendError::internal("test");

    // context module
    let _context = crate::context::RequestContext::new();

    // handler module
    let _handler_error = crate::handler::HandlerError::Backend("test".to_string());

    // middleware module
    let _middleware = crate::middleware::MiddlewareStack::new();

    // server module
    let _server_error = crate::server::ServerError::Configuration("test".to_string());
    let _server_config = crate::server::ServerConfig::default();
}

#[test]
fn test_feature_flags() {
    // Test that the library compiles with default features
    // This is more of a compilation test

    let _config = ServerConfig::default();
    // If we reach here, compilation succeeded
}

#[test]
fn test_documentation_examples() {
    // Test that the examples in the documentation would compile
    // (This is a simplified version of what's in the lib.rs docs)

    #[derive(Clone)]
    struct DocExampleBackend;

    #[derive(Debug)]
    struct DocExampleError;

    impl fmt::Display for DocExampleError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "Doc example error")
        }
    }

    impl StdError for DocExampleError {}

    impl From<BackendError> for DocExampleError {
        fn from(_: BackendError) -> Self {
            DocExampleError
        }
    }

    impl From<DocExampleError> for Error {
        fn from(_: DocExampleError) -> Self {
            Error::internal_error("Doc example error")
        }
    }

    // This would normally have the full McpBackend implementation
    // but for the test we just verify the types compile
    let _backend = DocExampleBackend;
    let _config = ServerConfig::default();

    // Tests pass if they compile
}