use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use rmcp::model::{
CallToolRequestParams, CallToolResponse, CallToolResult, CustomRequest, CustomResult,
ErrorCode, Implementation, ListToolsResult, PaginatedRequestParams, ServerCapabilities,
ServerConfig, Tool, ToolAnnotations,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData, RoleServer, ServerHandler};
use serde::Serialize;
use serde_json::{Map, Value, json};
#[cfg(feature = "demo")]
use crate::catalogue::Catalogue;
#[cfg(feature = "demo")]
use crate::demo::{get_project, list_projects};
use crate::operation::{Args, InvalidDeclaration, OpError, Operation, Param, Principal};
#[cfg(feature = "demo")]
#[cfg_attr(docsrs, doc(cfg(feature = "demo")))]
pub const TOOL_NAME: &str = list_projects::OPERATION.name;
#[cfg(feature = "demo")]
#[cfg_attr(docsrs, doc(cfg(feature = "demo")))]
pub const GET_PROJECT_TOOL: &str = get_project::OPERATION.name;
type Outcome = Result<serde_json::Result<Value>, OpError>;
type Call<S> = Box<
dyn for<'a> Fn(
&'a S,
&'a Principal,
&'a Args,
) -> Pin<Box<dyn Future<Output = Outcome> + Send + 'a>>
+ Send
+ Sync,
>;
pub struct McpTool<S> {
name: &'static str,
schema: Tool,
invalid: Option<InvalidDeclaration>,
call: Call<S>,
}
impl<S> McpTool<S> {
pub fn name(&self) -> &'static str {
self.name
}
}
pub fn tool<S, T>(operation: &'static Operation<S, T>) -> McpTool<S>
where
S: Sync + 'static,
T: Serialize + Send + 'static,
{
McpTool {
name: operation.name,
schema: Tool::new(
operation.name,
operation.description,
Arc::new(input_schema(operation.params)),
)
.with_annotations(ToolAnnotations::new().read_only(true)),
invalid: operation.check().err(),
call: Box::new(move |state, principal, args| {
Box::pin(async move {
operation
.call(state, principal, args)
.await
.map(|result| serde_json::to_value(&result))
})
}),
}
}
fn input_schema(params: &[Param]) -> Map<String, Value> {
let properties: Map<String, Value> = params
.iter()
.map(|param| {
let property = json!({ "type": "string", "description": param.description });
(param.name.to_owned(), property)
})
.collect();
let required: Vec<&str> = params
.iter()
.filter(|param| param.required)
.map(|param| param.name)
.collect();
let mut schema = Map::new();
schema.insert("type".to_owned(), json!("object"));
schema.insert("properties".to_owned(), Value::Object(properties));
if !required.is_empty() {
schema.insert("required".to_owned(), json!(required));
}
schema.insert("additionalProperties".to_owned(), Value::Bool(false));
schema
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToolError {
Duplicate(&'static str),
Operation(InvalidDeclaration),
}
impl std::fmt::Display for ToolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Duplicate(name) => write!(f, "senu: tool {name:?} is listed twice"),
Self::Operation(invalid) => write!(f, "senu: {invalid}"),
}
}
}
impl std::error::Error for ToolError {}
pub struct McpServer<S> {
state: S,
principal: Principal,
tools: Vec<McpTool<S>>,
name: &'static str,
version: &'static str,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ServeError {
Initialize,
Stopped,
}
impl std::fmt::Display for ServeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Initialize => "senu: MCP initialization failed",
Self::Stopped => "senu: the MCP server stopped unexpectedly",
})
}
}
impl std::error::Error for ServeError {}
#[cfg(feature = "demo")]
#[cfg_attr(docsrs, doc(cfg(feature = "demo")))]
impl McpServer<Catalogue> {
pub fn new(catalogue: Catalogue) -> Self {
Self::with_principal(catalogue, Principal::demo_mcp())
}
pub fn with_principal(catalogue: Catalogue, principal: Principal) -> Self {
Self {
state: catalogue,
principal,
tools: crate::demo::tools(),
name: "senu",
version: env!("CARGO_PKG_VERSION"),
}
}
}
impl<S> McpServer<S> {
pub fn with_tools(
state: S,
principal: Principal,
tools: Vec<McpTool<S>>,
) -> Result<Self, ToolError> {
for (i, tool) in tools.iter().enumerate() {
if let Some(invalid) = tool.invalid {
return Err(ToolError::Operation(invalid));
}
if tools[..i].iter().any(|other| other.name == tool.name) {
return Err(ToolError::Duplicate(tool.name));
}
}
Ok(Self {
state,
principal,
tools,
name: "senu",
version: env!("CARGO_PKG_VERSION"),
})
}
pub fn with_info(mut self, name: &'static str, version: &'static str) -> Self {
self.name = name;
self.version = version;
self
}
pub fn info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(Implementation::new(self.name, self.version))
}
pub fn tools(&self) -> Vec<Tool> {
self.tools.iter().map(|tool| tool.schema.clone()).collect()
}
pub async fn call(&self, request: &CallToolRequestParams) -> Result<CallToolResult, ErrorData> {
let Some(tool) = self.tools.iter().find(|tool| tool.name == request.name) else {
return Err(ErrorData::invalid_params("unknown tool", None));
};
let no_arguments = Map::new();
let args = request.arguments.as_ref().unwrap_or(&no_arguments);
match (tool.call)(&self.state, &self.principal, args).await {
Ok(value) => value
.map(CallToolResult::structured)
.map_err(|_| ErrorData::internal_error("internal", None)),
Err(err) => Ok(CallToolResult::structured_error(
json!({ "error": err.code() }),
)),
}
}
}
impl<S: Send + Sync + 'static> McpServer<S> {
pub async fn serve_stdio(self) -> Result<(), ServeError> {
use rmcp::ServiceExt as _;
use rmcp::service::{QuitReason, ServerInitializeError};
let running = match self.serve(rmcp::transport::io::stdio()).await {
Ok(running) => running,
Err(ServerInitializeError::ConnectionClosed(_)) => return Ok(()),
Err(_) => return Err(ServeError::Initialize),
};
match running.waiting().await {
Ok(QuitReason::Closed | QuitReason::Cancelled) => Ok(()),
_ => Err(ServeError::Stopped),
}
}
}
#[cfg(feature = "demo")]
#[cfg_attr(docsrs, doc(cfg(feature = "demo")))]
pub fn tools() -> Vec<Tool> {
McpServer::new(Catalogue::demo()).tools()
}
impl<S: Send + Sync + 'static> ServerHandler for McpServer<S> {
fn get_info(&self) -> ServerConfig {
self.info()
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult::with_all_items(self.tools()))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
self.call(&request).await.map(CallToolResponse::from)
}
fn get_tool(&self, name: &str) -> Option<Tool> {
self.tools
.iter()
.find(|tool| tool.name == name)
.map(|tool| tool.schema.clone())
}
async fn on_custom_request(
&self,
_request: CustomRequest,
_context: RequestContext<RoleServer>,
) -> Result<CustomResult, ErrorData> {
Err(ErrorData::new(
ErrorCode::METHOD_NOT_FOUND,
"method not found",
None,
))
}
}