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() -> ClientBuilder

Create a new client builder

Returns a new builder with default configuration.

Source

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

Enable or disable tool support

§Arguments
  • enabled - Whether to enable tool support
Source

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

Enable or disable prompt support

§Arguments
  • enabled - Whether to enable prompt support
Source

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

Enable or disable resource support

§Arguments
  • enabled - Whether to enable resource support
Source

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

Enable or disable sampling support

§Arguments
  • enabled - Whether to enable sampling support
Source

pub fn with_max_concurrent_handlers(self, limit: usize) -> ClientBuilder

Set maximum concurrent request/notification handlers

This limits how many server-initiated requests/notifications can be processed simultaneously. Provides automatic backpressure when the limit is reached.

§Arguments
  • limit - Maximum concurrent handlers (default: 100)
§Tuning Guide
  • Low-resource clients: 50
  • Standard clients: 100 (default)
  • High-performance: 200-500
  • Maximum recommended: 1000
§Example
use turbomcp_client::ClientBuilder;

let builder = ClientBuilder::new()
    .with_max_concurrent_handlers(200);
Source

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

Configure all capabilities at once

§Arguments
  • capabilities - The capabilities configuration
Source

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

Configure connection settings

§Arguments
  • config - The connection configuration
Source

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

Set request timeout

§Arguments
  • timeout_ms - Timeout in milliseconds
Source

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

Set maximum retry attempts

§Arguments
  • max_retries - Maximum number of retries
Source

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

Set retry delay

§Arguments
  • delay_ms - Retry delay in milliseconds
Source

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

Set keep-alive interval

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

pub fn enable_resilience(self) -> ClientBuilder

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) -> ClientBuilder

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, ) -> ClientBuilder

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, ) -> ClientBuilder

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>) -> ClientBuilder

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>>) -> ClientBuilder

Register multiple plugins at once

§Arguments
  • plugins - Vector of plugin implementations
Source

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

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>) -> ClientBuilder

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>, ) -> ClientBuilder

Register a resource update handler for processing resource change notifications

§Arguments
  • handler - The resource update handler implementation
Source

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

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>( self, transport: T, ) -> Result<Client<TurboTransport>, Box<Error>>
where T: Transport + 'static,

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>(self, transport: T) -> Client<T>
where T: Transport + 'static,

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<(), Error>

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§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

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

§

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

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

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
§

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

§

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<D> OwoColorize for D

Source§

fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>
where C: Color,

Set the foreground color generically Read more
Source§

fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>
where C: Color,

Set the background color generically. Read more
Source§

fn black(&self) -> FgColorDisplay<'_, Black, Self>

Change the foreground color to black
Source§

fn on_black(&self) -> BgColorDisplay<'_, Black, Self>

Change the background color to black
Source§

fn red(&self) -> FgColorDisplay<'_, Red, Self>

Change the foreground color to red
Source§

fn on_red(&self) -> BgColorDisplay<'_, Red, Self>

Change the background color to red
Source§

fn green(&self) -> FgColorDisplay<'_, Green, Self>

Change the foreground color to green
Source§

fn on_green(&self) -> BgColorDisplay<'_, Green, Self>

Change the background color to green
Source§

fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>

Change the foreground color to yellow
Source§

fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>

Change the background color to yellow
Source§

fn blue(&self) -> FgColorDisplay<'_, Blue, Self>

Change the foreground color to blue
Source§

fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>

Change the background color to blue
Source§

fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to magenta
Source§

fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to magenta
Source§

fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to purple
Source§

fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to purple
Source§

fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>

Change the foreground color to cyan
Source§

fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>

Change the background color to cyan
Source§

fn white(&self) -> FgColorDisplay<'_, White, Self>

Change the foreground color to white
Source§

fn on_white(&self) -> BgColorDisplay<'_, White, Self>

Change the background color to white
Source§

fn default_color(&self) -> FgColorDisplay<'_, Default, Self>

Change the foreground color to the terminal default
Source§

fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>

Change the background color to the terminal default
Source§

fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>

Change the foreground color to bright black
Source§

fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>

Change the background color to bright black
Source§

fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>

Change the foreground color to bright red
Source§

fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>

Change the background color to bright red
Source§

fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>

Change the foreground color to bright green
Source§

fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>

Change the background color to bright green
Source§

fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>

Change the foreground color to bright yellow
Source§

fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>

Change the background color to bright yellow
Source§

fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>

Change the foreground color to bright blue
Source§

fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>

Change the background color to bright blue
Source§

fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright magenta
Source§

fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright magenta
Source§

fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright purple
Source§

fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright purple
Source§

fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>

Change the foreground color to bright cyan
Source§

fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>

Change the background color to bright cyan
Source§

fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>

Change the foreground color to bright white
Source§

fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>

Change the background color to bright white
Source§

fn bold(&self) -> BoldDisplay<'_, Self>

Make the text bold
Source§

fn dimmed(&self) -> DimDisplay<'_, Self>

Make the text dim
Source§

fn italic(&self) -> ItalicDisplay<'_, Self>

Make the text italicized
Source§

fn underline(&self) -> UnderlineDisplay<'_, Self>

Make the text underlined
Make the text blink
Make the text blink (but fast!)
Source§

fn reversed(&self) -> ReversedDisplay<'_, Self>

Swap the foreground and background colors
Source§

fn hidden(&self) -> HiddenDisplay<'_, Self>

Hide the text
Source§

fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>

Cross out the text
Source§

fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either OwoColorize::fg or a color-specific method, such as OwoColorize::green, Read more
Source§

fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either OwoColorize::bg or a color-specific method, such as OwoColorize::on_yellow, Read more
Source§

fn fg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> FgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the foreground color to a specific RGB value.
Source§

fn bg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> BgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the background color to a specific RGB value.
Source§

fn truecolor(&self, r: u8, g: u8, b: u8) -> FgDynColorDisplay<'_, Rgb, Self>

Sets the foreground color to an RGB value.
Source§

fn on_truecolor(&self, r: u8, g: u8, b: u8) -> BgDynColorDisplay<'_, Rgb, Self>

Sets the background color to an RGB value.
Source§

fn style(&self, style: Style) -> Styled<&Self>

Apply a runtime-determined style
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
§

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

§

type Error = Infallible

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

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

Performs the conversion.
§

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

§

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

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

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