Expand description
§TurboMCP Client
MCP (Model Context Protocol) client implementation for connecting to MCP servers and consuming their capabilities (tools, prompts, resources, and sampling).
§Features
- Connection management with automatic reconnection
- Error handling and recovery mechanisms
- Support for all MCP capabilities including bidirectional sampling
- Elicitation response handling for server-initiated user input requests
- Transport-agnostic design (works with any
Transportimplementation) - Type-safe protocol communication
- Request/response correlation tracking
- Timeout and cancellation support
- Automatic capability negotiation
- Handler support for server-initiated requests (sampling and elicitation)
§Architecture
The client follows a layered architecture:
Application Layer
↓
Client API (this crate)
↓
Protocol Layer (turbomcp-protocol)
↓
Transport Layer (turbomcp-transport)§Usage
use turbomcp_client::{Client, ClientBuilder};
use turbomcp_transport::stdio::StdioTransport;
// Create a client with stdio transport
let transport = StdioTransport::new();
let mut client = Client::new(transport);
// Initialize connection and negotiate capabilities
let result = client.initialize().await?;
println!("Connected to: {}", result.server_info.name);
// List and call tools
let tools = client.list_tools().await?;
for tool in tools {
println!("Tool: {} - {}", tool.name, tool.description.as_deref().unwrap_or("No description"));
}
// Access resources
let resources = client.list_resources().await?;
for resource in resources {
println!("Resource: {} ({})", resource.name, resource.uri);
}§Elicitation Response Handling
The client supports handling server-initiated elicitation requests:
use turbomcp_client::Client;
use std::collections::HashMap;
// Simple elicitation handling example
async fn handle_server_elicitation() {
// When server requests user input, you would:
// 1. Present the schema to the user
// 2. Collect their input
// 3. Send response back to server
let user_preferences: HashMap<String, String> = HashMap::new();
// Your UI/CLI interaction logic here
println!("Server requesting user preferences");
}§Sampling Support
Handle server-initiated sampling requests for LLM capabilities:
use turbomcp_client::Client;
use turbomcp_client::sampling::SamplingHandler;
use turbomcp_protocol::types::{CreateMessageRequest, CreateMessageResult, Role, Content, StopReason, TextContent};
use async_trait::async_trait;
#[derive(Debug)]
struct MySamplingHandler {
// Your LLM client would go here
}
#[async_trait]
impl SamplingHandler for MySamplingHandler {
async fn handle_create_message(
&self,
request_id: String,
request: CreateMessageRequest
) -> Result<CreateMessageResult, Box<dyn std::error::Error + Send + Sync>> {
// Forward to your LLM provider (OpenAI, Anthropic, etc.)
// Use request_id for correlation tracking
// Allows the server to request LLM sampling through the client
Ok(CreateMessageResult {
role: Role::Assistant,
content: Content::Text(
TextContent {
text: "Response from LLM".to_string(),
annotations: None,
meta: None,
}
),
model: "gpt-4".to_string(),
stop_reason: Some(StopReason::EndTurn),
_meta: None,
})
}
}§Error Handling
The client provides comprehensive error handling with automatic retry logic:
match client.call_tool("my_tool", None).await {
Ok(result) => println!("Tool result: {:?}", result),
Err(e) => eprintln!("Tool call failed: {}", e),
}Re-exports§
pub use client::ConnectionInfo;pub use client::ConnectionState;pub use client::ManagerConfig;pub use client::ServerGroup;pub use client::SessionManager;pub use handlers::CancellationHandler;pub use handlers::ElicitationHandler;pub use handlers::ElicitationRequest;pub use handlers::ElicitationResponse;pub use handlers::HandlerError;pub use handlers::HandlerResult;pub use handlers::LogHandler;pub use handlers::PromptListChangedHandler;pub use handlers::ResourceListChangedHandler;pub use handlers::ResourceUpdateHandler;pub use handlers::RootsHandler;pub use handlers::ToolListChangedHandler;pub use sampling::SamplingHandler;pub use sampling::ServerInfo;pub use sampling::UserInteractionHandler;pub use plugins::CachePlugin;pub use plugins::ClientPlugin;pub use plugins::MetricsPlugin;pub use plugins::PluginConfig;pub use plugins::PluginContext;pub use plugins::PluginError;pub use plugins::PluginResult;pub use plugins::RetryPlugin;
Modules§
- client
- MCP client core implementation
- handlers
- Handler traits for bidirectional communication in MCP client
- integration
- Integration prelude for LLM framework integrations (Langchain, etc.)
- plugins
- Plugin system for TurboMCP client
- prelude
- Prelude module for convenient imports
- sampling
- MCP-Compliant Client-Side Sampling Support
Macros§
- with_
plugins - Execute a protocol call with full plugin middleware support
- with_
plugins_ list - Execute plugin middleware for methods that return lists (common pattern)
- with_
simple_ plugins - Execute a simple protocol call with plugin middleware for methods without complex request data
Structs§
- Cancelled
Notification - Cancellation notification
- Client
- JSON-RPC protocol handler for MCP communication MCP client for communicating with servers
- Client
Builder - Builder for configuring and creating MCP clients
- Client
Capabilities - Client capability configuration
- Connection
Config - Connection configuration for the client
- Error
- Comprehensive error type with rich context information
- Initialize
Result - Result of client initialization
- Logging
Notification - Logging notification
- Prompt
- Prompt definition per MCP 2025-06-18 specification
- Public
Server Capabilities - Server capabilities per MCP 2025-11-25 specification
- Resource
- Resource definition per MCP 2025-06-18 specification
- Resource
Contents - Resource contents
- Resource
Updated Notification - Resource updated notification
- Stdio
Transport - Standard I/O transport implementation
- Tool
- Represents a tool that can be executed by an MCP server
Enums§
- Elicitation
Action - Elicitation action taken by user
- LogLevel
- Log level enumeration
- Role
- Role in conversation
Constants§
- CRATE_
NAME - TurboMCP Client crate name
- VERSION
- TurboMCP Client version from Cargo.toml
Traits§
- Transport
- The core trait for all transport implementations.