rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A session's connected MCP servers behind one shared handle ([`McpHost`]),
//! which the session's tool set and its `mcp_reload` tool both hold.
//!
//! A reload reconciles the servers at once, during a turn too, since the
//! handle is not behind the session's runtime lock. Their tools join or
//! leave the tool set only when it takes the changes
//! ([`McpHost::take_changes`]), which the session does before its next
//! prompt: the running turn keeps the tools it started with, and the
//! executor never sees a tool its run does not have. `McpHost` is a leaf
//! lock: nothing that holds it waits on the runtime.

use std::{
    path::PathBuf,
    sync::{Arc, Mutex, MutexGuard, PoisonError},
};

use rho_sdk::tool::Tool;

use super::{
    config::McpConfig, McpBundle, McpCatalog, McpReload, McpReloadChanges, McpSecretAsks,
    McpSessionOptions, McpSessionReport,
};

/// The servers of one session, shared by its tool set and its tools.
#[derive(Clone, Default)]
pub(crate) struct McpHost {
    inner: Arc<Inner>,
}

#[derive(Default)]
struct Inner {
    state: Mutex<State>,
    /// Held across a reload, which takes the bundle out of `state`, so two
    /// reloads, or a reload and a close, run one after the other.
    reloads: tokio::sync::Mutex<()>,
}

#[derive(Default)]
struct State {
    bundle: Option<McpBundle>,
    catalog: McpCatalog,
    /// What a reload connects servers with; `None` for a session that does
    /// not connect them.
    options: Option<McpSessionOptions>,
    /// Whether the session can ask a person for a server's secret.
    secret_asks: McpSecretAsks,
    discovery: Option<McpDiscovery>,
    changes: Option<McpChanges>,
}

/// How a session finds its servers in config: where the config lives, and
/// how its `[mcp]` table becomes the session's servers, with a host's
/// servers on top and the plugins the session may load.
#[derive(Clone)]
pub(crate) struct McpDiscovery {
    config_path: PathBuf,
    servers: Arc<dyn Fn(&McpConfig) -> McpConfig + Send + Sync>,
}

impl McpDiscovery {
    pub(crate) fn new(
        config_path: PathBuf,
        servers: impl Fn(&McpConfig) -> McpConfig + Send + Sync + 'static,
    ) -> Self {
        Self {
            config_path,
            servers: Arc::new(servers),
        }
    }
}

/// What reloads changed since the tool set last took their changes.
pub(crate) struct McpChanges {
    /// Where the servers ended up.
    pub(crate) report: McpSessionReport,
    /// Tools of servers that closed, which the tool set still lists.
    pub(crate) retired: Vec<Arc<dyn Tool>>,
    /// Tools of servers that started, which the tool set does not list yet.
    pub(crate) added: Vec<Arc<dyn Tool>>,
}

impl McpChanges {
    /// Folds a later reload's changes in. A tool an earlier reload added and
    /// this one retired never reached the tool set, so it leaves both lists.
    fn merge(&mut self, later: Self) {
        self.report = later.report;
        for tool in later.retired {
            match self
                .added
                .iter()
                .position(|added| Arc::ptr_eq(added, &tool))
            {
                Some(index) => {
                    self.added.remove(index);
                }
                None => self.retired.push(tool),
            }
        }
        self.added.extend(later.added);
    }
}

/// Why a session's MCP servers were not reloaded.
#[derive(Debug, thiserror::Error)]
pub(crate) enum McpReloadError {
    #[error("this session does not connect MCP servers")]
    NotConnecting,
    #[error("could not read {path}: {error:#}")]
    Config { path: String, error: anyhow::Error },
    #[error("the reload stopped as rho shut down")]
    Interrupted,
}

impl McpHost {
    /// Holds `bundle`, the servers the session connected as it opened, and
    /// `catalog`, the prompts and resources they offer.
    pub(crate) fn attach(&self, bundle: Option<McpBundle>, catalog: McpCatalog) {
        let mut state = self.state();
        state.bundle = bundle;
        state.catalog = catalog;
    }

    /// Lets the servers reload, connecting them with `options`, those the
    /// session connected its servers with at start, in a session that can
    /// ask a person for their secrets when `secret_asks` says so.
    pub(crate) fn allow_reload(&self, options: McpSessionOptions, secret_asks: McpSecretAsks) {
        let mut state = self.state();
        state.options = Some(options);
        state.secret_asks = secret_asks;
    }

