use std::sync::Arc;
use rmcp::{
model::{
CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation,
ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool,
ToolAnnotations,
},
service::RequestContext,
ErrorData, RoleServer, ServerHandler, ServiceExt,
};
use rho_protocol::ClientEnvironment;
use super::session_control::{Action, Caller, Grant, SessionControl};
use crate::caller_context::{Access, CallerContext};
mod http_server;
pub(crate) mod token_store;
pub(crate) mod tokens;
pub(super) use http_server::{serve_http, HttpOptions};
const INSTRUCTIONS: &str = "Start, drive, and follow rho agent sessions through the rho daemon. \
`new` starts a session in a workspace with a first prompt; `wait` follows its turn until it \
ends, returning a cursor to call again while `done` is false; `read` pages through a \
transcript. A turn that needs an approval or an answer waits for a person in rho: no tool \
here can answer it.";
#[derive(Clone)]
pub(super) struct SessionTools {
control: Arc<SessionControl>,
transport: Transport,
environment: ClientEnvironment,
}
#[derive(Clone)]
enum Transport {
Stdio {
grant: Grant,
context: CallerContext,
},
Http,
}
impl SessionTools {
fn caller(&self, context: &RequestContext<RoleServer>) -> Result<Caller, ErrorData> {
let sent = CallerContext::from_meta(&context.meta)
.map_err(|error| ErrorData::invalid_params(format!("{error:#}"), None))?;
let (grant, default) = match &self.transport {
Transport::Stdio { grant, context } => (grant.clone(), context.clone()),
Transport::Http => {
let grant = context
.extensions
.get::<::http::request::Parts>()
.and_then(|parts| parts.extensions.get::<Grant>())
.cloned()
.ok_or_else(|| {
ErrorData::invalid_request("the request carries no token", None)
})?;
(grant, CallerContext::ROOT)
}
};
Ok(Caller::new(
grant,
&sent.unwrap_or(default),
self.environment.clone(),
))
}
}
impl ServerHandler for SessionTools {
fn get_info(&self) -> ServerConfig {
let capabilities = ServerCapabilities::builder()
.enable_tools()
.enable_experimental_with(CallerContext::capability())
.build();
ServerConfig::new(capabilities)
.with_server_info(Implementation::new("rho", env!("CARGO_PKG_VERSION")))
.with_instructions(INSTRUCTIONS)
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult::with_all_items(
Action::ALL.into_iter().map(tool).collect(),
))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let Some(action) = Action::from_name(&request.name) else {
return Err(ErrorData::invalid_params(
format!("no tool named {:?}", request.name),
None,
));
};
let caller = self.caller(&context)?;
let arguments = request.arguments.unwrap_or_default();
let result = match self.control.call(&caller, action, arguments).await {
Ok(value) => {
let text = serde_json::to_string_pretty(&value)
.map_err(|error| ErrorData::internal_error(error.to_string(), None))?;
CallToolResult::success(vec![ContentBlock::text(text)])
}
Err(error) => CallToolResult::error(vec![ContentBlock::text(error.to_string())]),
};
Ok(result.into())
}
}
fn tool(action: Action) -> Tool {
let annotations =
ToolAnnotations::with_title(action.name()).read_only(action.needs() == Access::Read);
Tool::new(action.name(), action.description(), action.input_schema())
.with_annotations(annotations)
}
pub(super) async fn serve_stdio(
control: Arc<SessionControl>,
access: Access,
context: CallerContext,
environment: ClientEnvironment,
) -> anyhow::Result<()> {
let tools = SessionTools {
control,
transport: Transport::Stdio {
grant: Grant::local(access),
context,
},
environment,
};
let running = tools.serve(rmcp::transport::stdio()).await?;
running.waiting().await?;
Ok(())
}