Expand description
§TurboMCP Server
MCP (Model Context Protocol) server implementation with graceful shutdown, routing, lifecycle management, and comprehensive observability features.
§Features
- Roots Configuration - Configurable filesystem roots via builder API or macro
- Elicitation Support - Server-initiated requests for interactive user input
- Sampling Protocol - Bidirectional LLM sampling with client interaction
- Graceful Shutdown - Shutdown handling with signal support
- Multi-Transport - STDIO, TCP, Unix, WebSocket, HTTP/SSE support
- Middleware Stack - Authentication, rate limiting, and security headers
- Request Routing - Efficient handler registration and dispatch
- Health Monitoring - Comprehensive health checks and metrics
- Error Recovery - Robust error handling and recovery mechanisms
- MCP Compliance - Full support for tools, prompts, resources, roots, sampling, and elicitation
- Server-Initiated Requests - Support for sampling and elicitation via
ServerCapabilities
§Example
use turbomcp_server::ServerBuilder;
use turbomcp_protocol::types::Root;
use tokio::signal;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let server = ServerBuilder::new()
.name("MyServer")
.version("1.0.0")
// Configure filesystem roots
.root("file:///workspace", Some("Workspace".to_string()))
.root("file:///tmp", Some("Temp".to_string()))
.build();
// Get shutdown handle for graceful termination
let shutdown_handle = server.shutdown_handle();
// In production: spawn server and wait for shutdown
// tokio::spawn(async move { server.run_stdio().await });
// signal::ctrl_c().await?;
// shutdown_handle.shutdown().await;
Ok(())
}
§Elicitation Support (New in 1.0.3)
The server now includes comprehensive elicitation support for interactive user input:
ElicitationCoordinator
for managing elicitation lifecycle- Request/response correlation with timeouts
- Retry logic with configurable attempts
- Priority-based request queuing
- Automatic cleanup of expired requests
§Sampling Support (New in 1.0.3)
The server provides built-in support for server-initiated sampling requests to clients:
use turbomcp_server::sampling::SamplingExt;
use turbomcp_core::RequestContext;
use turbomcp_protocol::types::{CreateMessageRequest, SamplingMessage, Role, Content, TextContent};
async fn my_tool(ctx: RequestContext) -> Result<String, Box<dyn std::error::Error>> {
// Create a sampling request
let request = CreateMessageRequest {
messages: vec![SamplingMessage {
role: Role::User,
content: Content::Text(TextContent {
text: "What is 2+2?".to_string(),
annotations: None,
meta: None,
}),
}],
max_tokens: 50,
// ... other fields
};
// Send the request to the client
let result = ctx.create_message(request).await?;
Ok(format!("Response: {:?}", result))
}
Sampling Features:
- Client-side sampling configuration support
- Server-side sampling metadata tracking
- Integration with elicitation for dynamic sampling decisions
- Configurable timeouts and retry logic
§Compile-Time Routing (Experimental - New in 1.0.3)
Zero-cost compile-time router generation for high-throughput scenarios:
- Zero-cost compile-time router generation
- Type-safe route matching at compile time
- Automatic handler registration through macros
- Performance optimization for high-throughput scenarios
Note: Compile-time routing is experimental and may have limitations with some MCP protocol methods.
Re-exports§
pub use config::Configuration;
pub use config::ConfigurationBuilder;
pub use config::ServerConfig;
pub use error::ServerError;
pub use error::ServerResult;
pub use handlers::CompletionHandler;
pub use handlers::ElicitationHandler;
pub use handlers::LoggingHandler;
pub use handlers::PingHandler;
pub use handlers::PromptHandler;
pub use handlers::ResourceHandler;
pub use handlers::ResourceTemplateHandler;
pub use handlers::SamplingHandler;
pub use handlers::ToolHandler;
pub use lifecycle::HealthStatus;
pub use lifecycle::ServerLifecycle;
pub use lifecycle::ShutdownSignal;
pub use metrics::MetricsCollector;
pub use metrics::ServerMetrics;
pub use middleware::AuthenticationMiddleware;
pub use middleware::LoggingMiddleware;
pub use middleware::Middleware;
pub use middleware::MiddlewareLayer;
pub use middleware::MiddlewareStack;
pub use middleware::RateLimitMiddleware;
pub use middleware::SecurityHeadersConfig;
pub use middleware::SecurityHeadersMiddleware;
pub use registry::HandlerRegistry;
pub use registry::Registry;
pub use registry::RegistryBuilder;
pub use routing::RequestRouter;
pub use routing::Route;
pub use routing::Router;
pub use server::McpServer;
pub use server::ServerBuilder;
pub use server::ShutdownHandle;
pub use elicitation::ElicitationCoordinator;
pub use elicitation::ElicitationTransport;
Modules§
- config
- Server configuration management
- elicitation
- Elicitation support for TurboMCP servers
- error
- Server error types and handling
- handlers
- Handler traits and implementations for MCP operations
- lifecycle
- Server lifecycle management and graceful shutdown
- metrics
- Production-grade metrics collection and monitoring system
- middleware
- Middleware system for request/response processing
- prelude
- Prelude for common server functionality
- registry
- Handler registry for dynamic loading and management
- routing
- Request routing and handler dispatch system
- sampling
- Server-initiated sampling support for TurboMCP
- server
- Core MCP server implementation
Structs§
- Call
Tool Request - Call tool request
- Call
Tool Result - Call tool result
- Client
Capabilities - Client capabilities per MCP 2025-06-18 specification
- Json
RpcError - JSON-RPC error object
- Json
RpcRequest - JSON-RPC request message
- Json
RpcResponse - JSON-RPC response message
- Json
RpcVersion - JSON-RPC version type
- List
Tools Result - List tools result
- Request
Context - Context information for request processing
- Server
Capabilities - Server capabilities per MCP 2025-06-18 specification
- Tool
- Tool definition per MCP 2025-06-18 specification
Enums§
- Message
Id - Unique identifier for messages
Constants§
- SERVER_
NAME - Server name
- SERVER_
VERSION - Server version
Functions§
- default_
config - Default server configuration
- server
- Create a new server builder