rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Native Model Context Protocol client.
//!
//! Configuration is the trust boundary: enabling a server is permission to
//! start it, discover its tools, and expose them for the session. Everything
//! below is per-session mechanics on top of that decision.

use std::sync::Arc;

use crate::session_environment::SessionEnvironment;
use config::McpConfig;

pub(crate) mod bearer_client;
mod bundle;
pub(crate) mod catalog;
pub(crate) mod client;
pub(crate) mod config;
pub(crate) mod definition;
pub(crate) mod display;
pub(crate) mod elicitation;
pub(crate) mod elicitation_form;
pub(crate) mod exported_name;
mod host;
mod http_client;
pub(crate) mod inflight;
pub(crate) mod oauth;
mod probe;
mod probe_redaction;
mod probe_stores;
pub(crate) mod progress;
pub(crate) mod prompt_command;
mod reload_tool;
pub(crate) mod report;
pub(crate) mod result;
pub(crate) mod roots;
pub(crate) mod secret_tool;
pub(crate) mod secrets;
pub(crate) mod session;
mod sightings;
mod stdio_watch;
mod tool;
pub(crate) mod validate;

pub(crate) use catalog::{
    McpCatalog, McpCatalogError, McpCompletionSupport, McpResource, McpResourceContent,
};
pub(crate) use elicitation::McpElicitationSupport;
pub(crate) use oauth::McpAuthorizationMode;
pub(crate) use report::{
    McpLoadMode, McpServerReport, McpServerStatus, McpSessionReport, McpSessionSummary,
    McpToolReport, McpTransportSummary,
};
pub(crate) use roots::McpRoots;
pub(crate) use validate::{
    parse_remote_url, parse_remote_url_with, validate_environment_header_names, validate_identity,
    validate_literal_headers, validate_oauth_client, validate_secret_header_names,
    validate_secret_name, validate_stdio_environment, McpHttpSecurity,
};

pub(crate) use bundle::{McpBundle, McpReload, McpReloadChanges};
pub(crate) use host::{McpChanges, McpDiscovery, McpHost, McpReloadError};
pub(crate) use probe::{probe, McpProbeSecrets, McpProbeStoredSecrets, McpProbeTokens};
pub(crate) use reload_tool::McpReloadBundle;
pub(crate) use secret_tool::McpSecretBundle;
pub(crate) use sightings::McpSightings;

/// Whether a session's host shows a person a masked prompt for an MCP
/// server's secret and stores what they type in its own credential store,
/// as the daemon does for a client that declares it. Gives a session that
/// reloads its servers the `mcp_request_secret` tool.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum McpSecretAsks {
    Available,
    #[default]
    Unavailable,
}

/// Whether this session should connect MCP servers or only inventory config.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum McpSessionPlan {
    /// Native runtime with tools: connect enabled servers.
    Connect,
    /// Emit config inventory without starting transports.
    Inventory(McpLoadMode),
}

/// Session-scoped inputs every connected server shares.
///
/// The two server-to-client services default to off, so a caller that cannot
/// serve them, such as the `rho mcp` inventory pass, gets the safe shape without
/// saying anything. Every caller names the session environment servers start
/// in, so none falls back to this process's by omission (#1659).
#[derive(Clone)]
pub(crate) struct McpSessionOptions {
    pub(crate) max_output_bytes: usize,
    /// Filesystem roots advertised through `roots/list`.
    pub(crate) roots: McpRoots,
    /// Whether a server that needs OAuth may open a browser login.
    pub(crate) authorization: McpAuthorizationMode,
    services: session::McpSessionServices,
    /// The session's environment: servers start in, and read `env_from_env`
    /// and `headers_from_env` from, the one current when they connect, and
    /// each tool call sends the caller context current when it runs.
    environment: SessionEnvironment,
    /// Where servers' `env_from_secret` and `headers_from_secret` values are
    /// stored ([`secrets`]): this process's own store, whatever store the
    /// session's client chose.
    secrets: Arc<dyn rho_providers::credentials::CredentialStore>,
    /// Where servers' OAuth tokens are read and saved: the session
    /// environment's store, unless a probe of a draft keeps its writes apart.
    oauth_tokens: Option<Arc<dyn rho_providers::credentials::CredentialStore>>,
    /// Where each server's start is recorded for `rho/mcp/list`: this
    /// process's book.
    sightings: McpSightings,
}

impl std::fmt::Debug for McpSessionOptions {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("McpSessionOptions")
            .field("max_output_bytes", &self.max_output_bytes)
            .field("roots", &self.roots)
            .field("authorization", &self.authorization)
            .field("services", &self.services)
            .field("environment", &self.environment)
            .finish_non_exhaustive()
    }
}

impl McpSessionOptions {
    /// Options for servers of a session whose environment is `environment`:
    /// a session's, or this process's for a caller without one.
    pub(crate) fn new(
        max_output_bytes: usize,
        roots: McpRoots,
        authorization: McpAuthorizationMode,
        environment: SessionEnvironment,
    ) -> Self {
        Self {
            max_output_bytes: max_output_bytes.max(1),
            roots,
            authorization,
            services: session::McpSessionServices {
                elicitation: McpElicitationSupport::Unavailable,
            },
            environment,
            secrets: Arc::new(crate::credential_store::UntrackedCredentialStore),
            oauth_tokens: None,
            sightings: McpSightings::process(),
        }
    }

    /// Read stored secrets from `store` instead of this process's own.
    pub(crate) fn with_secret_store(
        mut self,
        store: Arc<dyn rho_providers::credentials::CredentialStore>,
    ) -> Self {
        self.secrets = store;
        self
    }

    /// Read and save servers' OAuth tokens in `store` instead of the
    /// session environment's.
    fn with_oauth_token_store(
        mut self,
        store: Arc<dyn rho_providers::credentials::CredentialStore>,
    ) -> Self {
        self.oauth_tokens = Some(store);
        self
    }

    /// Where servers' OAuth tokens are read and saved.
    fn oauth_tokens(&self) -> Arc<dyn rho_providers::credentials::CredentialStore> {
        self.oauth_tokens
            .clone()
            .unwrap_or_else(|| self.environment.untracked_credentials())
    }

    /// Declare that this run can put a server's question in front of a person.
    pub(crate) fn with_elicitation(mut self, support: McpElicitationSupport) -> Self {
        self.services.elicitation = support;
        self
    }
}

pub(crate) struct McpConnectOutcome {
    pub(crate) report: McpSessionReport,
    pub(crate) bundle: Option<McpBundle>,
    /// Prompts and resources the interactive host can offer. Empty unless
    /// servers connected and declared them.
    pub(crate) catalog: McpCatalog,
}

impl McpConnectOutcome {
    /// Run the session plan against config: connect or inventory-only.
    pub(crate) async fn run(
        plan: McpSessionPlan,
        config: &McpConfig,
        options: McpSessionOptions,
    ) -> Self {
        match plan {
            McpSessionPlan::Connect => McpBundle::connect(config, options).await,
            McpSessionPlan::Inventory(mode) => Self {
                report: McpSessionReport::from_config_unloaded(config, mode),
                bundle: None,
                catalog: McpCatalog::default(),
            },
        }
    }
}

#[cfg(test)]
static MCP_RUNTIME_CONSTRUCTIONS: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Held by tests that start servers, so one reading
/// [`MCP_RUNTIME_CONSTRUCTIONS`] sees no other test's starts.
#[cfg(test)]
static MCP_CONNECT_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

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