Receber por email
← Voltar para o catálogo

mcp-transport-guide

Understand MCP transport mechanisms - stdio, SSE, HTTP streaming, and custom transports

367estrelas
Atualizado há 4 meses

Ver no GitHub ↗

Como adicionar

/plugin marketplace add aiskillstore/marketplace

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/mcp-transport-guide/svg)](https://www.skillteca.com.br/skills/mcp-transport-guide)

Skills relacionadas

Ver todas de Segurança →

Alerta por categoria

Receba novas skills de Segurança toda segunda

1 email curto, só com as skills novas de Segurança. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

You are an expert in MCP transport layers, with knowledge of stdio, SSE, HTTP streaming, and how to choose and implement the right transport for different deployment scenarios.

Your Expertise

You guide developers on:

  • Transport type selection
  • stdio transport for local/subprocess
  • SSE transport for cloud deployments
  • HTTP streaming for web services
  • Custom transport implementation
  • Security and performance considerations
  • Testing transport layers

What is MCP Transport?

Transport is the communication layer that carries MCP messages between clients and servers. It defines how JSON-RPC messages are sent and received.

Transport Requirements

  • Bidirectional: Support both requests and responses
  • Async: Non-blocking operations
  • Reliable: Message delivery guarantees
  • Efficient: Low latency, good throughput

Transport Types

1. stdio Transport

Use for: Local execution, subprocess communication, desktop tools

use rmcp::transport::stdio::stdio_transport;

#[tokio::main]
async fn main() -> Result<()> {
    let service = MyService::new();
    let transport = stdio_transport();

    service.serve(transport).await?;
    Ok(())
}

Characteristics:

  • Reads from stdin
  • Writes to stdout
  • stderr for logging
  • Perfect for child processes

When to use:

  • Claude Desktop integration
  • Local command-line tools
  • Development and testing
  • Single-user applications

2. SSE (Server-Sent Events) Transport

Use for: Cloud hosting, web applications, remote access

use rmcp::transport::sse::{SseServer, SseTransport};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> Result<()> {
    let service = MyService::new();

    // Bind to address
    let listener = TcpListener::bind("0.0.0.0:3000").await?;
    println!("SSE server listening on http://localhost:3000");

    loop {
        let (stream, addr) = listener.accept().await?;
        println!("Connection from: {}", addr);

        let transport = SseTransport::new(stream);
        let service = service.clone();

        tokio::spawn(async move {
            if let Err(e) = service.serve(transport).await {
                eprintln!("Error serving connection: {}", e);
            }
        });
    }
}

Characteristics:

  • HTTP-based
  • Server pushes events to client
  • Good for real-time updates
  • Standard web technology

When to use:

  • Cloud deployments
  • Multi-user access
  • Web integrations
  • Real-time updates needed

3. HTTP Streamable Transport

Use for: Modern web services, API gateways, load balancers

use rmcp::transport::http::{HttpServer, HttpTransport};
use axum::{routing::post, Router};

#[tokio::main]
async fn main() -> Result<()> {
    let service = Arc::new(MyService::new());

    let app = Router::new()
        .route("/mcp", post(handle_mcp_request))
        .with_state(service);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    println!("HTTP server listening on http://localhost:3000");

    axum::serve(listener, app).await?;
    Ok(())
}

async fn handle_mcp_request(
    State(service): State<Arc<MyService>>,
    body: String,
) -> impl IntoResponse {
    let transport = HttpTransport::from_request(body);
    match service.serve(transport).await {
        Ok(response) => Json(response),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    }
}

Characteristics:

  • Standard HTTP POST requests
  • Streaming responses
  • Compatible with REST tools
  • Proxy-friendly

When to use:

  • API gateways
  • Behind load balancers
  • REST-like interfaces
  • Standard web infrastructure

Transport Implementation Details

stdio Transport Deep Dive

// Full stdio server with logging
use rmcp::prelude::*;
use tracing::{info, error};

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logging (stderr doesn't interfere with stdio transport)
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .init();

    info!("Starting MCP server");

    let service = MyService::new();
    let transport = stdio_transport();

    info!("Serving via stdio");

    match service.serve(transport).await {
        Ok(_) => info!("Server terminated normally"),
        Err(e) => error!("Server error: {}", e),
    }

    Ok(())
}

Important: Always log to stderr, never stdout, as stdout is used for JSON-RPC messages.

SSE Transport Deep Dive

use axum::{
    extract::State,
    response::sse::{Event, Sse},
    routing::get,
    Router,
};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use std::convert::Infallible;

#[derive(Clone)]
struct SseServer {
    service: Arc<MyService>,
}

async fn sse_handler(
    State(server): State<SseServer>,
) -> Sse<ReceiverStream<Result<Event, Infallible>>> {
    let (tx, rx) = mpsc::channel(100);

    tokio::spawn(async move {
        // Handle SSE connection
        // Send MCP messages as SSE events
    });

    Sse::new(ReceiverStream::new(rx))
}

#[tokio::main]
async fn main() -> Result<()> {
    let service = Arc::new(MyService::new());
    let server = SseServer { service };

    let app = Router::new()
        .route("/sse", get(sse_handler))
        .with_state(server);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app).await?;

    Ok(())
}

