rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Secrets an MCP server reads from the credential store of the process that
//! runs it (#2103): `env_from_secret` for a stdio server's variables and
//! `headers_from_secret` for a Streamable HTTP server's headers.
//!
//! The store is this process's own, never one a daemon client chose: the
//! server runs on this machine, whichever machine the client is on. Each
//! secret belongs to one server identity, so a server reads only the secrets
//! stored for it, and is read when the server connects, so storing one takes
//! effect at the next connect without restarting anything.

use std::{collections::BTreeMap, sync::Arc};

use anyhow::Context;
use rho_providers::credentials::CredentialStore;

use super::{validate_identity, validate_secret_name};

/// Namespace for stored MCP secrets inside Rho's credential-store account
/// space, beside `mcp-oauth` ([`super::oauth`]).
const ACCOUNT_PREFIX: &str = "mcp-secret";

/// The account holding secret `name` of server `identity`. Neither may hold
/// `:`, so no two pairs share an account.
pub(super) fn account_name(identity: &str, name: &str) -> String {
    format!("{ACCOUNT_PREFIX}:{identity}:{name}")
}

/// What a server's stored secrets resolved to when it connects.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum StoredSecrets {
    /// Every secret it names, by name.
    Ready(BTreeMap<String, String>),
    /// The names it lists that hold no value, in config order.
    Missing(Vec<String>),
}

/// Reads the secrets `names` of server `identity` from `store`, off the async
/// workers, since an OS keyring may block its reader. The read runs on a
/// detached thread rather than tokio's blocking pool, whose threads a
/// runtime waits for as it shuts down: a store that never answers would hold
/// a CLI's exit after its caller gave up waiting.
pub(crate) async fn resolve(
    store: Arc<dyn CredentialStore>,
    identity: &str,
    names: &[String],
) -> anyhow::Result<StoredSecrets> {
    if names.is_empty() {
        return Ok(StoredSecrets::Ready(BTreeMap::new()));
    }
    let identity = identity.to_owned();
    let names = names.to_vec();
    let (answer, answered) = tokio::sync::oneshot::channel();
    let read = move || -> anyhow::Result<StoredSecrets> {
        let mut values = BTreeMap::new();
        let mut missing = Vec::new();
        for name in names {
            // Fresh, so a value another process stored is seen at once.
            match store
                .get_secret_fresh(&account_name(&identity, &name))
                .with_context(|| format!("could not read MCP secret `{name}` of `{identity}`"))?
            {
                Some(value) => {
                    values.insert(name, value);
                }
                None => missing.push(name),
            }
        }
        Ok(if missing.is_empty() {
            StoredSecrets::Ready(values)
        } else {
            StoredSecrets::Missing(missing)
        })
    };
    std::thread::Builder::new()
        .name("rho-mcp-secrets".into())
        .spawn(move || {
            let _ = answer.send(read());
        })
        .context("could not start the MCP secret reader")?;
    answered.await.context("MCP secret lookup panicked")?
}

/// Stores `value` as secret `name` of server `identity`, replacing any.
/// Blocks on an OS keyring; call it off the async workers.
pub(crate) fn store(
    store: &dyn CredentialStore,
    identity: &str,
    name: &str,
    value: &str,
) -> anyhow::Result<()> {
    validate_identity(identity)?;
    validate_secret_name(name)?;
    if value.is_empty() {
        anyhow::bail!("MCP secret `{name}` must not be empty");
    }
    store
        .set_secret(&account_name(identity, name), value)
        .with_context(|| format!("could not store MCP secret `{name}` of `{identity}`"))
}

/// Deletes secret `name` of server `identity`, and says whether one was
/// stored. Blocks on an OS keyring; call it off the async workers.
pub(crate) fn delete(
    store: &dyn CredentialStore,
    identity: &str,
    name: &str,
) -> anyhow::Result<bool> {
    validate_identity(identity)?;
    validate_secret_name(name)?;
    store
        .delete_secret(&account_name(identity, name))
        .with_context(|| format!("could not delete MCP secret `{name}` of `{identity}`"))
}

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