reasonkit-web 0.1.7

High-performance MCP server for browser automation, web capture, and content extraction. Rust-powered CDP client for AI agents.
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
//! MCP Transport Abstraction
//!
//! This module provides the `McpTransport` trait for pluggable MCP transport
//! backends, enabling flexible deployment options and performance optimization.
//!
//! # Supported Backends
//!
//! - **Stdio**: Standard I/O for CLI tool integration
//! - **SSE**: Server-Sent Events for web clients
//! - **WebSocket**: Bidirectional real-time communication
//! - **HTTP**: REST-style request/response
//!
//! # Performance Optimization
//!
//! The transport layer supports pluggable backends for performance tuning:
//! - Default `rmcp` SDK backend
//! - High-performance `pmcp` backend (feature-gated)
//!
//! # Usage
//!
//! ```rust,ignore
//! use reasonkit_web::mcp::transport::{McpTransport, StdioTransport};
//!
//! let transport = StdioTransport::new();
//! let message = transport.receive().await?;
//! transport.send(&response).await?;
//! ```

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use thiserror::Error;

/// MCP Transport errors
#[derive(Error, Debug)]
pub enum TransportError {
    /// Connection establishment failed
    #[error("Connection failed: {0}")]
    ConnectionFailed(String),

    /// Failed to send message
    #[error("Send failed: {0}")]
    SendFailed(String),

    /// Failed to receive message
    #[error("Receive failed: {0}")]
    ReceiveFailed(String),

    /// Operation timed out
    #[error("Timeout after {0:?}")]
    Timeout(Duration),

    /// Transport connection closed
    #[error("Transport closed")]
    Closed,

    /// Invalid message format error
    #[error("Invalid message format: {0}")]
    InvalidFormat(String),

    /// IO operation error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Serialization/deserialization error
    #[error("Serialization error: {0}")]
    Serialization(String),
}

/// Result type for transport operations
pub type TransportResult<T> = Result<T, TransportError>;

/// Transport configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransportConfig {
    /// Read timeout
    pub read_timeout: Duration,
    /// Write timeout
    pub write_timeout: Duration,
    /// Maximum message size in bytes
    pub max_message_size: usize,
    /// Enable compression
    pub compression: bool,
    /// Buffer size for reading
    pub buffer_size: usize,
}

impl Default for TransportConfig {
    fn default() -> Self {
        Self {
            read_timeout: Duration::from_secs(30),
            write_timeout: Duration::from_secs(30),
            max_message_size: 10 * 1024 * 1024, // 10 MB
            compression: false,
            buffer_size: 8192,
        }
    }
}

/// MCP message envelope
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpMessage {
    /// JSON-RPC version
    pub jsonrpc: String,
    /// Message ID (for request/response correlation)
    pub id: Option<serde_json::Value>,
    /// Method name (for requests)
    pub method: Option<String>,
    /// Parameters (for requests)
    pub params: Option<serde_json::Value>,
    /// Result (for responses)
    pub result: Option<serde_json::Value>,
    /// Error (for error responses)
    pub error: Option<McpError>,
}

impl McpMessage {
    /// Create a new request message
    pub fn request(
        id: impl Into<serde_json::Value>,
        method: &str,
        params: serde_json::Value,
    ) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: Some(id.into()),
            method: Some(method.to_string()),
            params: Some(params),
            result: None,
            error: None,
        }
    }

    /// Create a new response message
    pub fn response(id: impl Into<serde_json::Value>, result: serde_json::Value) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: Some(id.into()),
            method: None,
            params: None,
            result: Some(result),
            error: None,
        }
    }

    /// Create a new error response
    pub fn error_response(id: impl Into<serde_json::Value>, error: McpError) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: Some(id.into()),
            method: None,
            params: None,
            result: None,
            error: Some(error),
        }
    }

    /// Create a notification (no ID)
    pub fn notification(method: &str, params: serde_json::Value) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: None,
            method: Some(method.to_string()),
            params: Some(params),
            result: None,
            error: None,
        }
    }

    /// Check if this is a request
    pub fn is_request(&self) -> bool {
        self.method.is_some() && self.id.is_some()
    }

    /// Check if this is a notification
    pub fn is_notification(&self) -> bool {
        self.method.is_some() && self.id.is_none()
    }

    /// Check if this is a response
    pub fn is_response(&self) -> bool {
        self.id.is_some() && (self.result.is_some() || self.error.is_some())
    }
}

