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
//! Tool sources a session loads after it opens (see
//! [`crate::app::tools_prompt::ToolSourceLoad::Deferred`]): until they
//! attach, the session's MCP inventory reads `connecting` and its prompts
//! wait at [`SessionRuntime::begin_prompt`]. A reload reconciles its MCP
//! servers with config again later ([`SessionRuntime::reload_mcp`]).
use std::future::Future;
use rho_sdk::SystemPrompt;
use super::{model_scoped_config, SessionRuntime};
use crate::{
app::{
conversation_switch::replace_system_prompt,
tools_prompt::{DeferredToolSources, PendingToolSources},
},
config::Config,
model_identity::PromptModel,
tools::mcp::{config::McpConfig, McpConnectOutcome, McpReloadChanges, McpReloadError},
};
/// Why a session's MCP servers were not reloaded.
#[derive(Debug, thiserror::Error)]
pub(crate) enum SessionMcpReloadError {
#[error("the session's MCP servers are still connecting; reload once they finish")]
StillConnecting,
#[error(transparent)]
Reload(#[from] McpReloadError),
}
impl SessionRuntime {
/// Resolves once the session's deferred tool sources finished loading;
/// `None` when none are loading. It borrows nothing, so a host can wait
/// for it without holding the session.
pub(crate) fn tool_sources_loaded(&self) -> Option<impl Future<Output = ()> + Send + 'static> {
match self.built.tool_sources.as_ref()? {
PendingToolSources::Loading(sources) => Some(sources.loaded()),
PendingToolSources::Unbound => None,
}
}
/// Reads `true` once the session's deferred tool sources finished
/// loading, which is when its prompts stop waiting for them; `None`
/// when none are loading.
pub(crate) fn tool_sources_progress(&self) -> Option<tokio::sync::watch::Receiver<bool>> {
match self.built.tool_sources.as_ref()? {
PendingToolSources::Loading(sources) => Some(sources.progress()),
PendingToolSources::Unbound => None,
}
}
/// Attaches the deferred tool sources once they finished loading and
/// rebuilds the runtime with them, and says whether it did. Until they
/// loaded, and once the runtime runs with them, it does nothing.
///
/// The system prompt is rendered again with them, as opening renders
/// it when they load inline: a reopened session's saved prompt was
/// already replaced at opening, and they attach before the first model
/// request of each opening (prompts wait for them), so no request has
/// cached the prompt they replace.
///
/// On error the tools stay attached and the runtime keeps the list it
/// had; the next call tries the rebuild again.
pub(crate) async fn attach_loaded_tool_sources(
&mut self,
process_config: &Config,
) -> anyhow::Result<bool> {
// What an `mcp_reload` tool call changed during the last turn joins
// the tool set now.
if !matches!(
self.built.tool_sources,
Some(PendingToolSources::Loading(_))
) && self.built.tools.take_mcp_changes()
{
self.built.tool_sources = Some(PendingToolSources::Unbound);
}
match self.built.tool_sources.take() {
None => return Ok(false),
Some(PendingToolSources::Loading(sources)) if !sources.is_loaded() => {
self.built.tool_sources = Some(PendingToolSources::Loading(sources));
return Ok(false);
}
Some(PendingToolSources::Loading(sources)) => self.attach(sources).await,
Some(PendingToolSources::Unbound) => {}
}
if let Err(error) = self.bind_tool_sources(process_config).await {
self.built.tool_sources = Some(PendingToolSources::Unbound);
return Err(error);
}
Ok(true)
}
/// Reconciles the session's MCP servers with `servers`, the config's
/// `[mcp]` as it is now (see [`crate::tools::mcp::McpHost::reload`]).
/// When any started or stopped, the system prompt, which names the
/// servers, is rendered again and the runtime rebuilt on
/// `process_config` with the new tool list, so a host calls this
/// between turns. A rebuild that fails leaves the tools pending, as a
/// failed attach does, for the next prompt to bind; the servers changed
/// all the same.
pub(crate) async fn reload_mcp(
&mut self,
servers: &McpConfig,
process_config: &Config,
) -> Result<McpReloadChanges, SessionMcpReloadError> {
// Sources that finished loading attach first, so the reload starts
// from the servers they connected.
self.bind_pending_mcp_tools(process_config).await;
if matches!(
self.built.tool_sources,
Some(PendingToolSources::Loading(_))
) {
return Err(SessionMcpReloadError::StillConnecting);
}
let (changes, _) = self.built.tools.mcp_host().reload(servers).await?;
self.bind_pending_mcp_tools(process_config).await;
Ok(changes)
}
/// Binds tool sources that wait to be, logging a failure, which leaves
/// them waiting for the next prompt to try again.
async fn bind_pending_mcp_tools(&mut self, process_config: &Config) {
if let Err(error) = self.attach_loaded_tool_sources(process_config).await {
tracing::warn!(error = %format!("{error:#}"), "could not rebuild the session on its MCP tools; its next prompt tries again");
}
}
/// Puts what `sources` loaded into the session's tool set.
async fn attach(&mut self, sources: DeferredToolSources) {
match sources.outcome().await {
Ok(outcome) => {
self.built.tools.attach_mcp(outcome.mcp);
self.built.tools.attach_openapi(outcome.openapi);
}
// Say so, or the inventory reads `connecting` until the session ends.
Err(error) => {
let mut report = self.built.tools.mcp_report().clone();
report.fail_connecting(&format!("MCP connect did not finish: {error}"));
self.built.tools.attach_mcp(McpConnectOutcome {
report,
bundle: None,
catalog: Default::default(),
});
}
}
for problem in self
.built
.tools
.openapi_report()
.errors
.iter()
.chain(&self.built.tools.openapi_report().warnings)
{
tracing::warn!("{problem}");
}
}
/// Renders the system prompt with the tool set's sources and rebuilds
/// the runtime on the tool set.
async fn bind_tool_sources(&mut self, process_config: &Config) -> anyhow::Result<()> {
if let Some(template) = self.built.prompt_template.as_mut() {
template.replace_tool_sources(
self.built.tools.mcp_report(),
self.built.tools.openapi_report(),
self.built.tools.ui_tool(),
);
let running = PromptModel::from_sdk_identity(&self.built.provider.identity());
let built = template.render(&running, self.built.prompt.loaded.as_ref());
self.built.prompt.adopt(
crate::app::active_prompt::ActivePrompt::from_prepared(built),
&self.built.diagnostics,
self.built.tools.advisor(),
);
if let SystemPrompt::Custom(text) = &self.built.prompt.system {
replace_system_prompt(&self.built.session, text)?;
}
}
let config = model_scoped_config(&self.current_model(), process_config);
let (mode, writes) = (self.permission.mode, self.permission.writes.clone());
self.rebuild_runtime(&config, mode, writes).await?;
Ok(())
}
}