use std::sync::Arc;
use rho_sdk::{
model::ToolSpec,
tool::{
Tool, ToolContext, ToolError, ToolErrorKind, ToolFuture, ToolInvocation, ToolOutput,
ToolSecurity,
},
ToolCallId,
};
use serde::Deserialize;
use serde_json::json;
use tokio::sync::{mpsc, oneshot};
use super::{config::McpTransport, validate_identity, validate_secret_name, McpHost};
use crate::tools::{code_mode::ContextExposure, sdk_registry::ToolBundle};
pub(crate) const TOOL_NAME: &str = "mcp_request_secret";
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SecretRequest {
pub(crate) call_id: ToolCallId,
pub(crate) server: String,
pub(crate) name: String,
pub(crate) reason: Option<String>,
pub(crate) destination: rho_protocol::SecretDestination,
}
pub(crate) struct PendingSecret {
pub(crate) request: SecretRequest,
pub(crate) reply: oneshot::Sender<SecretOutcome>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SecretOutcome {
Stored,
Declined,
}
pub(crate) type SecretRequestSender = mpsc::UnboundedSender<PendingSecret>;
pub(crate) type SecretRequestReceiver = mpsc::UnboundedReceiver<PendingSecret>;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Arguments {
server: String,
name: String,
#[serde(default)]
reason: Option<String>,
}
struct McpSecretTool {
host: McpHost,
requests: SecretRequestSender,
}
impl Tool for McpSecretTool {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: TOOL_NAME.into(),
description: "Ask the user to type a secret, such as an API key, that an MCP server \
in config reads. `name` must be listed in the server's \
`env_from_secret` (stdio) or `headers_from_secret` (HTTP); add it \
there first. The user types it into a masked prompt and Rho stores it \
in its credential store; you never see the value. Never ask the user \
to paste a secret into the conversation. Once stored, call mcp_reload \
to start the server with it."
.into(),
input_schema: json!({
"type": "object",
"properties": {
"server": {"type": "string", "description": "The server's id in [mcp.servers]"},
"name": {"type": "string", "description": "The variable or header the server reads it as"},
"reason": {"type": "string", "description": "One short line for the user: what the secret is and where to get it"},
},
"required": ["server", "name"],
"additionalProperties": false,
}),
}
}
fn security(&self) -> ToolSecurity {
ToolSecurity::built_in([])
}
fn call<'a>(&'a self, invocation: ToolInvocation, context: ToolContext) -> ToolFuture<'a> {
Box::pin(async move {
let call_id = invocation.id().clone();
let Arguments {
server,
name,
reason,
} = serde_json::from_value(invocation.into_arguments())
.map_err(|error| invalid(error.to_string()))?;
validate_identity(&server)
.and_then(|()| validate_secret_name(&name))
.map_err(|error| invalid(format!("{error:#}")))?;
let destination = self.destination(&server, &name)?;
let (reply, outcome) = oneshot::channel();
self.requests
.send(PendingSecret {
request: SecretRequest {
call_id,
server: server.clone(),
name: name.clone(),
reason: reason.filter(|reason| !reason.trim().is_empty()),
destination,
},
reply,
})
.map_err(|_| execution("this session's host cannot ask for secrets"))?;
let outcome = tokio::select! {
biased;
() = context.cancellation().cancelled() => return Err(ToolError::cancelled()),
outcome = outcome => outcome.map_err(|_| ToolError::cancelled())?,
};
match outcome {
SecretOutcome::Stored => Ok(ToolOutput::text(format!(
"stored {name} for {server}; call mcp_reload to start the server with it"
))),
SecretOutcome::Declined => Ok(ToolOutput::text(format!(
"the user declined to give {name} for {server}, or their client cannot ask \
for secrets; they can store it with `rho mcp secret set {server} {name}`"
))),
}
})
}
}
impl McpSecretTool {
fn destination(
&self,
server: &str,
name: &str,
) -> Result<rho_protocol::SecretDestination, ToolError> {
let servers = self
.host
.configured_servers()
.map_err(|error| execution(error.to_string()))?;
let Some(config) = servers.servers.get(server) else {
return Err(invalid(format!(
"no MCP server `{server}` is configured; add [mcp.servers.{server}] first"
)));
};
if !config
.transport
.secret_names()
.iter()
.any(|listed| listed == name)
{
return Err(invalid(format!(
"server `{server}` reads no stored secret `{name}`; list it in env_from_secret \
(stdio) or headers_from_secret (HTTP) first"
)));
}
Ok(match &config.transport {
McpTransport::Stdio { command, args, .. } => rho_protocol::SecretDestination::Process {
command: command.clone(),
args: args.clone(),
},
McpTransport::StreamableHttp { url, .. } => {
rho_protocol::SecretDestination::Http { url: url.clone() }
}
})
}
}
fn invalid(message: impl Into<String>) -> ToolError {
ToolError::new(ToolErrorKind::InvalidArguments, message.into())
}
fn execution(message: impl Into<String>) -> ToolError {
ToolError::new(ToolErrorKind::Execution, message.into())
}
pub(crate) struct McpSecretBundle {
tools: Vec<Arc<dyn Tool>>,
}
impl McpSecretBundle {
pub(crate) fn new(host: McpHost, requests: SecretRequestSender) -> Self {
Self {
tools: vec![Arc::new(McpSecretTool { host, requests })],
}
}
}
impl ToolBundle for McpSecretBundle {
fn tools(&self) -> &[Arc<dyn Tool>] {
&self.tools
}
fn context_exposure(&self) -> ContextExposure {
ContextExposure::Hidden
}
}