fastmcp 0.0.0

A Rust framework for building Model Context Protocol (MCP) services
Documentation
use std::fmt::Debug;
use std::sync::Arc;

use async_trait::async_trait;
use tokio::sync::mpsc;

use crate::error::Result;
use crate::protocol::{ErrorMessage, Notification, Request, Response};

mod stdio;
pub use stdio::StdioTransport;

// 添加HTTP和WebSocket模块
#[cfg(feature = "http")]
pub mod http;
#[cfg(feature = "http")]
pub use http::HttpTransport;

#[cfg(feature = "websocket")]
pub mod websocket;
#[cfg(feature = "websocket")]
pub use websocket::WebSocketTransport;

/// Transport trait for MCP servers
#[async_trait]
pub trait Transport: Send + Sync + Debug {
    /// Start the transport
    async fn start(&self) -> Result<()>;

    /// Set the request handler
    fn set_request_handler(&mut self, handler: RequestHandler);
}

/// Transport configuration
#[derive(Debug, Clone)]
pub enum TransportConfig {
    /// Standard input/output transport
    Stdio,

    /// HTTP transport with specified host and port
    #[cfg(feature = "http")]
    Http { host: String, port: u16 },

    /// WebSocket transport with specified host and port
    #[cfg(feature = "websocket")]
    WebSocket { host: String, port: u16 },
}

/// Request handler function type
pub type RequestHandler =
    Arc<dyn Fn(Request) -> mpsc::Sender<(Request, mpsc::Sender<TransportMessage>)> + Send + Sync>;

/// Messages that can be sent through a transport
#[derive(Debug)]
pub enum TransportMessage {
    /// Response to a request
    Response(Response),

    /// Error response
    Error(ErrorMessage),

    /// Notification
    Notification(Notification),
}

/// Create a new transport based on configuration
pub fn create_transport(config: TransportConfig) -> Result<Box<dyn Transport>> {
    match config {
        TransportConfig::Stdio => {
            let transport = StdioTransport::new();
            Ok(Box::new(transport))
        }

        #[cfg(feature = "http")]
        TransportConfig::Http { host, port } => {
            let transport = HttpTransport::new(host, port);
            Ok(Box::new(transport))
        }

        #[cfg(feature = "websocket")]
        TransportConfig::WebSocket { host, port } => {
            let transport = WebSocketTransport::new(host, port);
            Ok(Box::new(transport))
        }
    }
}