ClientBuilder

Struct ClientBuilder 

Source
pub struct ClientBuilder { /* private fields */ }
Expand description

Builder for configuring and creating MCP clients

Provides a fluent interface for configuring client options before creation. The enhanced builder pattern supports comprehensive configuration including:

  • Protocol capabilities
  • Plugin registration
  • Handler registration
  • Connection settings
  • Resilience configuration

§Examples

Basic usage:

use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;

let client = ClientBuilder::new()
    .with_tools(true)
    .with_prompts(true)
    .with_resources(false)
    .build(StdioTransport::new());

Advanced configuration:

use turbomcp_client::{ClientBuilder, ConnectionConfig};
use turbomcp_client::plugins::{MetricsPlugin, PluginConfig};
use turbomcp_transport::stdio::StdioTransport;
use std::sync::Arc;

let client = ClientBuilder::new()
    .with_tools(true)
    .with_prompts(true)
    .with_resources(true)
    .with_sampling(true)
    .with_connection_config(ConnectionConfig {
        timeout_ms: 60_000,
        max_retries: 5,
        retry_delay_ms: 2_000,
        keepalive_ms: 30_000,
    })
    .with_plugin(Arc::new(MetricsPlugin::new(PluginConfig::Metrics)))
    .build(StdioTransport::new())
    .await?;

Implementations§

Source§

impl ClientBuilder

Source

pub fn new() -> Self

Create a new client builder

Returns a new builder with default configuration.

Source

pub fn with_tools(self, enabled: bool) -> Self

Enable or disable tool support

§Arguments
  • enabled - Whether to enable tool support
Source

pub fn with_prompts(self, enabled: bool) -> Self

Enable or disable prompt support

§Arguments
  • enabled - Whether to enable prompt support
Source

pub fn with_resources(self, enabled: bool) -> Self

Enable or disable resource support

§Arguments
  • enabled - Whether to enable resource support
Source

pub fn with_sampling(self, enabled: bool) -> Self

Enable or disable sampling support

§Arguments
  • enabled - Whether to enable sampling support
Source

pub fn with_capabilities(self, capabilities: ClientCapabilities) -> Self

Configure all capabilities at once

§Arguments
  • capabilities - The capabilities configuration
Source

pub fn with_connection_config(self, config: ConnectionConfig) -> Self

Configure connection settings

§Arguments
  • config - The connection configuration
Source

pub fn with_timeout(self, timeout_ms: u64) -> Self

Set request timeout

§Arguments
  • timeout_ms - Timeout in milliseconds
Source

pub fn with_max_retries(self, max_retries: u32) -> Self

Set maximum retry attempts

§Arguments
  • max_retries - Maximum number of retries
Source

pub fn with_retry_delay(self, delay_ms: u64) -> Self

Set retry delay

§Arguments
  • delay_ms - Retry delay in milliseconds
Source

pub fn with_keepalive(self, interval_ms: u64) -> Self

Set keep-alive interval

§Arguments
  • interval_ms - Keep-alive interval in milliseconds
Source

pub fn enable_resilience(self) -> Self

Enable resilient transport with circuit breaker, retry, and health checking

When enabled, the transport layer will automatically:

  • Retry failed operations with exponential backoff
  • Use circuit breaker pattern to prevent cascade failures
  • Perform periodic health checks
  • Deduplicate messages
§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;

let client = ClientBuilder::new()
    .enable_resilience()
    .build(StdioTransport::new());
Source

pub fn with_retry_config(self, config: RetryConfig) -> Self

Configure retry behavior for resilient transport

§Arguments
  • config - Retry configuration
§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_transport::resilience::RetryConfig;
use turbomcp_transport::stdio::StdioTransport;
use std::time::Duration;

let client = ClientBuilder::new()
    .enable_resilience()
    .with_retry_config(RetryConfig {
        max_attempts: 5,
        base_delay: Duration::from_millis(100),
        max_delay: Duration::from_secs(30),
        backoff_multiplier: 2.0,
        jitter_factor: 0.1,
        retry_on_connection_error: true,
        retry_on_timeout: true,
        custom_retry_conditions: Vec::new(),
    })
    .build(StdioTransport::new());
Source

pub fn with_circuit_breaker_config(self, config: CircuitBreakerConfig) -> Self

Configure circuit breaker for resilient transport

§Arguments
  • config - Circuit breaker configuration
§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_transport::resilience::CircuitBreakerConfig;
use turbomcp_transport::stdio::StdioTransport;
use std::time::Duration;

let client = ClientBuilder::new()
    .enable_resilience()
    .with_circuit_breaker_config(CircuitBreakerConfig {
        failure_threshold: 5,
        success_threshold: 2,
        timeout: Duration::from_secs(60),
        rolling_window_size: 100,
        minimum_requests: 10,
    })
    .build(StdioTransport::new());
Source

pub fn with_health_check_config(self, config: HealthCheckConfig) -> Self

Configure health checking for resilient transport

§Arguments
  • config - Health check configuration
