marona 2.0.0

Universal Model Gateway and MCP/Skill SDK with mandatory project-scoped Marona authentication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use crate::a2a_protocol::{
    self as protocol, endpoint, parse_task, unwrap, valid_url, validate_card, validate_host,
};
use crate::{A2AEvent, A2ATaskStore, Error, FunctionTool, Result, ToolContext};
use futures_util::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{
    pin::Pin,
    sync::Arc,
    time::{Duration, Instant},
};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct A2APolicy {
    pub require_https: bool,
    pub max_request_bytes: usize,
    pub max_response_bytes: usize,
    pub denied_fields: Vec<String>,
    pub allowed_skills: Vec<String>,
    pub allow_private_network: bool,
}
impl Default for A2APolicy {
    fn default() -> Self {
        Self {
            require_https: true,
            max_request_bytes: 1_000_000,
            max_response_bytes: 10_000_000,
            denied_fields: vec![],
            allowed_skills: vec![],
            allow_private_network: false,
        }
    }
}
#[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,
}
impl A2ATask {
    pub fn completed(&self) -> bool {
        self.state == "TASK_STATE_COMPLETED"
    }
    pub fn input_required(&self) -> bool {
        matches!(
            self.state.as_str(),
            "TASK_STATE_INPUT_REQUIRED" | "TASK_STATE_AUTH_REQUIRED"
        )
    }
}
#[derive(Debug, Clone, Default)]
pub struct A2ARunOptions {
    pub skill: Option<String>,
    pub task_id: Option<String>,
    pub context_id: Option<String>,
}
#[derive(Clone)]
pub struct A2APeer {
    pub name: String,
    pub url: String,
    pub description: Option<String>,
    pub bearer_token: Option<String>,
    pub api_key: Option<(String, String)>,
    pub send_credentials_with_card: bool,
    pub permissions: Vec<String>,
    pub policy: A2APolicy,
    pub timeout: Duration,
    pub max_retries: usize,
    pub card_ttl: Duration,
    pub task_store: A2ATaskStore,
    client: reqwest::Client,
    card: Arc<tokio::sync::RwLock<Option<(Instant, Value)>>>,
}
impl std::fmt::Debug for A2APeer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("A2APeer")
            .field("name", &self.name)
            .field("url", &self.url)
            .finish_non_exhaustive()
    }
}
impl A2APeer {
    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Result<Self> {
        Self::with_policy(name, url, A2APolicy::default())
    }
    pub fn with_policy(
        name: impl Into<String>,
        url: impl Into<String>,
        policy: A2APolicy,
    ) -> 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()));
        }
        valid_url(&url, &policy)?;
        if policy.max_request_bytes == 0 || policy.max_response_bytes == 0 {
            return Err(Error::Validation("A2A byte limits must be positive".into()));
        }
        Ok(Self {
            name,
            url: url.trim_end_matches('/').into(),
            description: None,
            bearer_token: None,
            api_key: None,
            send_credentials_with_card: false,
            permissions: vec![],
            policy,
            timeout: Duration::from_secs(60),
            max_retries: 2,
            card_ttl: Duration::from_secs(300),
            task_store: A2ATaskStore::default(),
            client: reqwest::Client::builder()
                .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 api_key(mut self, header: impl Into<String>, value: impl Into<String>) -> Self {
        self.api_key = Some((header.into(), 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.card = Arc::new(tokio::sync::RwLock::new(None));
        self
    }
    pub fn task_store(mut self, value: A2ATaskStore) -> Self {
        self.task_store = value;
        self
    }
    pub async fn discover(&self) -> Result<Value> {
        self.discover_force(false).await
    }
    pub async fn discover_force(&self, force: bool) -> Result<Value> {
        if !force {
            if let Some((when, card)) = &*self.card.read().await {
                if when.elapsed() < self.card_ttl {
                    return Ok(card.clone());
                }
            }
        }
        validate_host(&self.url, &self.policy).await?;
        let base = if self.url.ends_with(".json") {
            self.url
                .rsplit_once('/')
                .map(|v| format!("{}/", v.0))
                .unwrap_or_default()
        } else {
            format!("{}/", self.url)
        };
        let candidates = [
            if self.url.ends_with(".json") {
                self.url.clone()
            } else {
                format!("{base}.well-known/agent-card.json")
            },
            format!("{base}.well-known/agent.json"),
        ];
        for target in candidates {
            let request = self
                .headers(self.client.get(target), true)?
                .timeout(self.timeout);
            let response = request.send().await?;
            if response.status() == reqwest::StatusCode::NOT_FOUND {
                continue;
            }
            let card = self.read(response).await?;
            validate_card(&card)?;
            *self.card.write().await = Some((Instant::now(), card.clone()));
            return Ok(card);
        }
        Err(Error::A2A("A2A Agent Card not found".into()))
    }
    pub async fn run(
        &self,
        input: Value,
        skill: Option<&str>,
        context: &ToolContext,
    ) -> Result<A2ATask> {
        self.run_with_options(
            input,
            A2ARunOptions {
                skill: skill.map(str::to_owned),
                ..Default::default()
            },
            context,
        )
        .await
    }
    pub async fn run_with_options(
        &self,
        input: Value,
        options: A2ARunOptions,
        context: &ToolContext,
    ) -> Result<A2ATask> {
        self.check_permissions(context)?;
        let card = self.discover().await?;
        let params = self.message(&card, input, options, context)?;
        let task = parse_task(
            self.request(&card, "SendMessage", params, "message:send", false)
                .await?,
        )?;
        self.task_store
            .save(&self.name, &session(context), &task)
            .await?;
        if matches!(
            task.state.as_str(),
            "TASK_STATE_FAILED" | "TASK_STATE_REJECTED" | "TASK_STATE_CANCELED"
        ) {
            return Err(Error::A2A(format!("A2A task returned {}", task.state)));
        }
        Ok(task)
    }
    pub async fn continue_task(&self, input: Value, context: &ToolContext) -> Result<A2ATask> {
        let previous = self
            .task_store
            .latest(&self.name, &session(context))
            .await?
            .ok_or_else(|| Error::A2A("No previous A2A task exists for this session".into()))?;
        self.run_with_options(
            input,
            A2ARunOptions {
                task_id: Some(previous.id),
                context_id: previous.context_id,
                ..Default::default()
            },
            context,
        )
        .await
    }
    pub async fn get_task(&self, id: &str) -> Result<A2ATask> {
        if id.is_empty() {
            return Err(Error::A2A("Task ID is required".into()));
        }
        parse_task(
            self.request(
                &self.discover().await?,
                "GetTask",
                json!({"id":id,"historyLength":20}),
                &format!("tasks/{}", encode(id)),
                true,
            )
            .await?,
        )
    }
    pub async fn cancel(&self, id: &str) -> Result<A2ATask> {
        if id.is_empty() {
            return Err(Error::A2A("Task ID is required".into()));
        }
        parse_task(
            self.request(
                &self.discover().await?,
                "CancelTask",
                json!({"id":id}),
                &format!("tasks/{}:cancel", encode(id)),
                false,
            )
            .await?,
        )
    }
    pub async fn stream(
        &self,
        input: Value,
        options: A2ARunOptions,
        context: &ToolContext,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<A2AEvent>> + Send>>> {
        self.check_permissions(context)?;
        let card = self.discover().await?;
        let (endpoint, rpc) = endpoint(&card, &self.url);
        validate_host(&endpoint, &self.policy).await?;
        let params = self.message(&card, input, options, context)?;
        let body = if rpc {
            rpc_body("SendStreamingMessage", params)
        } else {
            params
        };
        self.check_size(&body)?;
        let target = if rpc {
            endpoint
        } else {
            format!("{}/message:stream", endpoint.trim_end_matches('/'))
        };
        let response = self
            .headers(self.client.post(target), false)?
            .header("Accept", "text/event-stream")
            .timeout(self.timeout)
            .json(&body)
            .send()
            .await?;
        if !response.status().is_success() {
            return Err(Error::A2A(format!(
                "A2A stream returned HTTP {}",
                response.status()
            )));
        }
        if !response
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .starts_with("text/event-stream")
        {
            return Err(Error::A2A("A2A stream requires text/event-stream".into()));
        }
        let peer = self.clone();
        let key = session(context);
        Ok(Box::pin(async_stream::try_stream! {
            let mut source = response.bytes_stream(); let mut buffer: Vec<u8> = vec![]; let mut data = String::new(); let mut received = 0;
            let mut remembered: Option<A2ATask> = None;
            loop {
                let chunk = source.next().await; let done = chunk.is_none();
                if let Some(chunk) = chunk { let chunk = chunk?; received += chunk.len(); if received > peer.policy.max_response_bytes { Err(Error::A2A("A2A stream exceeds response limit".into()))?; } buffer.extend_from_slice(&chunk); }
                else if !buffer.is_empty() || !data.is_empty() { buffer.extend_from_slice(b"\n\n"); }
                while let Some(end) = buffer.iter().position(|b| *b == b'\n') {
                    let line = String::from_utf8(buffer.drain(..=end).collect()).map_err(|_| Error::A2A("A2A stream contains invalid UTF-8".into()))?;
                    let line = line.trim_end_matches(['\r','\n']);
                    if let Some(value) = line.strip_prefix("data:") { if !data.is_empty() { data.push('\n'); } data.push_str(value.trim_start()); }
                    else if line.is_empty() && !data.is_empty() {
                        let value = unwrap(serde_json::from_str(&data).map_err(|_| Error::A2A("A2A stream contains invalid JSON".into()))?)?; data.clear();
                        if value.get("task").is_some() { remembered = Some(parse_task(value.clone())?); }
                        if let Some(task) = remembered.as_mut() {
                            if let Some(artifact) = value.pointer("/artifactUpdate/artifact") {
                                if !task.raw["artifacts"].is_array() { task.raw["artifacts"] = json!([]); }
                                task.raw["artifacts"].as_array_mut().unwrap().push(artifact.clone());
                            }
                            if let Some(status) = value.pointer("/statusUpdate/status") { task.raw["status"] = status.clone(); }
                            *task = parse_task(task.raw.clone())?;
                            peer.task_store.save(&peer.name, &key, task).await?;
                        }
                        if let Some(event) = protocol::event(&peer.name, value)? { yield event; }
                    }
                }
                if done { break; }
            }
        }))
    }
    pub fn function_tool(&self) -> FunctionTool {
        self.function_tool_with_events(None)
    }
    pub(crate) fn function_tool_with_events(
        &self,
        events: Option<Arc<dyn Fn(Value) + Send + Sync>>,
    ) -> FunctionTool {
        let peer = self.clone();
        let suffix: String = self
            .name
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
                    c
                } else {
                    '_'
                }
            })
            .collect();
        let name: String = format!("a2a__{}", suffix.trim_matches('_'))
            .chars()
            .take(64)
            .collect();
        let card = self
            .card
            .try_read()
            .ok()
            .and_then(|v| v.as_ref().map(|(_, card)| card.clone()))
            .unwrap_or(Value::Null);
        let mut description = self
            .description
            .clone()
            .or_else(|| card["description"].as_str().map(str::to_owned))
            .unwrap_or_else(|| format!("Collaborate with independent A2A peer {}.", self.name));
        if let Some(skills) = card.get("skills") {
            description.push_str(&format!(" Available skills: {skills}"));
        }
        FunctionTool::new(name, description,
            json!({"type":"object","properties":{"input":{},"skill":{"type":["string","null"]},"task_id":{"type":["string","null"]},"context_id":{"type":["string","null"]}},"required":["input"],"additionalProperties":false}),
            move |arguments, context| { let peer = peer.clone(); let events = events.clone(); async move {
                if let Some(callback) = &events { callback(json!({"type":"a2a.task.started","peer_name":peer.name})); }
                let task = peer.run_with_options(arguments["input"].clone(), A2ARunOptions {
                    skill: arguments["skill"].as_str().map(str::to_owned), task_id: arguments["task_id"].as_str().map(str::to_owned),
                    context_id: arguments["context_id"].as_str().map(str::to_owned) }, &context).await?;
                if let Some(callback) = &events { callback(json!({"type":if task.input_required() {"a2a.task.input_required"} else {"a2a.task.completed"},"peer_name":peer.name,"task_id":task.id,"state":task.state,"output":task.output,"data":{"task":task.raw}})); }
                serde_json::to_value(task).map_err(|_| Error::A2A("Could not serialize A2A task".into()))
            } }).permissions(self.permissions.clone()).timeout_ms(self.timeout.as_millis().min(u64::MAX as u128) as u64)
    }

    pub(crate) fn graph_definition(&self) -> Value {
        let card = self
            .card
            .try_read()
            .ok()
            .and_then(|v| v.as_ref().map(|(_, card)| card.clone()))
            .unwrap_or(Value::Null);
        let mut safe = serde_json::Map::new();
        for key in [
            "name",
            "description",
            "version",
            "protocolVersion",
            "capabilities",
            "skills",
        ] {
            if let Some(value) = card.get(key) {
                safe.insert(key.into(), value.clone());
            }
        }
        json!({"name":self.name,"tool_name":self.function_tool().name,"description":self.description.as_deref().or_else(||card["description"].as_str()),"agent_card":safe,"permissions":self.permissions})
    }
    fn check_permissions(&self, context: &ToolContext) -> Result<()> {
        for permission in &self.permissions {
            if !context.permissions.contains(permission) {
                return Err(Error::PermissionRequired(permission.clone()));
            }
        }
        Ok(())
    }
    fn message(
        &self,
        card: &Value,
        input: Value,
        options: A2ARunOptions,
        context: &ToolContext,
    ) -> Result<Value> {
        if let Some(skill) = &options.skill {
            if !self.policy.allowed_skills.is_empty() && !self.policy.allowed_skills.contains(skill)
            {
                return Err(Error::A2A("A2A skill denied by local policy".into()));
            }
            if card["skills"].as_array().is_some_and(|items| {
                !items.is_empty() && !items.iter().any(|v| v["id"].as_str() == Some(skill))
            }) {
                return Err(Error::A2A(
                    "A2A peer does not publish requested skill".into(),
                ));
            }
        }
        let mut message = json!({"messageId":Uuid::new_v4().to_string(),"role":"ROLE_USER","parts":protocol::parts(redact(input,&self.policy.denied_fields)),
            "metadata":{"requested_skill":options.skill,"marona":{"user_id":context.user_id,"session_id":context.session_id,"developer_id":context.developer_id,"permissions":self.permissions}}});
        if let Some(id) = options.task_id {
            message["taskId"] = json!(id);
        }
        if let Some(id) = options.context_id {
            message["contextId"] = json!(id);
        }
        Ok(
            json!({"message":message,"configuration":{"returnImmediately":false},"metadata":{"peer":self.name}}),
        )
    }
    async fn request(
        &self,
        card: &Value,
        operation: &str,
        params: Value,
        path: &str,
        get: bool,
    ) -> Result<Value> {
        let (endpoint, rpc) = endpoint(card, &self.url);
        validate_host(&endpoint, &self.policy).await?;
        let body = if rpc {
            rpc_body(operation, params)
        } else {
            params
        };
        self.check_size(&body)?;
        let target = if rpc {
            endpoint
        } else {
            format!("{}/{}", endpoint.trim_end_matches('/'), path)
        };
        let request = if !rpc && get {
            self.client.get(target)
        } else {
            self.client.post(target).json(&body)
        };
        let request = self.headers(request, false)?.timeout(self.timeout);
        for attempt in 0..=self.max_retries {
            match request
                .try_clone()
                .ok_or_else(|| Error::A2A("A2A request cannot be replayed".into()))?
                .send()
                .await
            {
                Ok(response) => return unwrap(self.read(response).await?),
                Err(error)
                    if attempt < self.max_retries && (error.is_timeout() || error.is_connect()) =>
                {
                    tokio::time::sleep(Duration::from_millis(
                        (250u64.saturating_mul(2u64.saturating_pow(attempt.min(3) as u32)))
                            .min(2000),
                    ))
                    .await
                }
                Err(error) => return Err(error.into()),
            }
        }
        Err(Error::A2A("A2A request failed".into()))
    }
    fn headers(
        &self,
        request: reqwest::RequestBuilder,
        public: bool,
    ) -> Result<reqwest::RequestBuilder> {
        let mut request = request
            .header("A2A-Version", "1.0")
            .header("Content-Type", "application/a2a+json");
        if !public || self.send_credentials_with_card {
            if let Some(token) = &self.bearer_token {
                if token.trim().is_empty() {
                    return Err(Error::A2A("A2A bearer token is required".into()));
                }
                request = request.bearer_auth(token);
            } else if let Some((header, key)) = &self.api_key {
                if key.trim().is_empty() {
                    return Err(Error::A2A("A2A API key is required".into()));
                }
                request = request.header(header, key);
            }
        }
        Ok(request)
    }
    fn check_size(&self, body: &Value) -> Result<()> {
        if body.to_string().len() > self.policy.max_request_bytes {
            return Err(Error::A2A("A2A request exceeds byte limit".into()));
        }
        Ok(())
    }
    async fn read(&self, response: reqwest::Response) -> Result<Value> {
        if !response.status().is_success() {
            return Err(Error::A2A(format!(
                "A2A peer returned HTTP {}",
                response.status()
            )));
        }
        let mut stream = response.bytes_stream();
        let mut bytes = vec![];
        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            if bytes.len() + chunk.len() > self.policy.max_response_bytes {
                return Err(Error::A2A("A2A response exceeds byte limit".into()));
            }
            bytes.extend_from_slice(&chunk);
        }
        serde_json::from_slice(&bytes).map_err(|_| Error::A2A("Invalid A2A JSON response".into()))
    }
}
fn session(context: &ToolContext) -> String {
    json!([context.developer_id, context.user_id, context.session_id]).to_string()
}
fn encode(value: &str) -> String {
    url::form_urlencoded::byte_serialize(value.as_bytes())
        .collect::<String>()
        .replace('+', "%20")
}
fn rpc_body(method: &str, params: Value) -> Value {
    json!({"jsonrpc":"2.0","id":Uuid::new_v4().to_string(),"method":method,"params":params})
}

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
}