use std::sync::Arc;
use rho_sdk::{
model::ToolSpec,
tool::{
Tool, ToolContext, ToolError, ToolErrorKind, ToolFuture, ToolInvocation, ToolOutput,
ToolSecurity,
},
};
use serde_json::json;
use super::{McpHost, McpReloadChanges, McpSecretAsks, McpServerStatus, McpSessionReport};
use crate::tools::{code_mode::ContextExposure, sdk_registry::ToolBundle};
pub(crate) const TOOL_NAME: &str = "mcp_reload";
struct McpReloadTool {
host: McpHost,
}
impl Tool for McpReloadTool {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: TOOL_NAME.into(),
description: "Reload this session's MCP servers from the config file as it is now, \
after you add, edit, enable, or disable a server, or after the user \
stores a secret one needs. Servers whose config, variables, and \
secrets are unchanged keep running; the rest start, restart, or stop. \
Returns what it did and each started server's status or error. A \
started server's tools become callable from the session's next turn, \
not this one."
.into(),
input_schema: json!({
"type": "object",
"properties": {},
"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 (changes, report) = self
.host
.reload_from_config()
.await
.map_err(|error| ToolError::new(ToolErrorKind::Execution, error.to_string()))?;
Ok(ToolOutput::text(reloaded_text(
&changes,
&report,
self.host.secret_asks(),
)))
})
}
}
fn reloaded_text(
changes: &McpReloadChanges,
report: &McpSessionReport,
secret_asks: McpSecretAsks,
) -> String {
let McpReloadChanges {
kept,
started,
stopped,
} = changes;
if started.is_empty() && stopped.is_empty() {
return if kept.is_empty() {
"no MCP servers are configured".to_owned()
} else {
format!("nothing changed; kept {}", kept.join(", "))
};
}
let mut lines = Vec::new();
for identity in started {
lines.push(match report.find(identity) {
Some(server) => started_line(identity, server),
None => format!("- {identity}: started"),
});
}
if !stopped.is_empty() {
lines.push(format!("stopped: {}", stopped.join(", ")));
}
if !kept.is_empty() {
lines.push(format!("kept: {}", kept.join(", ")));
}
if started.iter().any(|identity| {
report
.find(identity)
.is_some_and(|server| server.status() == McpServerStatus::Connected)
}) {
lines.push(
"The started servers' tools are callable from the session's next turn; find them \
with tool_search then."
.to_owned(),
);
}
if started.iter().any(|identity| {
report
.find(identity)
.is_some_and(|server| server.status() == McpServerStatus::NeedsSecret)
}) {
lines.push(
match secret_asks {
McpSecretAsks::Available => {
"A server that needs a secret starts once it is stored: ask the user for it \
with mcp_request_secret (find it with tool_search), then call mcp_reload \
again."
}
McpSecretAsks::Unavailable => {
"A server that needs a secret starts once it is stored: have the user run \
`rho mcp secret set <server> <NAME>`, then call mcp_reload again."
}
}
.to_owned(),
);
}
lines.join("\n")
}
fn started_line(identity: &str, server: &super::McpServerReport) -> String {
let status = server.status();
match (status, server.error()) {
(McpServerStatus::Connected, _) => {
format!("- {identity}: connected, {} tools", server.tool_count())
}
(_, Some(error)) => format!("- {identity}: {}: {error}", status.as_str()),
(_, None) => format!("- {identity}: {}", status.as_str()),
}
}
pub(crate) struct McpReloadBundle {
tools: Vec<Arc<dyn Tool>>,
}
impl McpReloadBundle {
pub(crate) fn new(host: McpHost) -> Self {
Self {
tools: vec![Arc::new(McpReloadTool { host })],
}
}
}
impl ToolBundle for McpReloadBundle {
fn tools(&self) -> &[Arc<dyn Tool>] {
&self.tools
}
fn context_exposure(&self) -> ContextExposure {
ContextExposure::Hidden
}
}