Skip to main content

Crate turbomcp_client

Crate turbomcp_client 

Source
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 Transport implementation)
  • 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::{ContentBlock, CreateMessageRequest, CreateMessageResult, Role, StopReason, TextContent};
use std::future::Future;
use std::pin::Pin;

#[derive(Debug)]
struct MySamplingHandler {
    // Your LLM client would go here
}

impl SamplingHandler for MySamplingHandler {
    fn handle_create_message(
        &self,
        request_id: String,
        request: CreateMessageRequest
    ) -> Pin<Box<dyn Future<Output = Result<CreateMessageResult, Box<dyn std::error::Error + Send + Sync>>> + Send + '_>> {
        Box::pin(async move {
            // 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: ContentBlock::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, 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::ProgressHandler;
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 middleware::Cache;
pub use middleware::CacheConfig;
pub use middleware::CacheLayer;
pub use middleware::CacheService;
pub use middleware::McpRequest;
pub use middleware::McpResponse;
pub use middleware::Metrics;
pub use middleware::MetricsLayer;
pub use middleware::MetricsService;
pub use middleware::MetricsSnapshot;
pub use middleware::TracingLayer;
pub use middleware::TracingService;

Modules§

client
MCP client core implementation
handlers
Handler traits for bidirectional communication in MCP client
integration
Integration prelude for LLM framework integrations (Langchain, etc.)
middleware
Tower-native middleware for MCP client.
prelude
Prelude module for convenient imports
sampling
MCP-Compliant Client-Side Sampling Support

Structs§

BlobResourceContents
Binary resource contents
CallToolResult
The result of a CallToolRequest.
CancelledNotification
Cancellation notification
Client
JSON-RPC protocol handler for MCP communication MCP client for communicating with servers
ClientBuilder
Builder for configuring and creating MCP clients
ClientCapabilities
Client capability configuration
ConnectionConfig
Connection configuration for the client
EmbeddedResource
Embedded resource content per the current MCP specification
InitializeResult
Result of client initialization
LoggingNotification
Logging notification
ProgressNotification
Progress notification for reporting progress on long-running operations.
Prompt
Prompt definition per the current MCP specification
PublicServerCapabilities
Server capabilities per MCP 2025-11-25 specification
Resource
Resource definition per the current MCP specification
ResourceContents
Resource contents
ResourceUpdatedNotification
Resource updated notification
StdioTransport
Standard I/O transport implementation
TextResourceContents
Text resource contents
Tool
Represents a tool that can be executed by an MCP server

Enums§

ContentBlock
Content block union type
ElicitationAction
Elicitation action taken by user
LogLevel
Log level enumeration
ResourceContent
Union type for resource contents (text or binary)
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.

Type Aliases§

Error
v3.0 Error alias for migration (prefer McpError directly)
Result
v3.0 Result alias using McpError