use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use futures_util::future::join_all;
use rho_protocol::SessionId;
use serde_json::{Map, Value};
use super::{token_store, tool::ServedTool};
use crate::{
app::session_control::{Action, Caller, ControlError, DaemonUse, SessionControl, WaitResult},
caller_context::{CallerContext, Scope, Workspaces},
};
mod client;
mod store;
pub(crate) use client::{call, wait, Asked, Lasts, RemoteError, CALL_TIMEOUT, FORWARDED, LASTING};
pub(crate) use store::{check_name, check_url, Remote, RemoteSet};
const SERVER: &str = "server";
#[derive(Debug, thiserror::Error)]
pub(crate) enum RouteError {
#[error("{0}")]
Server(String),
#[error(transparent)]
Control(#[from] ControlError),
#[error(transparent)]
Remote(#[from] RemoteError),
}
impl RouteError {
pub(crate) fn lasts(&self) -> Lasts {
match self {
Self::Server(_) => Lasts::ForGood,
Self::Control(error) => control_lasts(error),
Self::Remote(RemoteError::Failed { lasts, .. }) => *lasts,
Self::Remote(RemoteError::Unreachable { .. } | RemoteError::Refused { .. }) => {
Lasts::ForNow
}
}
}
}
pub(crate) fn control_lasts(error: &ControlError) -> Lasts {
if error.is_unknown_session() {
return Lasts::ForGood;
}
match error {
ControlError::Refused(_) => Lasts::ForGood,
ControlError::UnknownSession(_)
| ControlError::Invalid(_)
| ControlError::NotSteerable(_)
| ControlError::Daemon(_) => Lasts::ForNow,
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Target {
Local,
Remote(Remote),
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Route {
One(Target),
Every,
}
impl Target {
pub(crate) async fn call(
&self,
control: &SessionControl,
caller: &Caller,
action: Action,
arguments: Map<String, Value>,
) -> Result<Value, RouteError> {
match self {
Self::Local => Ok(control.call(caller, action, arguments).await?),
Self::Remote(remote) => {
caller.grant.permit(action).map_err(ControlError::from)?;
let arguments = for_any_release(action, arguments)?;
Ok(call(remote, action, arguments, &forwarded(caller), Asked::ByCall).await?)
}
}
}
pub(crate) async fn check_follow(
&self,
control: &SessionControl,
caller: &Caller,
session: &SessionId,
) -> Result<(), RouteError> {
match self {
Self::Local => Ok(control
.check_follow(caller, session, DaemonUse::Call)
.await?),
Self::Remote(_) => Ok(caller
.grant
.permit(Action::Wait)
.map_err(ControlError::from)?),
}
}
pub(crate) async fn now(
&self,
control: &SessionControl,
caller: &Caller,
session: &SessionId,
) -> Result<WaitResult, RouteError> {
match self {
Self::Local => Ok(control.now(session).await?),
Self::Remote(remote) => {
Ok(wait(
remote,
session,
0,
None,
&forwarded(caller),
Asked::ByCall,
)
.await?)
}
}
}
pub(crate) fn remote_name(&self) -> Option<&str> {
match self {
Self::Local => None,
Self::Remote(remote) => Some(&remote.name),
}
}
}
fn for_any_release(
action: Action,
mut arguments: Map<String, Value>,
) -> Result<Map<String, Value>, ControlError> {
match action {
Action::Prompt | Action::Steer => {
action.check_arguments(&arguments)?;
if let Some(message) = arguments.remove("prompt") {
arguments.insert("text".to_owned(), message);
}
}
Action::List
| Action::Read
| Action::New
| Action::Cancel
| Action::Wait
| Action::Answer => {}
}
Ok(arguments)
}
fn forwarded(caller: &Caller) -> CallerContext {
CallerContext {
depth: caller.depth,
scope: Scope {
access: caller.grant.scope.access,
workspaces: Workspaces::Any,
},
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Arrival {
Direct,
Forwarded(Asked),
}
impl Arrival {
pub(crate) fn of(meta: &Map<String, Value>) -> Self {
meta.get(FORWARDED)
.and_then(Value::as_str)
.and_then(Asked::from_name)
.map_or(Self::Direct, Self::Forwarded)
}
}
#[derive(Clone, Debug)]
pub(crate) struct Servers {
local: String,
warned: Arc<AtomicBool>,
}
impl Servers {
pub(crate) fn new(local: String) -> Self {
Self {
local,
warned: Arc::default(),
}
}
pub(crate) async fn load(&self, arrival: Arrival) -> Machines {
let remotes = match arrival {
Arrival::Forwarded(_) => Ok(RemoteSet::default()),
Arrival::Direct => token_store::load_fresh::<RemoteSet>()
.await
.map_err(|error| {
let error = format!("{error:#}");
if !self.warned.swap(true, Ordering::Relaxed) {
tracing::warn!(%error, "could not read the MCP server remotes; serving this machine only");
}
error
}),
};
Machines {
local: self.local.clone(),
remotes,
}
}
}
#[derive(Debug)]
pub(crate) struct Machines {
local: String,
remotes: Result<RemoteSet, String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Naming {
One,
Every,
Here,
}
impl Naming {
fn of(tool: ServedTool) -> Self {
match tool {
ServedTool::Core(Action::List) => Self::Every,
ServedTool::Unwatch => Self::Here,
ServedTool::Core(
Action::Read
| Action::New
| Action::Prompt
| Action::Steer
| Action::Cancel
| Action::Wait
| Action::Answer,
)
| ServedTool::Watch => Self::One,
}
}
}
impl Machines {
fn remotes(&self) -> &[Remote] {
self.remotes
.as_ref()
.map_or(&[], |remotes| remotes.remotes.as_slice())
}
pub(crate) fn is_hub(&self) -> bool {
!self.remotes().is_empty()
}
pub(crate) fn route(
&self,
tool: ServedTool,
arguments: &mut Map<String, Value>,
) -> Result<Route, RouteError> {
let name_of_tool = tool.name();
let named = match arguments.remove(SERVER) {
None | Some(Value::Null) => None,
Some(Value::String(name)) => Some(name),
Some(other) => {
return Err(RouteError::Server(format!(
"invalid `{name_of_tool}` arguments: `{SERVER}` is a server name, not {other}"
)))
}
};
let Some(name) = named else {
return match (self.is_hub(), Naming::of(tool)) {
(false, _) | (true, Naming::Here) => Ok(Route::One(Target::Local)),
(true, Naming::Every) => Ok(Route::Every),
(true, Naming::One) => Err(RouteError::Server(format!(
"`{name_of_tool}` needs `{SERVER}`, the machine to act on: one of {}",
self.names().join(", ")
))),
};
};
if name == self.local {
if self
.remotes
.as_ref()
.is_ok_and(|remotes| remotes.get(&name).is_some())
{
return Err(RouteError::Server(format!(
"remote {name:?} has this server's own name, so `{SERVER}` cannot tell them apart; rename the remote with `rho mcp remote add`"
)));
}
return Ok(Route::One(Target::Local));
}
match (
&self.remotes,
self.remotes().iter().find(|remote| remote.name == name),
) {
(_, Some(remote)) => Ok(Route::One(Target::Remote(remote.clone()))),
(Err(error), None) => Err(RouteError::Server(format!(
"could not read this server's remotes, so it cannot reach server {name:?}: {error}"
))),
(Ok(_), None) => Err(RouteError::Server(format!(
"no server {name:?}; servers: {}",
self.names().join(", ")
))),
}
}
fn names(&self) -> Vec<&str> {
let mut names = vec![self.local.as_str()];
for remote in self.remotes() {
if !names.contains(&remote.name.as_str()) {
names.push(&remote.name);
}
}
names
}
pub(crate) fn with_server(
&self,
tool: ServedTool,
mut schema: Map<String, Value>,
) -> Map<String, Value> {
if !self.is_hub() {
return schema;
}
let naming = Naming::of(tool);
let description = match naming {
Naming::One => {
"The machine the session is on, or to start it on. Webhook news names it as `server`."
}
Naming::Every => "The machine whose sessions to list; omit it to list every machine's.",
Naming::Here => "The machine the session is on; this server keeps every watch alike.",
};
if let Some(Value::Object(properties)) = schema.get_mut("properties") {
properties.insert(
SERVER.to_owned(),
serde_json::json!({
"type": "string",
"enum": self.names(),
"description": description,
}),
);
}
if naming == Naming::One {
match schema.get_mut("required") {
Some(Value::Array(required)) => required.push(Value::from(SERVER)),
_ => {
schema.insert("required".to_owned(), serde_json::json!([SERVER]));
}
}
}
schema
}
pub(crate) async fn list_every(
&self,
control: &SessionControl,
caller: &Caller,
arguments: Map<String, Value>,
) -> Value {
let targets: Vec<(&str, Target)> = std::iter::once((self.local.as_str(), Target::Local))
.chain(
self.remotes()
.iter()
.map(|remote| (remote.name.as_str(), Target::Remote(remote.clone()))),
)
.collect();
let lists = join_all(
targets
.iter()
.map(|(_, target)| target.call(control, caller, Action::List, arguments.clone())),
)
.await;
let servers = targets
.iter()
.zip(lists)
.map(|((name, _), listed)| {
let mut entry = Map::from_iter([(SERVER.to_owned(), Value::from(*name))]);
match listed {
Ok(Value::Object(listed)) => entry.extend(listed),
Ok(other) => {
entry.insert(
"error".to_owned(),
Value::from(format!(
"`list` answered something other than an object: {other}"
)),
);
}
Err(error) => {
entry.insert("error".to_owned(), Value::from(error.to_string()));
}
}
Value::Object(entry)
})
.collect();
serde_json::json!({ "servers": Value::Array(servers) })
}
pub(crate) fn name_of<'a>(&'a self, target: &'a Target) -> &'a str {
target.remote_name().unwrap_or(&self.local)
}
pub(crate) fn stamp(&self, result: &mut Value, target: &Target, tool: ServedTool) {
if !self.is_hub() || Naming::of(tool) == Naming::Here {
return;
}
if let Value::Object(result) = result {
result.insert(SERVER.to_owned(), Value::from(self.name_of(target)));
}
}
}
#[cfg(test)]
#[path = "mod_tests.rs"]
mod tests;