/// MCP error object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpError {
    /// Error code
    pub code: i32,
    /// Error message
    pub message: String,
    /// Additional error data
    pub data: Option<serde_json::Value>,
}

impl McpError {
    /// Parse error (-32700)
    pub fn parse_error(message: impl Into<String>) -> Self {
        Self {
            code: -32700,
            message: message.into(),
            data: None,
        }
    }

    /// Invalid request (-32600)
    pub fn invalid_request(message: impl Into<String>) -> Self {
        Self {
            code: -32600,
            message: message.into(),
            data: None,
        }
    }

    /// Method not found (-32601)
    pub fn method_not_found(method: &str) -> Self {
        Self {
            code: -32601,
            message: format!("Method not found: {}", method),
            data: None,
        }
    }

    /// Invalid params (-32602)
    pub fn invalid_params(message: impl Into<String>) -> Self {
        Self {
            code: -32602,
            message: message.into(),
            data: None,
        }
    }

    /// Internal error (-32603)
    pub fn internal_error(message: impl Into<String>) -> Self {
        Self {
            code: -32603,
            message: message.into(),
            data: None,
        }
    }
}

/// Transport statistics for monitoring
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TransportStats {
    /// Messages sent
    pub messages_sent: u64,
    /// Messages received
    pub messages_received: u64,
    /// Bytes sent
    pub bytes_sent: u64,
    /// Bytes received
    pub bytes_received: u64,
    /// Send errors
    pub send_errors: u64,
    /// Receive errors
    pub receive_errors: u64,
    /// Average send latency in microseconds
    pub avg_send_latency_us: u64,
    /// Average receive latency in microseconds
    pub avg_receive_latency_us: u64,
}

/// MCP Transport trait for pluggable backends
///
/// Implement this trait to create custom MCP transport backends.
#[async_trait]
pub trait McpTransport: Send + Sync {
    /// Get the transport type name
    fn transport_type(&self) -> &'static str;

    /// Connect the transport
    async fn connect(&mut self) -> TransportResult<()>;

    /// Disconnect the transport
    async fn disconnect(&mut self) -> TransportResult<()>;

    /// Check if connected
    fn is_connected(&self) -> bool;

    /// Send a message
    async fn send(&mut self, message: &McpMessage) -> TransportResult<()>;

    /// Receive a message
    async fn receive(&mut self) -> TransportResult<McpMessage>;

    /// Receive with timeout
    async fn receive_timeout(&mut self, timeout: Duration) -> TransportResult<McpMessage>;

    /// Get transport statistics
    fn stats(&self) -> TransportStats;

    /// Reset statistics
    fn reset_stats(&mut self);
}

/// Transport type enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransportType {
    /// Standard I/O
    Stdio,
    /// Server-Sent Events
    Sse,
    /// WebSocket
    WebSocket,
    /// HTTP
    Http,
}

impl std::fmt::Display for TransportType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Stdio => write!(f, "stdio"),
            Self::Sse => write!(f, "sse"),
            Self::WebSocket => write!(f, "websocket"),
            Self::Http => write!(f, "http"),
        }
    }
}

/// Standard I/O transport implementation
pub struct StdioTransport {
    #[allow(dead_code)]
    config: TransportConfig,
    connected: bool,
    stats: TransportStats,
}

impl StdioTransport {
    /// Create a new stdio transport
    pub fn new() -> Self {
        Self::with_config(TransportConfig::default())
    }

    /// Create with configuration
    pub fn with_config(config: TransportConfig) -> Self {
        Self {
            config,
            connected: false,
            stats: TransportStats::default(),
        }
    }
}

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

