use std::{
borrow::Cow, collections::HashMap, future::Future, net::SocketAddr, pin::Pin, sync::Arc,
};
use axum::{
extract::{Request, State},
http::{HeaderMap, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Json, Router,
};
use rmcp::{
model::{
CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation,
ListToolsResult, PaginatedRequestParams, ProtocolVersion, ServerCapabilities, ServerConfig,
Tool, ToolAnnotations,
},
service::{RequestContext, RoleServer},
transport::streamable_http_server::{
session::local::LocalSessionManager, tower::StreamableHttpService,
StreamableHttpServerConfig,
},
ErrorData as McpError, ServerHandler,
};
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;
use super::{
failure, standard_output_schema, AuthConfig, Error, ExecutionMode, ExecutionTarget,
HostingConfig, PermissionSpec, Result, ToolContext, ToolSpec,
};
type ToolFuture = Pin<Box<dyn Future<Output = Result<Value>> + Send>>;
type ToolHandler = Arc<dyn Fn(Value, ToolContext) -> ToolFuture + Send + Sync>;
#[derive(Clone)]
struct RegisteredTool {
spec: ToolSpec,
handler: ToolHandler,
}
#[derive(Clone)]
pub struct MCPServer {
inner: Arc<AppInner>,
}
struct AppInner {
name: String,
server_name: String,
slug: String,
description: String,
category: String,
tagline: Option<String>,
icon_url: Option<String>,
website_url: Option<String>,
privacy_url: Option<String>,
terms_url: Option<String>,
support_url: Option<String>,
version: String,
visibility: String,
pricing_model: String,
monthly_price_cents: i64,
currency: String,
marketplace_commission_bps: i64,
payment_processing_bps: i64,
execution_modes: Vec<ExecutionMode>,
execution_targets: Vec<ExecutionTarget>,
permissions: Vec<PermissionSpec>,
auth: AuthConfig,
hosting: HostingConfig,
tools: HashMap<String, RegisteredTool>,
manifest_override: Option<Value>,
registration_override: Option<Value>,
health_extra: Value,
allowed_hosts: Vec<String>,
allowed_origins: Vec<String>,
api_key_env: Option<String>,
api_key_headers: Vec<String>,
}
pub struct MCPServerBuilder {
inner: AppInner,
}
pub struct ToolBuilder {
name: String,
title: Option<String>,
description: String,
input_schema: Value,
output_schema: Value,
destructive: bool,
confirmation: bool,
system: bool,
}
impl ToolBuilder {
pub fn new(
name: impl Into<String>,
description: impl Into<String>,
input_schema: Value,
) -> Self {
Self {
name: name.into(),
title: None,
description: description.into(),
input_schema,
output_schema: standard_output_schema(),
destructive: false,
confirmation: false,
system: false,
}
}
pub fn title(mut self, value: impl Into<String>) -> Self {
self.title = Some(value.into());
self
}
pub fn destructive(mut self, value: bool) -> Self {
self.destructive = value;
self
}
pub fn requires_confirmation(mut self, value: bool) -> Self {
self.confirmation = value;
self
}
pub fn system(mut self, value: bool) -> Self {
self.system = value;
self
}
pub fn output_schema(mut self, value: Value) -> Self {
self.output_schema = value;
self
}
}
impl MCPServer {
pub fn builder(name: impl Into<String>, slug: impl Into<String>) -> MCPServerBuilder {
let name = name.into();
let slug = slug.into();
let allowed_hosts = default_allowed_hosts(&slug);
MCPServerBuilder {
inner: AppInner {
name,
server_name: slug.clone(),
slug,
description: String::new(),
category: "other".into(),
tagline: None,
icon_url: None,
website_url: None,
privacy_url: None,
terms_url: None,
support_url: None,
version: "0.1.0".into(),
visibility: "public".into(),
pricing_model: "free".into(),
monthly_price_cents: 0,
currency: "USD".into(),
marketplace_commission_bps: 2000,
payment_processing_bps: 290,
execution_modes: vec![ExecutionMode::Online],
execution_targets: Vec::new(),
permissions: Vec::new(),
auth: AuthConfig::default(),
hosting: HostingConfig::default(),
tools: HashMap::new(),
manifest_override: None,
registration_override: None,
health_extra: json!({}),
allowed_hosts,
allowed_origins: Vec::new(),
api_key_env: None,
api_key_headers: vec!["x-marona-api-key".into()],
},
}
}
pub fn manifest(&self) -> Value {
if let Some(manifest) = &self.inner.manifest_override {
return manifest.clone();
}
let tools: Vec<_> = self
.inner
.tools
.values()
.filter(|tool| !tool.spec.system)
.map(|tool| descriptor(&tool.spec))
.collect();
generic_manifest(&self.inner, &tools, "http://localhost")
}
pub fn hub_registration(&self) -> Value {
if let Some(registration) = &self.inner.registration_override {
return registration.clone();
}
generic_registration(
&self.inner,
&self.visible_tool_descriptors(),
"http://localhost",
)
}
pub fn router(&self) -> Router {
let cancellation = CancellationToken::new();
let config = StreamableHttpServerConfig::default()
.with_legacy_session_mode(false)
.with_json_response(true)
.with_sse_keep_alive(None)
.with_allowed_hosts(self.inner.allowed_hosts.clone())
.with_cancellation_token(cancellation);
let app = self.clone();
let service: StreamableHttpService<MCPServer, LocalSessionManager> =
StreamableHttpService::new(move || Ok(app.clone()), Default::default(), config);
Router::new()
.route("/health", get(health))
.route("/manifest", get(manifest))
.route("/hub-registration", get(registration))
.nest_service("/mcp", service)
.layer(middleware::from_fn_with_state(self.clone(), verify_api_key))
.with_state(self.clone())
}
pub async fn serve(self, address: SocketAddr) -> Result<()> {
let listener = tokio::net::TcpListener::bind(address).await?;
axum::serve(listener, self.router())
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
pub async fn run_stdio(self) -> Result<()> {
use rmcp::ServiceExt;
let service = ServiceExt::serve(self, rmcp::transport::stdio())
.await
.map_err(|e| Error::Tool(e.to_string()))?;
service
.waiting()
.await
.map_err(|e| Error::Tool(e.to_string()))?;
Ok(())
}
fn visible_tool_descriptors(&self) -> Vec<Value> {
self.inner
.tools
.values()
.filter(|tool| !tool.spec.system)
.map(|tool| descriptor(&tool.spec))
.collect()
}
}
impl MCPServerBuilder {
pub fn server_name(mut self, value: impl Into<String>) -> Self {
self.inner.server_name = value.into();
self
}
pub fn description(mut self, value: impl Into<String>) -> Self {
self.inner.description = value.into();
self
}
pub fn category(mut self, value: impl Into<String>) -> Self {
self.inner.category = value.into();
self
}
pub fn tagline(mut self, value: impl Into<String>) -> Self {
self.inner.tagline = Some(value.into());
self
}
pub fn icon_url(mut self, value: impl Into<String>) -> Self {
self.inner.icon_url = Some(value.into());
self
}
pub fn website_url(mut self, value: impl Into<String>) -> Self {
self.inner.website_url = Some(value.into());
self
}
pub fn privacy_url(mut self, value: impl Into<String>) -> Self {
self.inner.privacy_url = Some(value.into());
self
}
pub fn terms_url(mut self, value: impl Into<String>) -> Self {
self.inner.terms_url = Some(value.into());
self
}
pub fn support_url(mut self, value: impl Into<String>) -> Self {
self.inner.support_url = Some(value.into());
self
}
pub fn version(mut self, value: impl Into<String>) -> Self {
self.inner.version = value.into();
self
}
pub fn visibility(mut self, value: impl Into<String>) -> Self {
self.inner.visibility = value.into();
self
}
pub fn pricing(
mut self,
model: impl Into<String>,
monthly_price_cents: i64,
currency: impl Into<String>,
) -> Self {
self.inner.pricing_model = model.into();
self.inner.monthly_price_cents = monthly_price_cents;
self.inner.currency = currency.into().to_uppercase();
self
}
pub fn execution_modes(mut self, value: Vec<ExecutionMode>) -> Self {
self.inner.execution_modes = value;
self
}
pub fn execution_targets(mut self, value: Vec<ExecutionTarget>) -> Self {
self.inner.execution_targets = value;
self
}
pub fn permissions(mut self, value: Vec<PermissionSpec>) -> Self {
self.inner.permissions = value;
self
}
pub fn auth(mut self, value: AuthConfig) -> Self {
self.inner.auth = value;
self
}
pub fn hosting(mut self, value: HostingConfig) -> Self {
self.inner.hosting = value;
self
}
pub fn public_manifest(mut self, value: Value) -> Self {
self.inner.manifest_override = Some(value);
self
}
pub fn hub_registration(mut self, value: Value) -> Self {
self.inner.registration_override = Some(value);
self
}
pub fn health_extra(mut self, value: Value) -> Self {
self.inner.health_extra = value;
self
}
pub fn allowed_origins(mut self, value: Vec<String>) -> Self {
self.inner.allowed_origins = value;
self
}
pub fn allowed_hosts(mut self, value: Vec<String>) -> Self {
self.inner.allowed_hosts = value;
self
}
pub fn api_key_env(mut self, value: impl Into<String>) -> Self {
self.inner.api_key_env = Some(value.into());
self
}
pub fn api_key_headers(mut self, value: Vec<String>) -> Self {
self.inner.api_key_headers = value;
self
}
pub fn tool<F, Fut, T>(mut self, tool: ToolBuilder, handler: F) -> Result<Self>
where
F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<T>> + Send + 'static,
T: serde::Serialize + Send + 'static,
{
if self.inner.tools.contains_key(&tool.name) {
return Err(Error::DuplicateTool(tool.name));
}
let title = tool.title.unwrap_or_else(|| title_case(&tool.name));
let spec = ToolSpec {
name: tool.name.clone(),
title,
description: tool.description,
input_schema: tool.input_schema,
output_schema: tool.output_schema,
is_destructive: tool.destructive,
requires_user_confirmation: tool.confirmation,
system: tool.system,
};
self.inner.tools.insert(
tool.name,
RegisteredTool {
spec,
handler: Arc::new(move |args, context| {
let future = handler(args, context);
Box::pin(async move { Ok(serde_json::to_value(future.await?)?) })
}),
},
);
Ok(self)
}
pub fn build(self) -> Result<MCPServer> {
if self.inner.description.trim().is_empty() {
return Err(Error::Configuration("description is required".into()));
}
if self.inner.tools.is_empty() {
return Err(Error::Configuration("at least one tool is required".into()));
}
if !matches!(self.inner.visibility.as_str(), "public" | "private") {
return Err(Error::Configuration(
"visibility must be public or private".into(),
));
}
if !matches!(self.inner.pricing_model.as_str(), "free" | "paid") {
return Err(Error::Configuration(
"pricing model must be free or paid".into(),
));
}
if self.inner.pricing_model == "free" && self.inner.monthly_price_cents != 0 {
return Err(Error::Configuration(
"free Apps cannot have a monthly price".into(),
));
}
for tool in self.inner.tools.values() {
if !tool.spec.input_schema.is_object() {
return Err(Error::Configuration(format!(
"tool `{}` input schema must be an object",
tool.spec.name
)));
}
let required = tool
.spec
.output_schema
.get("required")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
for field in [
"status",
"success",
"message",
"content",
"content_type",
"presentation_hint",
"context",
] {
if !required.iter().any(|item| item.as_str() == Some(field)) {
return Err(Error::Configuration(format!(
"tool `{}` output schema must require `{field}`",
tool.spec.name
)));
}
}
}
Ok(MCPServer {
inner: Arc::new(self.inner),
})
}
}
impl ServerHandler for MCPServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_protocol_version(ProtocolVersion::V_2025_11_25)
.with_server_info(Implementation::new(
self.inner.server_name.clone(),
self.inner.version.clone(),
))
.with_instructions(self.inner.description.clone())
}
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
Cow::Borrowed(&[
ProtocolVersion::V_2025_11_25,
ProtocolVersion::V_2025_06_18,
ProtocolVersion::V_2025_03_26,
])
}
fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> impl Future<Output = std::result::Result<ListToolsResult, McpError>> + Send + '_ {
let tools = self
.inner
.tools
.values()
.map(|tool| mcp_tool(&tool.spec))
.collect();
std::future::ready(Ok(ListToolsResult::with_all_items(tools)))
}
fn get_tool(&self, name: &str) -> Option<Tool> {
self.inner.tools.get(name).map(|tool| mcp_tool(&tool.spec))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> std::result::Result<CallToolResponse, McpError> {
let Some(tool) = self.inner.tools.get(request.name.as_ref()) else {
return Err(McpError::invalid_params(
format!("unknown tool `{}`", request.name),
None,
));
};
let args = Value::Object(request.arguments.unwrap_or_default());
if !jsonschema::is_valid(&tool.spec.input_schema, &args) {
return Err(McpError::invalid_params("Invalid tool arguments", None));
}
let headers = context
.extensions
.get::<http::request::Parts>()
.map(|parts| &parts.headers);
let tool_context = headers.map(ToolContext::from_headers).unwrap_or_default();
let result = match (tool.handler)(args, tool_context).await {
Ok(result) => normalize_tool_result(result),
Err(_) => failure("Tool execution failed", "tool_failed").into_value(),
};
let mut value = result;
if value.get("success").and_then(Value::as_bool) == Some(true)
&& !jsonschema::is_valid(&tool.spec.output_schema, &value)
{
value = failure("Invalid tool output", "contract_error").into_value();
}
let mut call_result = CallToolResult::structured(value.clone());
call_result.content = vec![ContentBlock::text(
value
.get("content")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned(),
)];
call_result.is_error = Some(
!value
.get("success")
.and_then(Value::as_bool)
.unwrap_or(false),
);
Ok(call_result.into())
}
}
async fn health(State(app): State<MCPServer>) -> Json<Value> {
let mut payload = json!({"status":"ok","service":app.inner.server_name,"server":app.inner.server_name,"version":app.inner.version,"protocol_version":super::PROTOCOL_VERSION,"tools":app.inner.tools.len()});
if let (Some(target), Some(extra)) =
(payload.as_object_mut(), app.inner.health_extra.as_object())
{
target.extend(extra.clone());
}
Json(payload)
}
async fn manifest(State(app): State<MCPServer>, headers: HeaderMap) -> Json<Value> {
if let Some(value) = &app.inner.manifest_override {
return Json(value.clone());
}
Json(generic_manifest(
&app.inner,
&app.visible_tool_descriptors(),
&request_base(&headers),
))
}
async fn registration(State(app): State<MCPServer>, headers: HeaderMap) -> Json<Value> {
if let Some(value) = &app.inner.registration_override {
return Json(value.clone());
}
Json(generic_registration(
&app.inner,
&app.visible_tool_descriptors(),
&request_base(&headers),
))
}
async fn verify_api_key(State(app): State<MCPServer>, request: Request, next: Next) -> Response {
if !request.uri().path().starts_with("/mcp") {
return next.run(request).await;
}
if let Some(origin) = request.headers().get("origin") {
let origin = origin.to_str().unwrap_or_default();
let host = request
.headers()
.get("host")
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
if origin != format!("http://{host}")
&& origin != format!("https://{host}")
&& !app.inner.allowed_origins.iter().any(|v| v == origin)
{
return StatusCode::FORBIDDEN.into_response();
}
}
let Some(env_name) = &app.inner.api_key_env else {
return next.run(request).await;
};
let Ok(expected) = std::env::var(env_name) else {
return StatusCode::SERVICE_UNAVAILABLE.into_response();
};
if expected.is_empty() {
return StatusCode::SERVICE_UNAVAILABLE.into_response();
}
let bearer = request
.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v == format!("Bearer {expected}"));
let header_match = app.inner.api_key_headers.iter().any(|name| {
request
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v == expected)
});
if bearer || header_match {
next.run(request).await
} else {
(StatusCode::UNAUTHORIZED, "Missing or invalid MCP API key").into_response()
}
}
fn mcp_tool(spec: &ToolSpec) -> Tool {
let input = spec.input_schema.as_object().cloned().unwrap_or_default();
let output = spec.output_schema.as_object().cloned().unwrap_or_default();
Tool::new(
Cow::Owned(spec.name.clone()),
Cow::Owned(spec.description.clone()),
Arc::new(input),
)
.with_title(spec.title.clone())
.with_raw_output_schema(Arc::new(output))
.with_annotations(
ToolAnnotations::new()
.read_only(!spec.is_destructive)
.destructive(spec.is_destructive)
.open_world(true),
)
}
fn descriptor(spec: &ToolSpec) -> Value {
json!({"name":spec.name,"title":spec.title,"description":spec.description,"input_schema":spec.input_schema,"output_schema":spec.output_schema,"is_destructive":spec.is_destructive,"requires_user_confirmation":spec.requires_user_confirmation})
}
fn generic_manifest(inner: &AppInner, tools: &[Value], base: &str) -> Value {
let server_url = format!("{}/mcp/", base.trim_end_matches('/'));
json!({"name":inner.server_name,"display_name":inner.name,"version":inner.version,"protocol_version":super::PROTOCOL_VERSION,"transport":"streamable_http","server_url":server_url,"health_check_url":format!("{}/health",base.trim_end_matches('/')),"icon_url":inner.icon_url,"visibility":inner.visibility,"pricing_model":inner.pricing_model,"monthly_price_cents":inner.monthly_price_cents,"currency":inner.currency,"execution_modes":inner.execution_modes,"execution_targets":resolved_targets(inner,&server_url),"tools":tools,"permissions":inner.permissions,"hosting":hosting_descriptor(&inner.hosting)})
}
fn generic_registration(inner: &AppInner, tools: &[Value], base: &str) -> Value {
let manifest = generic_manifest(inner, tools, base);
let server_url = manifest["server_url"].clone();
let health = manifest["health_check_url"].clone();
json!({"name":inner.name,"slug":inner.slug,"tagline":inner.tagline,"description":inner.description,"category":inner.category,"version":inner.version,"icon_url":inner.icon_url,"website_url":inner.website_url,"privacy_url":inner.privacy_url,"terms_url":inner.terms_url,"support_url":inner.support_url,"visibility":inner.visibility,"pricing_model":inner.pricing_model,"monthly_price_cents":inner.monthly_price_cents,"currency":inner.currency,"marketplace_commission_bps":inner.marketplace_commission_bps,"payment_processing_bps":inner.payment_processing_bps,"execution_modes":inner.execution_modes,"execution_targets":manifest["execution_targets"],"hosting":hosting_descriptor(&inner.hosting),"mcp_server":{"name":inner.name,"server_url":server_url,"transport":"streamable_http","protocol_version":super::PROTOCOL_VERSION,"health_check_url":health,"connection_config":{"docs_url":format!("{}/docs",base.trim_end_matches('/')),"manifest_url":format!("{}/manifest",base.trim_end_matches('/')),"execution_modes":inner.execution_modes,"execution_targets":manifest["execution_targets"]}},"tools":tools,"permissions":inner.permissions,"is_auth_required":inner.auth.is_auth_required,"auth_type":inner.auth.auth_type,"auth_instructions":inner.auth.auth_instructions,"connection_schema":inner.auth.connection_schema})
}
fn resolved_targets(inner: &AppInner, server_url: &str) -> Vec<ExecutionTarget> {
let mut targets = inner.execution_targets.clone();
if inner
.execution_modes
.iter()
.any(|mode| matches!(mode, ExecutionMode::Online | ExecutionMode::Hybrid))
&& !targets.iter().any(|target| {
target
.config
.get("mode")
.and_then(Value::as_str)
.is_some_and(|mode| mode == "online" || mode == "hybrid")
})
{
let mut config = serde_json::Map::new();
config.insert("mode".into(), json!("online"));
config.insert("url".into(), json!(server_url));
config.insert("transport".into(), json!("streamable_http"));
config.insert("endpoint".into(), json!("/mcp"));
targets.insert(
0,
ExecutionTarget {
target_type: "remote_mcp".into(),
config,
},
);
}
targets
}
fn hosting_descriptor(hosting: &HostingConfig) -> Value {
let secrets = hosting
.secrets
.keys()
.map(|key| (key.clone(), json!({"configured":true})))
.collect::<serde_json::Map<_, _>>();
let runtime = hosting
.runtime_config
.iter()
.filter(|(key, _)| !looks_secret(key))
.map(|(key, value)| (key.clone(), value.clone()))
.collect::<serde_json::Map<_, _>>();
json!({"mode":hosting.mode,"runtime":hosting.runtime,"environment":hosting.environment,"secrets":secrets,"runtime_config":runtime})
}
fn looks_secret(value: &str) -> bool {
let value = value.to_lowercase();
["secret", "token", "password", "private", "key"]
.iter()
.any(|part| value.contains(part))
}
fn request_base(headers: &HeaderMap) -> String {
let scheme = headers
.get("x-forwarded-proto")
.and_then(|v| v.to_str().ok())
.unwrap_or("http");
let host = headers
.get("x-forwarded-host")
.or_else(|| headers.get("host"))
.and_then(|v| v.to_str().ok())
.unwrap_or("localhost");
format!("{scheme}://{host}")
}
fn default_allowed_hosts(slug: &str) -> Vec<String> {
let domain = std::env::var("MARONA_MCP_PUBLIC_DOMAIN").unwrap_or_else(|_| "marona.ai".into());
vec![
"localhost".into(),
"127.0.0.1".into(),
"::1".into(),
format!("{slug}.{domain}"),
]
}
fn title_case(name: &str) -> String {
name.split('_')
.map(|word| {
let mut chars = word.chars();
chars
.next()
.map(|first| first.to_uppercase().collect::<String>() + chars.as_str())
.unwrap_or_default()
})
.collect::<Vec<_>>()
.join(" ")
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::{MCPServer, ToolBuilder};
use crate::mcp::success;
#[test]
fn hides_system_tools_from_hub_manifest_but_keeps_public_tools() {
let app = MCPServer::builder("Example", "example")
.description("Example MCP")
.tool(
ToolBuilder::new("visible", "Visible tool", json!({"type":"object"})),
|_, _| async { Ok(success("visible")) },
)
.unwrap()
.tool(
ToolBuilder::new("internal", "Internal tool", json!({"type":"object"}))
.system(true),
|_, _| async { Ok(success("internal")) },
)
.unwrap()
.build()
.unwrap();
let manifest = app.manifest();
let tools = manifest["tools"].as_array().unwrap();
assert_eq!(tools.len(), 1);
assert_eq!(tools[0]["name"], "visible");
}
}
fn normalize_tool_result(value: Value) -> Value {
let fields = [
"status",
"success",
"message",
"content",
"content_type",
"presentation_hint",
"context",
];
if value.is_object() && fields.iter().all(|field| value.get(field).is_some()) {
return value;
}
let content = value
.as_str()
.map(str::to_owned)
.unwrap_or_else(|| value.to_string());
let data = if value.is_object() {
value
} else {
json!({"value": value})
};
super::success(content).with_data(data).into_value()
}
#[cfg(test)]
mod plain_result_tests {
use super::*;
#[test]
fn preserves_all_json_values_and_compatibility_results() {
for value in [
json!({"greeting":"Hi"}),
json!({}),
json!("Hi"),
json!([1, "two"]),
json!([]),
json!(0),
json!(false),
Value::Null,
json!({"success":false}),
] {
let result = normalize_tool_result(value.clone());
assert_eq!(result["success"], true);
assert_eq!(
result["data"],
if value.is_object() {
value
} else {
json!({"value":value})
}
);
}
let failure = super::super::failure("Failed", "test").into_value();
assert_eq!(normalize_tool_result(failure.clone()), failure);
}
}