§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_transport::resilience::HealthCheckConfig;
use turbomcp_transport::stdio::StdioTransport;
use std::time::Duration;

let client = ClientBuilder::new()
    .enable_resilience()
    .with_health_check_config(HealthCheckConfig {
        interval: Duration::from_secs(30),
        timeout: Duration::from_secs(5),
        failure_threshold: 3,
        success_threshold: 1,
        custom_check: None,
    })
    .build(StdioTransport::new());
Source

pub fn with_plugin(self, plugin: Arc<dyn ClientPlugin>) -> Self

Register a plugin with the client

Plugins provide middleware functionality for request/response processing, metrics collection, retry logic, caching, and other cross-cutting concerns.

§Arguments
  • plugin - The plugin implementation
§Examples
use turbomcp_client::{ClientBuilder, ConnectionConfig};
use turbomcp_client::plugins::{MetricsPlugin, RetryPlugin, PluginConfig, RetryConfig};
use std::sync::Arc;

let client = ClientBuilder::new()
    .with_plugin(Arc::new(MetricsPlugin::new(PluginConfig::Metrics)))
    .with_plugin(Arc::new(RetryPlugin::new(PluginConfig::Retry(RetryConfig {
        max_retries: 5,
        base_delay_ms: 1000,
        max_delay_ms: 30000,
        backoff_multiplier: 2.0,
        retry_on_timeout: true,
        retry_on_connection_error: true,
    }))));
Source

pub fn with_plugins(self, plugins: Vec<Arc<dyn ClientPlugin>>) -> Self

Register multiple plugins at once

§Arguments
  • plugins - Vector of plugin implementations
Source

pub fn with_elicitation_handler( self, handler: Arc<dyn ElicitationHandler>, ) -> Self

Register an elicitation handler for processing user input requests

§Arguments
  • handler - The elicitation handler implementation
Source

pub fn with_log_handler(self, handler: Arc<dyn LogHandler>) -> Self

Register a log handler for processing server log messages

§Arguments
  • handler - The log handler implementation
Source

pub fn with_resource_update_handler( self, handler: Arc<dyn ResourceUpdateHandler>, ) -> Self

Register a resource update handler for processing resource change notifications

§Arguments
  • handler - The resource update handler implementation
Source

pub async fn build<T: Transport + 'static>( self, transport: T, ) -> Result<Client<T>>

Build a client with the configured options

Creates a new client instance with all the configured options. The client will be initialized with the registered plugins, handlers, and providers.

§Arguments
  • transport - The transport to use for the client
§Returns

Returns a configured Client instance wrapped in a Result for async setup.

§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;

let client = ClientBuilder::new()
    .with_tools(true)
    .with_prompts(true)
    .build(StdioTransport::new())
    .await?;
Source

pub async fn build_resilient<T: Transport + 'static>( self, transport: T, ) -> Result<Client<TurboTransport>>

Build a client with resilient transport (circuit breaker, retry, health checking)

When resilience features are enabled via enable_resilience() or any resilience configuration method, this wraps the transport in a TurboTransport that provides:

  • Automatic retry with exponential backoff
  • Circuit breaker pattern for fast failure
  • Health checking and monitoring
  • Message deduplication
§Arguments
  • transport - The base transport to wrap with resilience features
§Returns

Returns a configured Client<TurboTransport> instance.

§Errors

Returns an error if plugin initialization fails.

§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;
use turbomcp_transport::resilience::{RetryConfig, CircuitBreakerConfig, HealthCheckConfig};
use std::time::Duration;

let client = ClientBuilder::new()
    .with_retry_config(RetryConfig {
        max_attempts: 5,
        base_delay: Duration::from_millis(200),
        ..Default::default()
    })
    .with_circuit_breaker_config(CircuitBreakerConfig {
        failure_threshold: 3,
        timeout: Duration::from_secs(30),
        ..Default::default()
    })
    .with_health_check_config(HealthCheckConfig {
        interval: Duration::from_secs(15),
        timeout: Duration::from_secs(5),
        ..Default::default()
    })
    .build_resilient(StdioTransport::new())
    .await?;
Source

pub fn build_sync<T: Transport + 'static>(self, transport: T) -> Client<T>

Build a client synchronously with basic configuration only

This is a convenience method for simple use cases where no async setup is required. For advanced features like plugins, use build() instead.

§Arguments
  • transport - The transport to use for the client
§Returns

Returns a configured Client instance.

§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;

let client = ClientBuilder::new()
    .with_tools(true)
    .build_sync(StdioTransport::new());
Source

pub fn capabilities(&self) -> &ClientCapabilities

Get the current capabilities configuration

Source

pub fn connection_config(&self) -> &ConnectionConfig

Get the current connection configuration

Source

pub fn plugin_count(&self) -> usize

Get the number of registered plugins

Source

pub fn has_handlers(&self) -> bool

Check if any handlers are registered

Trait Implementations§

Source§

impl Debug for ClientBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ClientBuilder

Source§

fn default() -> ClientBuilder

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more