marona 5.5.0

Marona Agents, MCP server and App authoring, B2A, D2A, realtime and A2A
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
use crate::a2a_protocol::{parse_task, parts, parts_output};
use crate::{A2ARequestContext, A2ATaskStore, Agent, Error, Result, Runner};
use axum::{
    body::Bytes,
    extract::{DefaultBodyLimit, OriginalUri, State},
    http::{HeaderMap, Method, StatusCode},
    response::{sse::Event, IntoResponse, Response, Sse},
    routing::any,
    Json, Router,
};
use serde_json::{json, Value};
use std::{convert::Infallible, future::Future, pin::Pin, sync::Arc};
use uuid::Uuid;

type HandlerFuture = Pin<Box<dyn Future<Output = Result<Value>> + Send>>;
type Executor = Arc<dyn Fn(Value, A2ARequestContext) -> HandlerFuture + Send + Sync>;
type Legacy = Arc<dyn Fn(Value) -> HandlerFuture + Send + Sync>;

#[derive(Clone)]
pub struct A2AServer {
    pub agent_card: Value,
    executor: Option<Executor>,
    legacy: Option<Legacy>,
    api_key: Option<String>,
    store: A2ATaskStore,
    max_request_bytes: usize,
    store_lock: Arc<tokio::sync::Mutex<()>>,
}
impl A2AServer {
    /// Low-level handler receives SendMessage parameters and returns a Task or task envelope.
    pub fn new<F, Fut>(agent_card: Value, handler: F) -> Self
    where
        F: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Value>> + Send + 'static,
    {
        Self {
            agent_card,
            executor: None,
            legacy: Some(Arc::new(move |value| Box::pin(handler(value)))),
            api_key: None,
            store: A2ATaskStore::default(),
            max_request_bytes: 1_000_000,
            store_lock: Arc::new(tokio::sync::Mutex::new(())),
        }
    }
    pub fn with_executor<F, Fut>(agent_card: Value, executor: F) -> Self
    where
        F: Fn(Value, A2ARequestContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Value>> + Send + 'static,
    {
        Self {
            agent_card,
            executor: Some(Arc::new(move |value, context| {
                Box::pin(executor(value, context))
            })),
            legacy: None,
            api_key: None,
            store: A2ATaskStore::default(),
            max_request_bytes: 1_000_000,
            store_lock: Arc::new(tokio::sync::Mutex::new(())),
        }
    }
    pub fn from_agent(agent: Agent, skills: Vec<Value>, url: &str) -> Result<Self> {
        if skills.is_empty()
            || skills
                .iter()
                .any(|v| v["id"].as_str().unwrap_or("").is_empty())
        {
            return Err(Error::Validation(
                "A2A server requires published skills with IDs".into(),
            ));
        }
        let card = json!({"name":agent.name,"description":agent.description.clone().unwrap_or_else(|| agent.name.clone()),"version":"1.0.0","protocolVersion":"1.0","url":url,
            "supportedInterfaces":[{"url":url,"protocolBinding":"HTTP+JSON","protocolVersion":"1.0"},{"url":format!("{}/rpc",url.trim_end_matches('/')),"protocolBinding":"JSONRPC","protocolVersion":"1.0"}],
            "capabilities":{"streaming":true,"pushNotifications":false},"defaultInputModes":["text/plain","application/json"],"defaultOutputModes":["text/plain","application/json"],"skills":skills});
        Ok(Self::with_executor(card, move |input, context| {
            let agent = agent.clone();
            async move {
                let input = if agent.input_schema.is_none() && !input.is_string() {
                    json!(input.to_string())
                } else {
                    input
                };
                let result = Runner::run(
                    &agent,
                    input,
                    context.user_id.as_deref(),
                    Some(&context.session_id),
                )
                .await?;
                Ok(result.output)
            }
        }))
    }
    pub fn api_key(mut self, value: impl Into<String>) -> Result<Self> {
        let key = value.into();
        if key.trim().is_empty() {
            return Err(Error::Validation("A2A API key cannot be empty".into()));
        }
        self.api_key = Some(key);
        Ok(self)
    }
    pub fn task_store(mut self, store: A2ATaskStore) -> Self {
        self.store = store;
        self
    }
    pub fn max_request_bytes(mut self, value: usize) -> Result<Self> {
        if value == 0 {
            return Err(Error::Validation(
                "A2A request limit must be positive".into(),
            ));
        }
        self.max_request_bytes = value;
        Ok(self)
    }
    pub fn router(self) -> Router {
        Router::new()
            .route("/", any(handle))
            .route("/{*path}", any(handle))
            .layer(DefaultBodyLimit::max(self.max_request_bytes))
            .with_state(Arc::new(self))
    }
    fn namespace(&self) -> String {
        format!(
            "server:{}",
            self.agent_card["name"].as_str().unwrap_or("agent")
        )
    }
    async fn execute(&self, request: Value) -> Result<Value> {
        let message = &request["message"];
        let id = message["taskId"]
            .as_str()
            .map(str::to_owned)
            .unwrap_or_else(|| Uuid::new_v4().to_string());
        let context_id = message["contextId"].as_str().unwrap_or(&id).to_owned();
        {
            let _lock = self.store_lock.lock().await;
            if let Some(previous) = self.store.latest(&self.namespace(), &id).await? {
                if previous.state == "TASK_STATE_CANCELED" {
                    return Ok(json!({"task":previous.raw}));
                }
            }
            self.store
                .save(
                    &self.namespace(),
                    &id,
                    &parse_task(task(
                        &id,
                        &context_id,
                        "TASK_STATE_WORKING",
                        Value::Null,
                        None,
                    ))?,
                )
                .await?;
        }
        let skill = message["metadata"]["requested_skill"]
            .as_str()
            .map(str::to_owned);
        let published = skill.as_ref().is_none_or(|skill| {
            self.agent_card["skills"]
                .as_array()
                .into_iter()
                .flatten()
                .any(|v| v["id"].as_str() == Some(skill))
        });
        let mut raw;
        if !published {
            raw = task(
                &id,
                &context_id,
                "TASK_STATE_REJECTED",
                Value::Null,
                Some("Requested skill is not published"),
            );
        } else {
            let metadata = message.get("metadata").cloned().unwrap_or(json!({}));
            let marona = &metadata["marona"];
            let context = A2ARequestContext {
                task_id: id.clone(),
                context_id: context_id.clone(),
                skill,
                user_id: marona["user_id"].as_str().map(str::to_owned),
                session_id: marona["session_id"].as_str().unwrap_or(&context_id).into(),
                metadata,
            };
            let result = if let Some(executor) = &self.executor {
                executor(parts_output(&message["parts"]), context).await
            } else {
                (self.legacy.as_ref().unwrap())(request).await
            };
            raw = match result {
                Ok(output) if self.legacy.is_some() => parse_task(output)?.raw,
                Ok(output) => task(&id, &context_id, "TASK_STATE_COMPLETED", output, None),
                Err(
                    Error::PermissionRequired(_)
                    | Error::ApprovalRequired(_)
                    | Error::ServiceConnectionRequired(_),
                ) => task(
                    &id,
                    &context_id,
                    "TASK_STATE_INPUT_REQUIRED",
                    Value::Null,
                    Some("Agent requires additional authorization or input"),
                ),
                Err(_) => task(
                    &id,
                    &context_id,
                    "TASK_STATE_FAILED",
                    Value::Null,
                    Some("Agent execution failed"),
                ),
            };
        }
        {
            let _lock = self.store_lock.lock().await;
            if let Some(current) = self.store.latest(&self.namespace(), &id).await? {
                if current.state == "TASK_STATE_CANCELED" {
                    raw = current.raw;
                }
            }
            self.store
                .save(
                    &self.namespace(),
                    raw["id"].as_str().unwrap_or(&id),
                    &parse_task(raw.clone())?,
                )
                .await?;
        }
        Ok(json!({"task":raw}))
    }
}
async fn handle(
    State(server): State<Arc<A2AServer>>,
    OriginalUri(uri): OriginalUri,
    method: Method,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    let path = uri.path();
    if method == Method::GET
        && matches!(
            path,
            "/.well-known/agent-card.json" | "/.well-known/agent.json"
        )
    {
        return Json(server.agent_card.clone()).into_response();
    }
    if let Some(key) = &server.api_key {
        if headers.get("authorization").and_then(|v| v.to_str().ok())
            != Some(&format!("Bearer {key}"))
        {
            return (
                StatusCode::UNAUTHORIZED,
                Json(json!({"error":{"message":"A2A authentication required"}})),
            )
                .into_response();
        }
    }
    let rpc = path == "/rpc";
    if method == Method::GET && path.starts_with("/tasks/") {
        return task_response(&server, &decode(&path[7..]), false, false, Value::Null).await;
    }
    if method != Method::POST {
        return StatusCode::METHOD_NOT_ALLOWED.into_response();
    }
    let payload: Value = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error":{"message":"Invalid JSON"}})),
            )
                .into_response()
        }
    };
    let id = payload.get("id").cloned().unwrap_or(Value::Null);
    let operation = payload["method"].as_str().unwrap_or("");
    let params = if rpc {
        payload.get("params").cloned().unwrap_or(Value::Null)
    } else {
        payload.clone()
    };
    if !params.is_object() {
        return StatusCode::BAD_REQUEST.into_response();
    }
    if rpc && matches!(operation, "GetTask" | "CancelTask") {
        return task_response(
            &server,
            params["id"].as_str().unwrap_or(""),
            operation == "CancelTask",
            true,
            id,
        )
        .await;
    }
    if !rpc && path.starts_with("/tasks/") && path.ends_with(":cancel") {
        return task_response(&server, &decode(&path[7..path.len() - 7]), true, false, id).await;
    }
    let streaming = path == "/message:stream" || (rpc && operation == "SendStreamingMessage");
    if streaming || path == "/message:send" || (rpc && operation == "SendMessage") {
        if !params["message"].is_object() || !params["message"]["parts"].is_array() {
            return StatusCode::BAD_REQUEST.into_response();
        }
        if streaming {
            return streaming_response(server, params, rpc, id);
        }
        return match server.execute(params).await {
            Ok(value) => Json(envelope(value, rpc, id)).into_response(),
            Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
        };
    }
    if rpc {
        Json(json!({"jsonrpc":"2.0","id":id,"error":{"code":-32601,"message":"Method not found"}}))
            .into_response()
    } else {
        StatusCode::NOT_FOUND.into_response()
    }
}
async fn task_response(
    server: &A2AServer,
    id: &str,
    cancel: bool,
    rpc: bool,
    rpc_id: Value,
) -> Response {
    let _lock = server.store_lock.lock().await;
    match server.store.latest(&server.namespace(), id).await {
        Ok(Some(mut task)) => {
            if cancel {
                task.raw["status"] = json!({"state":"TASK_STATE_CANCELED"});
                let parsed = match parse_task(task.raw.clone()) {
                    Ok(v) => v,
                    Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
                };
                if server
                    .store
                    .save(&server.namespace(), id, &parsed)
                    .await
                    .is_err()
                {
                    return StatusCode::INTERNAL_SERVER_ERROR.into_response();
                }
            }
            Json(envelope(json!({"task":task.raw}), rpc, rpc_id)).into_response()
        }
        Ok(None) if rpc => Json(
            json!({"jsonrpc":"2.0","id":rpc_id,"error":{"code":-32001,"message":"Task not found"}}),
        )
        .into_response(),
        Ok(None) => StatusCode::NOT_FOUND.into_response(),
        Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
    }
}
fn streaming_response(
    server: Arc<A2AServer>,
    mut params: Value,
    rpc: bool,
    rpc_id: Value,
) -> Response {
    let id = params["message"]["taskId"]
        .as_str()
        .map(str::to_owned)
        .unwrap_or_else(|| Uuid::new_v4().to_string());
    let context_id = params["message"]["contextId"]
        .as_str()
        .unwrap_or(&id)
        .to_owned();
    params["message"]["taskId"] = json!(id);
    params["message"]["contextId"] = json!(context_id);
    Sse::new(async_stream::stream! {
        let started = json!({"task":task(&id,&context_id,"TASK_STATE_WORKING",Value::Null,None)});
        yield Ok::<_,Infallible>(Event::default().data(envelope(started,rpc,rpc_id.clone()).to_string()));
        let result = match server.execute(params).await { Ok(v) => v, Err(_) => json!({"task":task(&id,&context_id,"TASK_STATE_FAILED",Value::Null,Some("Agent execution failed"))}) };
        for artifact in result["task"]["artifacts"].as_array().into_iter().flatten() {
            yield Ok(Event::default().data(envelope(json!({"artifactUpdate":{"taskId":id,"contextId":context_id,"artifact":artifact}}),rpc,rpc_id.clone()).to_string()));
        }
        yield Ok(Event::default().data(envelope(json!({"statusUpdate":{"taskId":id,"contextId":context_id,"status":result["task"]["status"]}}),rpc,rpc_id).to_string()));
    }).into_response()
}
fn task(id: &str, context_id: &str, state: &str, output: Value, message: Option<&str>) -> Value {
    let mut value = json!({"id":id,"contextId":context_id,"status":{"state":state},"metadata":{"framework":"marona"}});
    if let Some(message) = message {
        value["status"]["message"] = json!({"messageId":Uuid::new_v4().to_string(),"role":"ROLE_AGENT","parts":parts(json!(message))});
    }
    if !output.is_null() {
        value["artifacts"] = json!([{"artifactId":Uuid::new_v4().to_string(),"name":"result","parts":parts(output)}]);
    }
    value
}
fn envelope(value: Value, rpc: bool, id: Value) -> Value {
    if rpc {
        json!({"jsonrpc":"2.0","id":id,"result":value})
    } else {
        value
    }
}
fn decode(value: &str) -> String {
    url::form_urlencoded::parse(format!("v={value}").as_bytes())
        .next()
        .map(|(_, v)| v.into_owned())
        .unwrap_or_default()
}