    /// Whether the session can ask a person for a server's secret.
    pub(crate) fn secret_asks(&self) -> McpSecretAsks {
        self.state().secret_asks
    }

    /// Sets how a reload finds the session's servers in config.
    pub(crate) fn set_discovery(&self, discovery: McpDiscovery) {
        self.state().discovery = Some(discovery);
    }

    /// Every connected server's tools, in identity order.
    pub(crate) fn tools(&self) -> Vec<Arc<dyn Tool>> {
        self.state()
            .bundle
            .as_ref()
            .map(|bundle| bundle.tools().to_vec())
            .unwrap_or_default()
    }

    /// Reconciles the servers with `servers`, a config's `[mcp]` table, as
    /// [`McpBundle::reload`] does: a server that would start the same way
    /// keeps running, the rest start, restart, or stop.
    ///
    /// The reconcile runs on its own task, so a caller that stops waiting,
    /// as a cancelled turn's `mcp_reload` does, never drops the servers it
    /// took out: the task still puts them back and records the changes.
    pub(crate) async fn reload(
        &self,
        servers: &McpConfig,
    ) -> Result<(McpReloadChanges, McpSessionReport), McpReloadError> {
        let host = self.clone();
        let servers = servers.clone();
        match tokio::spawn(async move { host.reconcile(&servers).await }).await {
            Ok(reloaded) => reloaded,
            Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
            Err(_) => Err(McpReloadError::Interrupted),
        }
    }

    async fn reconcile(
        &self,
        servers: &McpConfig,
    ) -> Result<(McpReloadChanges, McpSessionReport), McpReloadError> {
        let _reloading = self.inner.reloads.lock().await;
        let (previous, catalog, options, discovery) = {
            let mut state = self.state();
            let (Some(options), Some(discovery)) = (state.options.clone(), state.discovery.clone())
            else {
                return Err(McpReloadError::NotConnecting);
            };
            (
                state.bundle.take(),
                state.catalog.clone(),
                options,
                discovery,
            )
        };
        let McpReload {
            outcome,
            changes,
            retired,
            added,
        } = McpBundle::reload(previous, catalog, &(discovery.servers)(servers), &options).await;
        let report = outcome.report.clone();
        let mut state = self.state();
        state.bundle = outcome.bundle;
        state.catalog = outcome.catalog;
        // A reload that started and stopped nothing leaves the tool set, and
        // the prompt that names the servers, as they are.
        if !changes.started.is_empty() || !changes.stopped.is_empty() {
            let later = McpChanges {
                report: outcome.report,
                retired,
                added,
            };
            match &mut state.changes {
                Some(earlier) => earlier.merge(later),
                None => state.changes = Some(later),
            }
        }
        Ok((changes, report))
    }

    /// Reloads from the session's config file as it is now, as the
    /// `mcp_reload` tool does.
    pub(crate) async fn reload_from_config(
        &self,
    ) -> Result<(McpReloadChanges, McpSessionReport), McpReloadError> {
        let config = self.config_file()?;
        self.reload(&config.mcp).await
    }

    /// The servers a reload would find in the session's config file as it
    /// is now, the host's and plugins' among them.
    pub(crate) fn configured_servers(&self) -> Result<McpConfig, McpReloadError> {
        let config = self.config_file()?;
        let discovery = self
            .state()
            .discovery
            .clone()
            .ok_or(McpReloadError::NotConnecting)?;
        Ok((discovery.servers)(&config.mcp))
    }

    fn config_file(&self) -> Result<crate::config::Config, McpReloadError> {
        let path = self
            .state()
            .discovery
            .as_ref()
            .map(|discovery| discovery.config_path.clone())
            .ok_or(McpReloadError::NotConnecting)?;
        crate::config::Config::load(Some(path.clone())).map_err(|error| McpReloadError::Config {
            path: path.display().to_string(),
            error,
        })
    }

    /// What reloads changed since the last call, if any reloaded.
    pub(crate) fn take_changes(&self) -> Option<McpChanges> {
        self.state().changes.take()
    }

    /// Closes every server, once any reload under way has finished.
    pub(crate) async fn close(&self) {
        let _reloading = self.inner.reloads.lock().await;
        let bundle = self.state().bundle.take();
        if let Some(bundle) = bundle {
            bundle.close().await;
        }
    }

    fn state(&self) -> MutexGuard<'_, State> {
        self.inner
            .state
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }
}

#[cfg(test)]
#[path = "host_tests.rs"]
mod tests;