marona 1.1.2

Universal Model Gateway and MCP/Skill SDK with mandatory project-scoped Marona authentication
Documentation
use std::{sync::Arc, time::Duration};

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use url::Url;
use uuid::Uuid;

use crate::{Error, FunctionTool, Result, ToolContext};

#[cfg(feature = "a2a")]
type A2AHandlerFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Result<Value>> + Send>>;
#[cfg(feature = "a2a")]
type A2AHandler = Arc<dyn Fn(Value) -> A2AHandlerFuture + Send + Sync>;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2APolicy {
    pub require_https: bool,
    pub max_request_bytes: usize,
    pub max_response_bytes: usize,
    #[serde(default)]
    pub denied_fields: Vec<String>,
}

impl Default for A2APolicy {
    fn default() -> Self {
        Self {
            require_https: true,
            max_request_bytes: 1_048_576,
            max_response_bytes: 8_388_608,
            denied_fields: vec![],
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2ATask {
    pub id: String,
    pub context_id: Option<String>,
    pub state: String,
    #[serde(default)]
    pub output: Value,
    #[serde(default)]
    pub artifacts: Vec<Value>,
    #[serde(default)]
    pub raw: Value,
}

#[derive(Clone, Debug)]
pub struct A2APeer {
    pub name: String,
    pub url: String,
    pub description: Option<String>,
    pub bearer_token: Option<String>,
    pub permissions: Vec<String>,
    pub policy: A2APolicy,
    client: reqwest::Client,
    card: Arc<tokio::sync::RwLock<Option<Value>>>,
}

impl A2APeer {
    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Result<Self> {
        let name = name.into();
        let url = url.into();
        if name.trim().is_empty() {
            return Err(Error::Validation("A2A peer name is required".into()));
        }
        Url::parse(&url).map_err(|e| Error::Validation(format!("invalid A2A URL: {e}")))?;
        Ok(Self {
            name,
            url: url.trim_end_matches('/').into(),
            description: None,
            bearer_token: None,
            permissions: vec![],
            policy: A2APolicy::default(),
            client: reqwest::Client::builder()
                .timeout(Duration::from_secs(60))
                .redirect(reqwest::redirect::Policy::none())
                .build()?,
            card: Arc::new(tokio::sync::RwLock::new(None)),
        })
    }
    pub fn description(mut self, value: impl Into<String>) -> Self {
        self.description = Some(value.into());
        self
    }
    pub fn bearer_token(mut self, value: impl Into<String>) -> Self {
        self.bearer_token = Some(value.into());
        self
    }
    pub fn permissions(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.permissions = values.into_iter().map(Into::into).collect();
        self
    }
    pub fn policy(mut self, value: A2APolicy) -> Self {
        self.policy = value;
        self
    }

    pub async fn discover(&self) -> Result<Value> {
        if let Some(card) = self.card.read().await.clone() {
            return Ok(card);
        }
        self.validate_url()?;
        let url = format!("{}/.well-known/agent-card.json", self.url);
        let mut request = self.client.get(url);
        if let Some(token) = &self.bearer_token {
            request = request.bearer_auth(token);
        }
        let response = request.send().await?;
        let status = response.status();
        let bytes = response.bytes().await?;
        if !status.is_success() {
            return Err(Error::A2A(format!("Agent Card returned HTTP {status}")));
        }
        if bytes.len() > self.policy.max_response_bytes {
            return Err(Error::A2A("Agent Card exceeds response limit".into()));
        }
        let card: Value = serde_json::from_slice(&bytes).map_err(|e| Error::A2A(e.to_string()))?;
        *self.card.write().await = Some(card.clone());
        Ok(card)
    }

    pub async fn run(
        &self,
        input: Value,
        skill: Option<&str>,
        context: &ToolContext,
    ) -> Result<A2ATask> {
        for permission in &self.permissions {
            if !context.permissions.iter().any(|value| value == permission) {
                return Err(Error::PermissionRequired(permission.clone()));
            }
        }
        let card = self.discover().await?;
        let endpoint = card
            .pointer("/interfaces/0/url")
            .or_else(|| card.get("url"))
            .and_then(Value::as_str)
            .unwrap_or(&self.url);
        let safe = redact(input, &self.policy.denied_fields);
        let params = json!({"message":{"messageId":Uuid::new_v4().to_string(),"role":"ROLE_USER","parts":[{"kind":"data","data":safe}]},"configuration":{"acceptedOutputModes":["text/plain","application/json"]},"metadata":{"skill":skill,"user_id":context.user_id,"session_id":context.session_id}});
        let body = json!({"jsonrpc":"2.0","id":Uuid::new_v4().to_string(),"method":"SendMessage","params":params});
        let encoded = serde_json::to_vec(&body).map_err(|e| Error::A2A(e.to_string()))?;
        if encoded.len() > self.policy.max_request_bytes {
            return Err(Error::A2A("request exceeds A2A limit".into()));
        }
        let mut request = self
            .client
            .post(endpoint)
            .json(&body)
            .header("A2A-Version", "1.0");
        if let Some(token) = &self.bearer_token {
            request = request.bearer_auth(token);
        }
        let response = request.send().await?;
        let status = response.status();
        let bytes = response.bytes().await?;
        if !status.is_success() {
            return Err(Error::A2A(format!("peer returned HTTP {status}")));
        }
        if bytes.len() > self.policy.max_response_bytes {
            return Err(Error::A2A("response exceeds A2A limit".into()));
        }
        let raw: Value = serde_json::from_slice(&bytes).map_err(|e| Error::A2A(e.to_string()))?;
        let value = raw.get("result").cloned().unwrap_or_else(|| raw.clone());
        Ok(A2ATask {
            id: value
                .get("id")
                .or_else(|| value.get("taskId"))
                .and_then(Value::as_str)
                .unwrap_or("")
                .into(),
            context_id: value
                .get("contextId")
                .and_then(Value::as_str)
                .map(str::to_owned),
            state: value
                .pointer("/status/state")
                .or_else(|| value.get("state"))
                .and_then(Value::as_str)
                .unwrap_or("TASK_STATE_COMPLETED")
                .into(),
            output: value.get("output").cloned().unwrap_or_else(|| {
                value
                    .pointer("/status/message")
                    .cloned()
                    .unwrap_or(Value::Null)
            }),
            artifacts: value
                .get("artifacts")
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default(),
            raw,
        })
    }

    pub fn function_tool(&self) -> FunctionTool {
        let peer = self.clone();
        let tool_name = format!("a2a__{}", self.name.to_lowercase().replace([' ', '-'], "_"));
        FunctionTool::new(
            tool_name,
            self.description
                .clone()
                .unwrap_or_else(|| format!("Collaborate with independent A2A peer {}.", self.name)),
            json!({"type":"object","properties":{"input":{},"skill":{"type":["string","null"]}},"required":["input"],"additionalProperties":false}),
            move |arguments, context| {
                let peer = peer.clone();
                async move {
                    let task = peer
                        .run(
                            arguments.get("input").cloned().unwrap_or(Value::Null),
                            arguments.get("skill").and_then(Value::as_str),
                            &context,
                        )
                        .await?;
                    serde_json::to_value(task).map_err(|e| Error::A2A(e.to_string()))
                }
            },
        )
    }

    fn validate_url(&self) -> Result<()> {
        let url = Url::parse(&self.url).map_err(|e| Error::A2A(e.to_string()))?;
        if self.policy.require_https
            && url.scheme() != "https"
            && !matches!(url.host_str(), Some("127.0.0.1" | "localhost"))
        {
            return Err(Error::A2A("A2A peer requires HTTPS".into()));
        }
        Ok(())
    }
}

fn redact(mut value: Value, denied: &[String]) -> Value {
    match &mut value {
        Value::Object(map) => {
            for key in denied {
                map.remove(key);
            }
            for item in map.values_mut() {
                *item = redact(item.take(), denied);
            }
        }
        Value::Array(items) => {
            for item in items {
                *item = redact(item.take(), denied);
            }
        }
        _ => {}
    }
    value
}

#[cfg(feature = "a2a")]
pub struct A2AServer {
    pub agent_card: Value,
    handler: A2AHandler,
}

#[cfg(feature = "a2a")]
impl A2AServer {
    pub fn new<F, Fut>(agent_card: Value, handler: F) -> Self
    where
        F: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = Result<Value>> + Send + 'static,
    {
        Self {
            agent_card,
            handler: Arc::new(move |value| Box::pin(handler(value))),
        }
    }
    pub fn router(self) -> axum::Router {
        use axum::{
            extract::State,
            routing::{get, post},
            Json, Router,
        };
        #[derive(Clone)]
        struct StateValue {
            card: Value,
            handler: A2AHandler,
        }
        async fn card(State(state): State<StateValue>) -> Json<Value> {
            Json(state.card)
        }
        async fn call(State(state): State<StateValue>, Json(value): Json<Value>) -> Json<Value> {
            let id = value.get("id").cloned().unwrap_or(Value::Null);
            let params = value.get("params").cloned().unwrap_or(Value::Null);
            match (state.handler)(params).await {
                Ok(result) => Json(json!({"jsonrpc":"2.0","id":id,"result":result})),
                Err(error) => Json(
                    json!({"jsonrpc":"2.0","id":id,"error":{"code":-32000,"message":error.to_string()}}),
                ),
            }
        }
        Router::new()
            .route("/.well-known/agent-card.json", get(card))
            .route("/", post(call))
            .with_state(StateValue {
                card: self.agent_card,
                handler: self.handler,
            })
    }
}