mcp-transport-guide
Understand MCP transport mechanisms - stdio, SSE, HTTP streaming, and custom transports
What this skill does
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
```rust
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
```rust
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
```rust
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
```rust
// 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
```rust
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
```rust
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
```rust
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 |
|-----------|---------|-------Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.