use std::convert::Infallible;
use std::net::{Ipv4Addr, SocketAddr};
use std::sync::Arc;
use arc_swap::{ArcSwap, ArcSwapOption};
use rmcp::handler::server::tool::{ToolCallContext, ToolRoute, ToolRouter};
use rmcp::model::{
CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, ServerInfo,
};
use rmcp::service::{NotificationContext, Peer, RequestContext};
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::tower::{
StreamableHttpServerConfig, StreamableHttpService,
};
use rmcp::{ErrorData, RoleServer, ServerHandler};
use crate::config::Config;
use crate::tools::Tools;
pub async fn serve<S>(
config: Config,
state: S,
tools: Arc<Tools<S>>,
) -> Result<Infallible, std::io::Error>
where
S: Send + Sync + 'static,
{
let router = Arc::new(ArcSwap::from_pointee(build(&tools.routes())));
let peer: Arc<ArcSwapOption<Peer<RoleServer>>> = Arc::new(ArcSwapOption::empty());
let installed = tools.on_replace({
let (router, peer) = (router.clone(), peer.clone());
move |routes: Arc<Vec<ToolRoute<S>>>| {
router.store(Arc::new(build(&routes)));
if let Some(peer) = peer.load_full() {
tokio::spawn(async move {
let _ = peer.notify_tool_list_changed().await;
});
}
}
});
if !installed {
return Err(std::io::Error::other(
"these Tools are already being served — one server per Tools, \
or the other one would go stale",
));
}
let handler = Handler {
info: Arc::new(server_info(&config)),
state: Arc::new(state),
router,
peer,
};
let mut http = StreamableHttpServerConfig::default();
http.sse_keep_alive = config.sse_keep_alive;
http.stateful_mode = true;
let service = StreamableHttpService::new(
move || Ok(handler.clone()),
Arc::new(LocalSessionManager::default()),
http,
);
let axum_router = axum::Router::new()
.route(
crate::command_executor::COMMAND_PATH,
axum::routing::post(command_response),
)
.fallback_service(service);
let addr = SocketAddr::from((Ipv4Addr::UNSPECIFIED, config.port));
let listener = tokio::net::TcpListener::bind(addr)
.await
.map_err(|e| std::io::Error::new(e.kind(), format!("bind {addr}: {e}")))?;
axum::serve(listener, axum_router).await?;
Err(std::io::Error::other("the listener stopped without an error"))
}
fn server_info(config: &Config) -> ServerInfo {
let mut implementation =
rmcp::model::Implementation::new(config.name.clone(), config.version.clone());
implementation.title = config.title.clone();
implementation.description = config.description.clone();
implementation.website_url = config.website_url.clone();
implementation.icons = config.icons.clone();
let mut tools = rmcp::model::ToolsCapability::default();
tools.list_changed = Some(true);
let mut capabilities = rmcp::model::ServerCapabilities::builder()
.enable_tools_with(tools)
.build();
let mut experimental = std::collections::BTreeMap::new();
experimental.insert(
objectiveai_sdk::mcp::OBJECTIVEAI_CAPABILITY.to_string(),
serde_json::Map::new(),
);
capabilities.experimental = Some(experimental);
let mut info = ServerInfo::default();
info.capabilities = capabilities;
info.server_info = implementation;
info.instructions = config.instructions.clone();
info
}
async fn command_response(
axum::Json(frame): axum::Json<objectiveai_sdk::mcp::CliResponse>,
) -> axum::http::StatusCode {
crate::command_executor::deliver(frame);
axum::http::StatusCode::OK
}
fn build<S: Send + Sync + 'static>(routes: &[ToolRoute<S>]) -> ToolRouter<S> {
let mut router = ToolRouter::new();
for route in routes {
router.add_route(route.clone());
}
router
}
struct Handler<S> {
info: Arc<ServerInfo>,
state: Arc<S>,
router: Arc<ArcSwap<ToolRouter<S>>>,
peer: Arc<ArcSwapOption<Peer<RoleServer>>>,
}
impl<S> Clone for Handler<S> {
fn clone(&self) -> Self {
Self {
info: self.info.clone(),
state: self.state.clone(),
router: self.router.clone(),
peer: self.peer.clone(),
}
}
}
impl<S: Send + Sync + 'static> ServerHandler for Handler<S> {
fn get_info(&self) -> ServerInfo {
(*self.info).clone()
}
async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
self.peer.store(Some(Arc::new(context.peer.clone())));
crate::command_executor::set_peer(context.peer);
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult {
tools: self.router.load().list_all(),
..Default::default()
})
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResult, ErrorData> {
let router = self.router.load_full();
let context = ToolCallContext::new(self.state.as_ref(), request, context);
router.call(context).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use rmcp::model::Tool;
struct Server;
fn route(name: &'static str) -> ToolRoute<Server> {
let schema: Arc<rmcp::model::JsonObject> = Arc::new(Default::default());
ToolRoute::new_dyn(Tool::new(name, "", schema), |_context| {
Box::pin(async { Ok(CallToolResult::success(vec![])) })
})
}
#[test]
fn the_configured_identity_reaches_the_initialize_reply() {
let info = server_info(
&Config::new(1, "hello-channel", "0.1.6")
.with_title("Hello")
.with_instructions("Call greet."),
);
assert_eq!(info.server_info.name, "hello-channel");
assert_eq!(info.server_info.version, "0.1.6");
assert_eq!(info.server_info.title.as_deref(), Some("Hello"));
assert_eq!(info.instructions.as_deref(), Some("Call greet."));
}
#[test]
fn the_objectiveai_capability_is_declared() {
let info = server_info(&Config::new(1, "n", "v"));
let experimental = info.capabilities.experimental.expect("declared");
assert!(experimental.contains_key(objectiveai_sdk::mcp::OBJECTIVEAI_CAPABILITY));
assert_eq!(
info.capabilities.tools.and_then(|t| t.list_changed),
Some(true),
);
}
#[test]
fn bind_address_is_not_loopback() {
let addr = SocketAddr::from((Ipv4Addr::UNSPECIFIED, 8080));
assert!(!addr.ip().is_loopback());
assert_eq!(addr.port(), 8080);
}
#[test]
fn build_routes_by_name() {
let router = build(&[route("alpha"), route("beta")]);
let names: Vec<_> = router.list_all().into_iter().map(|t| t.name).collect();
assert_eq!(names, ["alpha", "beta"]);
assert!(router.get("alpha").is_some());
assert!(router.get("missing").is_none());
}
#[test]
fn a_duplicate_name_keeps_the_last_route() {
let router = build(&[route("alpha"), route("alpha")]);
assert_eq!(router.list_all().len(), 1);
}
#[test]
fn replace_rebuilds_the_live_router() {
let tools = crate::tools::Tools::new([route("alpha")]);
let router = Arc::new(ArcSwap::from_pointee(build(&tools.routes())));
let installed = tools.on_replace({
let router = router.clone();
move |routes| router.store(Arc::new(build(&routes)))
});
assert!(installed);
assert!(router.load().get("alpha").is_some());
tools.replace([route("beta")]);
assert!(router.load().get("beta").is_some(), "the new tool routes");
assert!(router.load().get("alpha").is_none(), "the old one does not");
}
}