pulseengine_mcp_transport/
lib.rs

1//! Transport layer implementations for MCP servers
2//!
3//! This crate provides multiple transport options for MCP servers:
4//! stdio (Claude Desktop), HTTP (web clients), and WebSocket (real-time).
5//!
6//! # Quick Start
7//!
8//! ```rust,no_run
9//! use mcp_transport::{TransportConfig, create_transport};
10//! use pulseengine_mcp_protocol::{Request, Response};
11//!
12//! // Create HTTP transport
13//! let config = TransportConfig::Http { port: 3001 };
14//! let mut transport = create_transport(config).unwrap();
15//!
16//! // Define request handler
17//! let handler = Box::new(|request: Request| {
18//!     Box::pin(async move {
19//!         Response::success(serde_json::json!({"result": "handled"}))
20//!     })
21//! });
22//!
23//! // Start transport (in real code)
24//! // transport.start(handler).await.unwrap();
25//! ```
26
27pub mod batch;
28pub mod config;
29pub mod http;
30pub mod stdio;
31pub mod streamable_http;
32pub mod validation;
33pub mod websocket;
34
35#[cfg(test)]
36mod http_test;
37
38use async_trait::async_trait;
39use pulseengine_mcp_protocol::{Request, Response};
40// std::error::Error not needed with thiserror
41use thiserror::Error as ThisError;
42
43pub use config::TransportConfig;
44
45#[derive(Debug, ThisError)]
46pub enum TransportError {
47    #[error("Transport configuration error: {0}")]
48    Config(String),
49
50    #[error("Connection error: {0}")]
51    Connection(String),
52
53    #[error("Protocol error: {0}")]
54    Protocol(String),
55}
56
57/// Request handler function type
58pub type RequestHandler = Box<
59    dyn Fn(Request) -> std::pin::Pin<Box<dyn std::future::Future<Output = Response> + Send>>
60        + Send
61        + Sync,
62>;
63
64/// Transport layer trait
65#[async_trait]
66pub trait Transport: Send + Sync {
67    async fn start(&mut self, handler: RequestHandler) -> std::result::Result<(), TransportError>;
68    async fn stop(&mut self) -> std::result::Result<(), TransportError>;
69    async fn health_check(&self) -> std::result::Result<(), TransportError>;
70}
71
72/// Create a transport from configuration
73pub fn create_transport(
74    config: TransportConfig,
75) -> std::result::Result<Box<dyn Transport>, TransportError> {
76    match config {
77        TransportConfig::Stdio => Ok(Box::new(stdio::StdioTransport::new())),
78        TransportConfig::Http { port, .. } => Ok(Box::new(http::HttpTransport::new(port))),
79        TransportConfig::WebSocket { port, .. } => {
80            Ok(Box::new(websocket::WebSocketTransport::new(port)))
81        }
82    }
83}