use std::sync::Arc;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use crate::{core::Core, Error, Result};
const DISCOVER: &str = "marona__discover_capabilities";
const CALL: &str = "marona__call_capability";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConnectOptions {
pub apps: Option<Vec<String>>,
#[serde(default)]
pub skills: Vec<String>,
#[serde(default = "default_interface")]
pub interface: String,
}
fn default_interface() -> String {
"api".into()
}
#[derive(Clone, Debug)]
pub struct Hub {
pub(crate) core: Arc<Core>,
}
impl Hub {
pub async fn connect(&self, options: ConnectOptions) -> Result<McpConnection> {
let mut body = Map::new();
if let Some(apps) = &options.apps {
body.insert("apps".into(), json!(apps));
}
if !options.skills.is_empty() {
body.insert("skills".into(), json!(options.skills));
}
body.insert("adapter".into(), json!("tools"));
body.insert("interface".into(), json!(options.interface));
let payload = self
.core
.json::<Value>(
&self.core.hub_url,
Method::POST,
"/hub/connect",
Some(&Value::Object(body)),
)
.await?;
Ok(McpConnection {
core: self.core.clone(),
unscoped: options.apps.is_none() && options.skills.is_empty(),
interface: options.interface,
payload,
})
}
pub async fn connect_all(&self) -> Result<McpConnection> {
self.connect(ConnectOptions::default()).await
}
pub async fn register_mcp_server(
&self,
name: &str,
slug: &str,
server_url: &str,
description: &str,
visibility: &str,
auth_mode: &str,
) -> Result<Value> {
self.core
.json(
&self.core.hub_url,
Method::POST,
"/hub/mcp/servers",
Some(&json!({
"name": name, "slug": slug, "server_url": server_url,
"description": description, "visibility": visibility,
"transport": "streamable_http", "auth_mode": auth_mode,
})),
)
.await
}
pub async fn list_mcp_servers(&self) -> Result<Value> {
self.mcp_request(Method::GET, "/hub/mcp/servers", None)
.await
}
pub async fn get_mcp_server(&self, server_id: &str) -> Result<Value> {
self.mcp_request(Method::GET, &mcp_path(server_id), None)
.await
}
pub async fn verify_mcp_server(&self, server_id: &str) -> Result<Value> {
self.mcp_request(
Method::POST,
&format!("{}/verify", mcp_path(server_id)),
Some(&json!({})),
)
.await
}
pub async fn activate_mcp_server(
&self,
server_id: &str,
allowed_tools: &[String],
) -> Result<Value> {
self.mcp_request(
Method::POST,
&format!("{}/activate", mcp_path(server_id)),
Some(&json!({"allowed_tools":allowed_tools})),
)
.await
}
pub async fn disable_mcp_server(&self, server_id: &str) -> Result<Value> {
self.mcp_request(
Method::POST,
&format!("{}/disable", mcp_path(server_id)),
Some(&json!({})),
)
.await
}
pub async fn set_mcp_api_key(
&self,
server_id: &str,
value: &str,
header: &str,
user_subject: Option<&str>,
) -> Result<Value> {
self.mcp_request(
Method::POST,
&format!("{}/credentials/api-key", mcp_path(server_id)),
Some(&json!({"value":value,"header":header,"user_subject":user_subject})),
)
.await
}
pub async fn configure_mcp_oauth_client(
&self,
server_id: &str,
client_id: &str,
client_secret: Option<&str>,
) -> Result<Value> {
self.mcp_request(
Method::POST,
&format!("{}/credentials/oauth-client", mcp_path(server_id)),
Some(&json!({"client_id":client_id,"client_secret":client_secret})),
)
.await
}
pub async fn start_mcp_oauth(
&self,
server_id: &str,
scopes: &[String],
user_subject: Option<&str>,
) -> Result<Value> {
self.mcp_request(
Method::POST,
&format!("{}/oauth/start", mcp_path(server_id)),
Some(&json!({"scopes":scopes,"user_subject":user_subject})),
)
.await
}
pub async fn execute_mcp_tool(
&self,
server_id: &str,
tool: &str,
arguments: &Value,
user_subject: Option<&str>,
approved: bool,
request_id: Option<&str>,
) -> Result<Value> {
self.mcp_request(
Method::POST,
&format!("{}/execute", mcp_path(server_id)),
Some(&json!({
"tool": tool,
"arguments": arguments,
"user_subject": user_subject,
"approved": approved,
"request_id": request_id,
})),
)
.await
}
pub async fn list_mcp_invocations(&self, limit: u16) -> Result<Value> {
self.mcp_request(
Method::GET,
&format!("/hub/mcp/invocations?limit={limit}"),
None,
)
.await
}
pub async fn list_mcp_registry(&self, limit: u16, cursor: Option<&str>) -> Result<Value> {
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
serializer.append_pair("limit", &limit.to_string());
if let Some(cursor) = cursor {
serializer.append_pair("cursor", cursor);
}
self.mcp_request(
Method::GET,
&format!("/hub/mcp/registry?{}", serializer.finish()),
None,
)
.await
}
pub async fn import_mcp_registry(
&self,
registry_name: &str,
version: &str,
slug: Option<&str>,
visibility: &str,
auth_mode: &str,
) -> Result<Value> {
self.mcp_request(
Method::POST,
"/hub/mcp/registry/import",
Some(&json!({
"registry_name": registry_name,
"version": version,
"slug": slug,
"visibility": visibility,
"auth_mode": auth_mode,
})),
)
.await
}
async fn mcp_request(&self, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {
self.core.json(&self.core.hub_url, method, path, body).await
}
}
fn mcp_path(server_id: &str) -> String {
let encoded: String = url::form_urlencoded::byte_serialize(server_id.as_bytes()).collect();
format!("/hub/mcp/servers/{encoded}")
}
#[derive(Clone, Debug)]
pub struct McpConnection {
pub(crate) core: Arc<Core>,
pub(crate) unscoped: bool,
pub(crate) interface: String,
pub(crate) payload: Value,
}
impl McpConnection {
pub fn list_tools(&self) -> Vec<Value> {
if self.unscoped {
gateway_tools()
} else {
self.list_capabilities()
}
}
pub fn list_capabilities(&self) -> Vec<Value> {
self.descriptors()
.iter()
.filter_map(normalize_tool)
.collect()
}
pub fn warnings(&self) -> Vec<Value> {
self.payload
.get("warnings")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
}
pub fn session(&self) -> Value {
json!({
"status": self.payload.get("status"),
"execution": self.payload.get("execution"),
"mode": self.core.mode,
"apps": self.payload.get("apps").cloned().unwrap_or_else(|| json!([])),
"skills": self.payload.get("skills").cloned().unwrap_or_else(|| json!([])),
"developer_context": self.payload.get("developer_context").cloned().unwrap_or_else(|| json!({})),
"warnings": self.warnings(),
"server_urls": self.server_urls(),
})
}
pub fn server_urls(&self) -> Vec<String> {
let mut values = Vec::new();
for descriptor in self.descriptors() {
for pointer in [
"/marona/mcp_server_url",
"/x_marona/mcp_server_url",
"/mcp_server_url",
"/server_url",
] {
if let Some(url) = descriptor.pointer(pointer).and_then(Value::as_str) {
if !values.iter().any(|value| value == url) {
values.push(url.to_owned());
}
}
}
}
values
}
pub fn server_url(&self) -> Option<String> {
let values = self.server_urls();
(values.len() == 1).then(|| values[0].clone())
}
pub async fn call_tool(
&self,
name: &str,
arguments: Value,
user_id: Option<&str>,
conversation_id: Option<&str>,
) -> Result<Value> {
if self.unscoped && name == DISCOVER {
return Ok(self.discover(&arguments));
}
if self.unscoped && name == CALL {
let capability = arguments
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| Error::Validation("capability name is required".into()))?;
let nested = arguments
.get("arguments")
.cloned()
.unwrap_or_else(|| json!({}));
return Box::pin(self.call_tool(capability, nested, user_id, conversation_id)).await;
}
let descriptor = self
.descriptors()
.into_iter()
.find(|item| tool_name(item).as_deref() == Some(name))
.ok_or_else(|| {
Error::Validation(format!("connected capability '{name}' was not found"))
})?;
let marona = descriptor
.get("marona")
.or_else(|| descriptor.get("x_marona"))
.and_then(Value::as_object)
.cloned()
.unwrap_or_default();
let is_skill = marona.get("type").and_then(Value::as_str) == Some("skill");
let body = if is_skill {
json!({
"skill_name": marona.get("skill_name"),
"request": arguments.get("request").and_then(Value::as_str).unwrap_or(""),
"context": arguments.get("context").cloned().unwrap_or_else(|| json!({})),
"interface": self.interface,
"user_id": user_id,
"conversation_id": conversation_id,
})
} else {
json!({
"app_slug": marona.get("app_slug"),
"tool_name": marona.get("tool_name").and_then(Value::as_str).unwrap_or(name),
"arguments": arguments,
"interface": self.interface,
"user_id": user_id,
"conversation_id": conversation_id,
})
};
let path = if is_skill {
"/runtime/skills/execute"
} else {
"/runtime/tools/execute"
};
self.core
.json(&self.core.runtime_url, Method::POST, path, Some(&body))
.await
}
pub(crate) fn descriptors(&self) -> Vec<Value> {
self.payload
.get("connections")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
}
fn discover(&self, arguments: &Value) -> Value {
let query = arguments
.get("query")
.and_then(Value::as_str)
.unwrap_or("")
.to_lowercase();
let selected = self
.list_capabilities()
.into_iter()
.filter(|tool| query.is_empty() || tool.to_string().to_lowercase().contains(&query))
.collect::<Vec<_>>();
json!({"structuredContent":{"status":"capabilities_discovered","tools":selected}})
}
}
fn tool_name(value: &Value) -> Option<String> {
value
.pointer("/function/name")
.or_else(|| value.get("name"))
.and_then(Value::as_str)
.map(str::to_owned)
}
fn normalize_tool(value: &Value) -> Option<Value> {
let name = tool_name(value)?;
let description = value
.pointer("/function/description")
.or_else(|| value.get("description"))
.and_then(Value::as_str)
.unwrap_or("");
let schema = value
.pointer("/function/parameters")
.or_else(|| value.get("inputSchema"))
.cloned()
.unwrap_or_else(|| json!({"type":"object","properties":{},"additionalProperties":false}));
let mut normalized = json!({"name":name,"description":description,"inputSchema":schema});
if let Some(metadata) = value.get("marona").or_else(|| value.get("x_marona")) {
normalized["annotations"] = metadata.clone();
}
Some(normalized)
}
fn gateway_tools() -> Vec<Value> {
vec![
json!({"name":DISCOVER,"description":"Discover relevant Marona Apps, Skills, and exact capability schemas for the current request.","inputSchema":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"],"additionalProperties":false}}),
json!({"name":CALL,"description":"Execute one exact capability returned by Marona discovery.","inputSchema":{"type":"object","properties":{"name":{"type":"string"},"arguments":{"type":"object"}},"required":["name","arguments"],"additionalProperties":false}}),
]
}