1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! 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;