#[async_trait]
impl McpTransport for StdioTransport {
    fn transport_type(&self) -> &'static str {
        "stdio"
    }

    async fn connect(&mut self) -> TransportResult<()> {
        self.connected = true;
        Ok(())
    }

    async fn disconnect(&mut self) -> TransportResult<()> {
        self.connected = false;
        Ok(())
    }

    fn is_connected(&self) -> bool {
        self.connected
    }

    async fn send(&mut self, message: &McpMessage) -> TransportResult<()> {
        let json = serde_json::to_string(message)
            .map_err(|e| TransportError::Serialization(e.to_string()))?;

        // Write to stdout with Content-Length header (LSP style)
        let content = format!("Content-Length: {}\r\n\r\n{}", json.len(), json);

        use std::io::Write;
        let mut stdout = std::io::stdout().lock();
        stdout
            .write_all(content.as_bytes())
            .map_err(TransportError::Io)?;
        stdout.flush().map_err(TransportError::Io)?;

        self.stats.messages_sent += 1;
        self.stats.bytes_sent += content.len() as u64;

        Ok(())
    }

    async fn receive(&mut self) -> TransportResult<McpMessage> {
        use std::io::{BufRead, Read};

        let stdin = std::io::stdin();
        let mut reader = stdin.lock();

        // Read Content-Length header
        let mut header_line = String::new();
        reader
            .read_line(&mut header_line)
            .map_err(TransportError::Io)?;

        let content_length: usize = header_line
            .trim()
            .strip_prefix("Content-Length: ")
            .ok_or_else(|| TransportError::InvalidFormat("Missing Content-Length header".into()))?
            .parse()
            .map_err(|_| TransportError::InvalidFormat("Invalid Content-Length".into()))?;

        // Skip empty line
        let mut empty = String::new();
        reader.read_line(&mut empty).map_err(TransportError::Io)?;

        // Read content
        let mut content = vec![0u8; content_length];
        reader
            .read_exact(&mut content)
            .map_err(TransportError::Io)?;

        let message: McpMessage = serde_json::from_slice(&content)
            .map_err(|e| TransportError::InvalidFormat(e.to_string()))?;

        self.stats.messages_received += 1;
        self.stats.bytes_received += content_length as u64;

        Ok(message)
    }

    async fn receive_timeout(&mut self, _timeout: Duration) -> TransportResult<McpMessage> {
        // For stdio, timeout handling would require threading
        // This is a simplified implementation
        self.receive().await
    }

    fn stats(&self) -> TransportStats {
        self.stats.clone()
    }

    fn reset_stats(&mut self) {
        self.stats = TransportStats::default();
    }
}

/// Transport factory for creating transport instances
pub struct TransportFactory;

impl TransportFactory {
    /// Create a transport of the specified type
    pub fn create(transport_type: TransportType) -> Box<dyn McpTransport> {
        match transport_type {
            TransportType::Stdio => Box::new(StdioTransport::new()),
            // Other transports would be implemented similarly
            TransportType::Sse | TransportType::WebSocket | TransportType::Http => {
                // Placeholder - would need full implementations
                Box::new(StdioTransport::new())
            }
        }
    }

    /// Create a transport with configuration
    pub fn create_with_config(
        transport_type: TransportType,
        config: TransportConfig,
    ) -> Box<dyn McpTransport> {
        match transport_type {
            TransportType::Stdio => Box::new(StdioTransport::with_config(config)),
            _ => Box::new(StdioTransport::with_config(config)),
        }
    }
}

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

    #[test]
    fn test_message_request() {
        let msg = McpMessage::request(1, "tools/list", serde_json::json!({}));
        assert!(msg.is_request());
        assert!(!msg.is_notification());
        assert!(!msg.is_response());
    }

    #[test]
    fn test_message_notification() {
        let msg = McpMessage::notification("progress", serde_json::json!({ "percent": 50 }));
        assert!(!msg.is_request());
        assert!(msg.is_notification());
        assert!(!msg.is_response());
    }

    #[test]
    fn test_message_response() {
        let msg = McpMessage::response(1, serde_json::json!({ "tools": [] }));
        assert!(!msg.is_request());
        assert!(!msg.is_notification());
        assert!(msg.is_response());
    }

    #[test]
    fn test_error_codes() {
        let err = McpError::method_not_found("unknown");
        assert_eq!(err.code, -32601);

        let err = McpError::invalid_params("bad param");
        assert_eq!(err.code, -32602);
    }

    #[test]
    fn test_transport_config_default() {
        let config = TransportConfig::default();
        assert_eq!(config.read_timeout, Duration::from_secs(30));
        assert!(!config.compression);
    }
}