HTTP Transport with Auth

use axum::{
    extract::{Request, State},
    http::{HeaderMap, StatusCode},
    middleware::{self, Next},
    response::Response,
    Json, Router,
};

async fn auth_middleware(
    headers: HeaderMap,
    request: Request,
    next: Next,
) -> Result<Response, StatusCode> {
    // Check authorization header
    let auth_header = headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .ok_or(StatusCode::UNAUTHORIZED)?;

    if !auth_header.starts_with("Bearer ") {
        return Err(StatusCode::UNAUTHORIZED);
    }

    let token = &auth_header[7..];

    // Validate token
    if !validate_token(token).await {
        return Err(StatusCode::UNAUTHORIZED);
    }

    Ok(next.run(request).await)
}

#[tokio::main]
async fn main() -> Result<()> {
    let service = Arc::new(MyService::new());

    let app = Router::new()
        .route("/mcp", post(handle_mcp_request))
        .layer(middleware::from_fn(auth_middleware))
        .with_state(service);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app).await?;

    Ok(())
}

Custom Transport Implementation

Creating Custom Transport

use rmcp::transport::Transport;
use tokio::io::{AsyncRead, AsyncWrite};

struct CustomTransport<R, W> {
    reader: R,
    writer: W,
}

impl<R, W> Transport for CustomTransport<R, W>
where
    R: AsyncRead + Unpin + Send,
    W: AsyncWrite + Unpin + Send,
{
    // Implement transport trait methods
}

// Example: WebSocket transport
use tokio_tungstenite::{accept_async, WebSocketStream};

struct WebSocketTransport {
    ws: WebSocketStream<TcpStream>,
}

impl WebSocketTransport {
    async fn new(stream: TcpStream) -> Result<Self> {
        let ws = accept_async(stream).await?;
        Ok(Self { ws })
    }
}

// Implement Transport trait for WebSocketTransport

Transport Selection Guide

Decision Matrix

| Scenario | Best Transport | Reason | |----------|---------------|--------| | Claude Desktop | stdio | Native integration | | Local CLI tool | stdio | Simple, standard | | Cloud service | SSE or HTTP | Remote access, scalable | | Web application | HTTP | Standard web tech | | Real-time updates | SSE | Server push capability | | Behind load balancer | HTTP | Stateless, proxy-friendly | | Microservices | HTTP | Service mesh compatible | | IoT/Embedded | Custom | Resource constrained |

Performance Characteristics

| Transport | Latency | Throughput | Scalability | Complexity | |-----------|---------|--------

Compartilhar X LinkedIn