SessionManager

Struct SessionManager 

Source
pub struct SessionManager<T: Transport + 'static> { /* private fields */ }
Expand description

Multi-Server Session Manager for MCP Clients

The SessionManager coordinates multiple MCP server sessions with automatic health monitoring and lifecycle management. Each session represents a long-lived, initialized connection to a different MCP server.

§Use Cases

  • Multi-Server Applications: IDE with multiple tool servers
  • Service Coordination: Orchestrate operations across multiple MCP servers
  • Health Monitoring: Track health of all connected servers
  • Failover: Switch between primary/backup servers

§Examples

use turbomcp_client::SessionManager;
use turbomcp_transport::stdio::StdioTransport;

let mut manager = SessionManager::with_defaults();

// Add sessions to different servers
let github_transport = StdioTransport::new();
let fs_transport = StdioTransport::new();
manager.add_server("github", github_transport).await?;
manager.add_server("filesystem", fs_transport).await?;

// Start health monitoring
manager.start_health_monitoring().await;

// Get stats
let stats = manager.session_stats().await;
println!("Managing {} sessions", stats.len());

Implementations§

Source§

impl<T: Transport + Send + 'static> SessionManager<T>

Source

pub fn new(config: ManagerConfig) -> Self

Create a new connection manager with the specified configuration

Source

pub fn with_defaults() -> Self

Create a new connection manager with default configuration

Source

pub async fn add_server( &mut self, id: impl Into<String>, transport: T, ) -> Result<()>

Add a new server session

Creates and initializes a session to the specified MCP server.

§Arguments
  • id - Unique identifier for this server (e.g., “github”, “filesystem”)
  • transport - Transport implementation for connecting to the server
§Errors

Returns an error if:

  • Maximum sessions limit is reached
  • Server ID already exists
  • Client initialization fails
§Examples
let mut manager = SessionManager::with_defaults();
let github_transport = StdioTransport::new();
let fs_transport = StdioTransport::new();
manager.add_server("github", github_transport).await?;
manager.add_server("filesystem", fs_transport).await?;
Source

pub async fn add_server_with_reconnect<F>( &mut self, id: impl Into<String>, transport_factory: F, ) -> Result<()>
where F: Fn() -> T + Send + Sync + 'static,

Add a server session with automatic reconnection support

This method accepts a factory function that creates new transport instances, enabling automatic reconnection if the session fails.

§Arguments
  • id - Unique identifier for this server
  • transport_factory - Function that creates new transport instances
§Examples
let mut manager = SessionManager::with_defaults();

// Transport with reconnection factory
manager.add_server_with_reconnect("api", || {
    StdioTransport::new()
}).await?;
Source

pub async fn remove_server(&mut self, id: &str) -> bool

Remove a managed connection

§Arguments
  • id - ID of the connection to remove
§Returns

Returns true if the connection was removed, false if not found

Source

pub async fn get_session_info(&self, id: &str) -> Option<ConnectionInfo>

Get information about a specific connection

Source

pub async fn list_sessions(&self) -> Vec<ConnectionInfo>

List all managed connections

Source

pub async fn get_healthy_connection(&self) -> Option<String>

Get a healthy connection, preferring the one with the fewest active requests

§Returns

Returns the ID of a healthy connection, or None if no healthy connections exist

Source

pub async fn session_stats(&self) -> HashMap<ConnectionState, usize>

Get count of connections by state

Source

pub async fn start_health_monitoring(&mut self)

Start automatic health monitoring

Spawns a background task that periodically checks the health of all connections

Source

pub fn stop_health_monitoring(&mut self)

Stop automatic health monitoring

Source

pub async fn session_count(&self) -> usize

Get total number of managed connections

Source§

impl SessionManager<TurboTransport>

Source

pub async fn add_resilient_server<BaseT>( &mut self, id: impl Into<String>, transport: BaseT, retry_config: RetryConfig, circuit_config: CircuitBreakerConfig, health_config: HealthCheckConfig, ) -> Result<()>
where BaseT: Transport + 'static,

Add a server with automatic robustness (specialized for TurboTransport)

This convenience method is only available when using SessionManager<TurboTransport>. It wraps any transport in TurboTransport with the specified configurations.

§Examples
let mut manager: SessionManager<TurboTransport> = SessionManager::with_defaults();

// Use explicit configuration for clarity
use std::time::Duration;
manager.add_resilient_server(
    "github",
    StdioTransport::new(),
    RetryConfig {
        max_attempts: 5,
        base_delay: Duration::from_millis(200),
        ..Default::default()
    },
    CircuitBreakerConfig {
        failure_threshold: 3,
        timeout: Duration::from_secs(30),
        ..Default::default()
    },
    HealthCheckConfig {
        interval: Duration::from_secs(15),
        timeout: Duration::from_secs(5),
        ..Default::default()
    },
).await?;

Trait Implementations§

Source§

impl<T: Transport + 'static> Drop for SessionManager<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T> Freeze for SessionManager<T>

§

impl<T> !RefUnwindSafe for SessionManager<T>

§

impl<T> Send for SessionManager<T>

§

impl<T> Sync for SessionManager<T>

§

impl<T> Unpin for SessionManager<T>

§

impl<T> !UnwindSafe for SessionManager<T>

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