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
  • LLM provider configuration
  • Handler registration
  • Connection settings
  • Session management

§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_client::llm::{OpenAIProvider, LLMProviderConfig};
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)))
    .with_llm_provider("openai", Arc::new(OpenAIProvider::new(LLMProviderConfig {
        api_key: std::env::var("OPENAI_API_KEY")?,
        model: "gpt-4".to_string(),
        ..Default::default()
    })?))
    .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 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_llm_provider( self, name: impl Into<String>, provider: Arc<dyn LLMProvider>, ) -> Self

Register an LLM provider

LLM providers handle server-initiated sampling requests by forwarding them to language model services like OpenAI, Anthropic, or local models.

§Arguments
  • name - Unique name for the provider
  • provider - The LLM provider implementation
§Examples
use turbomcp_client::ClientBuilder;
use turbomcp_client::llm::{OpenAIProvider, AnthropicProvider, LLMProviderConfig};
use std::sync::Arc;

let client = ClientBuilder::new()
    .with_llm_provider("openai", Arc::new(OpenAIProvider::new(LLMProviderConfig {
        api_key: std::env::var("OPENAI_API_KEY")?,
        model: "gpt-4".to_string(),
        ..Default::default()
    })?))
    .with_llm_provider("anthropic", Arc::new(AnthropicProvider::new(LLMProviderConfig {
        api_key: std::env::var("ANTHROPIC_API_KEY")?,
        model: "claude-3-5-sonnet-20241022".to_string(),
        ..Default::default()
    })?));
Source

pub fn with_llm_providers( self, providers: HashMap<String, Arc<dyn LLMProvider>>, ) -> Self

Register multiple LLM providers at once

§Arguments
  • providers - Map of provider names to implementations
Source

pub fn with_session_config(self, config: SessionConfig) -> Self

Configure session management for conversations

§Arguments
  • config - Session configuration for conversation tracking
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_progress_handler(self, handler: Arc<dyn ProgressHandler>) -> Self

Register a progress handler for processing operation progress updates

§Arguments
  • handler - The progress 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>(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 fn build_sync<T: Transport>(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 LLM providers, 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 llm_provider_count(&self) -> usize

Get the number of registered LLM providers

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