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
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
//! Typed decoder/encoder access over HTTP or MCP; models remain with their provider.
use crate::{B2AIntent, B2AMessage, Error, Result};
use reqwest::{
    header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE},
    redirect::Policy,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::time::Duration;

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum B2ADecodeStatus {
    Decoded,
    Abstain,
    PoorSignal,
    CalibrationRequired,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2ADecodeResult {
    pub status: B2ADecodeStatus,
    pub intent: Option<B2AIntent>,
    #[serde(default)]
    pub message: Option<B2AMessage>,
    pub provenance: Value,
    pub uncertainty: Value,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AEncodedFeedback {
    pub feedback_id: String,
    pub profile: String,
    pub media_type: String,
    pub content: Value,
    pub provenance: Value,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum B2ACodecTransport {
    #[default]
    Http,
    Mcp,
}
#[derive(Clone, Debug)]
pub struct B2ACodecOptions {
    pub transport: B2ACodecTransport,
    pub timeout: Duration,
    pub decode_tool: String,
    pub encode_tool: String,
    pub decode_path: String,
    pub encode_path: String,
    pub allow_simulation: bool,
}
impl Default for B2ACodecOptions {
    fn default() -> Self {
        Self {
            transport: B2ACodecTransport::Http,
            timeout: Duration::from_secs(60),
            decode_tool: "decode".into(),
            encode_tool: "encode".into(),
            decode_path: "/v1/decode".into(),
            encode_path: "/v1/encode".into(),
            allow_simulation: false,
        }
    }
}
/// A bounded, non-retrying connection with a separate neural-service credential.
#[derive(Clone)]
pub struct B2ACodec {
    url: String,
    client: reqwest::Client,
    options: B2ACodecOptions,
}
impl B2ACodec {
    pub fn new(url: &str, token: &str) -> Result<Self> {
        Self::with_options(url, token, B2ACodecOptions::default())
    }
    pub fn with_options(url: &str, token: &str, options: B2ACodecOptions) -> Result<Self> {
        let parsed = url::Url::parse(url).map_err(|_| bad("Invalid codec URL"))?;
        if !["http", "https"].contains(&parsed.scheme())
            || parsed.host_str().is_none()
            || !parsed.username().is_empty()
            || parsed.password().is_some()
            || parsed.query().is_some()
            || parsed.fragment().is_some()
        {
            return Err(bad("Invalid codec endpoint"));
        }
        if parsed.scheme() == "http"
            && !["localhost", "127.0.0.1", "[::1]", "::1"]
                .contains(&parsed.host_str().unwrap_or(""))
        {
            return Err(bad("Remote codec endpoints require HTTPS"));
        }
        for text in [token, &options.decode_tool, &options.encode_tool] {
            nonempty(text)?;
        }
        for path in [&options.decode_path, &options.encode_path] {
            if !path.starts_with('/') || path.starts_with("//") || path.contains(['?', '#', '\\']) {
                return Err(bad("Invalid codec path"));
            }
        }
        if options.timeout.is_zero() {
            return Err(bad("Codec timeout must be positive"));
        }
        let mut headers = HeaderMap::new();
        let mut auth = HeaderValue::from_str(&format!("Bearer {token}"))
            .map_err(|_| bad("Invalid neural credential"))?;
        auth.set_sensitive(true);
        headers.insert(AUTHORIZATION, auth);
        headers.insert(
            ACCEPT,
            HeaderValue::from_static("application/json, text/event-stream"),
        );
        let client = reqwest::Client::builder()
            .default_headers(headers)
            .redirect(Policy::none())
            .timeout(options.timeout)
            .build()?;
        Ok(Self {
            url: parsed.as_str().trim_end_matches('/').into(),
            client,
            options,
        })
    }
    pub async fn decode(&self, signal: &Value, consent: bool) -> Result<B2ADecodeResult> {
        require_consent(consent)?;
        object(Some(signal))?;
        let data = self
            .call("decode", json!({"signal":signal,"consent":true}))
            .await?;
        let status: B2ADecodeStatus =
            serde_json::from_value(data.get("status").cloned().unwrap_or(Value::Null))
                .map_err(|_| bad("Invalid decoder status"))?;
        let provenance = self.provenance(data.get("provenance"))?;
        let uncertainty = Value::Object(object(data.get("uncertainty"))?);
        if let Some(message) = data.get("message").filter(|v| !v.is_null()) {
            if status != B2ADecodeStatus::Decoded {
                return Err(bad("An abstaining decoder cannot return a message"));
            }
            let mut body = serde_json::to_value(B2AMessage::from_value(message.clone())?)
                .map_err(|e| bad(&e.to_string()))?;
            body["payload"]["provenance"] = provenance.clone();
            body["payload"]["uncertainty"] = uncertainty.clone();
            for block in body["payload"]["content"].as_array_mut().unwrap() {
                if block["uri"].as_str().is_some_and(|v| v.starts_with("b2a:")) {
                    let resource = self
                        .call("read_resource", json!({"uri":block["uri"],"consent":true}))
                        .await?;
                    if resource["type"] != block["type"]
                        || resource["mime_type"] != block["mime_type"]
                        || resource["uri"]
                            .as_str()
                            .is_some_and(|v| v.starts_with("b2a:"))
                    {
                        return Err(bad("Resource resolution must preserve type/MIME and return inline data or HTTPS"));
                    }
                    let target = block.as_object_mut().unwrap();
                    if resource.get("data").is_some() {
                        target.remove("uri");
                    }
                    target.extend(resource.as_object().unwrap().clone());
                }
            }
            return Ok(B2ADecodeResult {
                status,
                intent: None,
                message: Some(B2AMessage::from_value(body)?),
                provenance,
                uncertainty,
            });
        }
        let content = data.get("intent").cloned().unwrap_or(Value::Null);
        let intent = if status == B2ADecodeStatus::Decoded {
            if content.as_object().is_some_and(Map::is_empty) {
                return Err(bad("Decoder returned empty intent"));
            }
            let mut intent = B2AIntent::new(content)?;
            if let Some(confidence) = data.get("confidence").filter(|v| !v.is_null()) {
                intent = intent.with_confidence(
                    confidence
                        .as_f64()
                        .ok_or_else(|| bad("Invalid decoder confidence"))?,
                )?;
            }
            let mut metadata = object(Some(&provenance))?;
            metadata.insert("uncertainty".into(), uncertainty.clone());
            if let Some(id) = signal.get("signal_id").filter(|v| !v.is_null()) {
                metadata.insert("signal_id".into(), json!(text(Some(id))?));
            }
            let mut decoder = Map::new();
            for (key, source) in [("id", "backend"), ("version", "version")] {
                if let Some(value) = provenance.get(source).filter(|v| !v.is_null()) {
                    decoder.insert(key.into(), json!(text(Some(value))?));
                }
            }
            if !decoder.is_empty() {
                intent.decoder = Some(Value::Object(decoder));
            }
            intent.provenance = Some(Value::Object(metadata));
            intent.validate()?;
            Some(intent)
        } else {
            if !content.is_null() {
                return Err(bad("Abstaining decoder returned actionable intent"));
            }
            None
        };
        Ok(B2ADecodeResult {
            status,
            intent,
            message: None,
            provenance,
            uncertainty,
        })
    }
    pub async fn encode(
        &self,
        response: &Value,
        profile: &str,
        consent: bool,
    ) -> Result<B2AEncodedFeedback> {
        self.encode_with(
            response,
            profile,
            consent,
            &json!({}),
            &["application/json"],
        )
        .await
    }
    pub async fn encode_with(
        &self,
        response: &Value,
        profile: &str,
        consent: bool,
        context: &Value,
        media_types: &[&str],
    ) -> Result<B2AEncodedFeedback> {
        require_consent(consent)?;
        nonempty(profile)?;
        object(Some(response))?;
        object(Some(context))?;
        if media_types.is_empty() {
            return Err(bad("At least one output media type is required"));
        }
        for media in media_types {
            nonempty(media)?;
        }
        let data = self.call("encode", json!({"request":{"response":response,"profile":profile,"context":context},"consent":true})).await?;
        let media_type = text(data.get("media_type"))?;
        if data.get("profile").and_then(Value::as_str) != Some(profile)
            || !media_types.contains(&media_type.as_str())
        {
            return Err(bad("Encoder output does not match interface capabilities"));
        }
        Ok(B2AEncodedFeedback {
            feedback_id: text(data.get("feedback_id"))?,
            profile: profile.into(),
            media_type,
            content: Value::Object(object(Some(data.get("content").unwrap_or(&Value::Null)))?),
            provenance: self.provenance(data.get("provenance"))?,
        })
    }
    fn provenance(&self, value: Option<&Value>) -> Result<Value> {
        let provenance = object(value)?;
        let flag = match provenance.get("simulation") {
            None => false,
            Some(Value::Bool(v)) => *v,
            _ => return Err(bad("Invalid neural provenance")),
        };
        if flag && !self.options.allow_simulation {
            return Err(bad("Neural output failed provenance validation"));
        }
        Ok(Value::Object(provenance))
    }
    async fn call(&self, operation: &str, arguments: Value) -> Result<Value> {
        tokio::time::timeout(self.options.timeout, self.exchange(operation, arguments))
            .await
            .map_err(|_| {
                Error::Timeout(self.options.timeout.as_millis().min(u64::MAX as u128) as u64)
            })?
    }
    async fn exchange(&self, operation: &str, arguments: Value) -> Result<Value> {
        if self.options.transport == B2ACodecTransport::Http {
            let path = if operation == "read_resource" {
                "/v1/resources/read"
            } else if operation == "decode" {
                &self.options.decode_path
            } else {
                &self.options.encode_path
            };
            let response = self
                .client
                .post(format!("{}{path}", self.url))
                .json(&arguments)
                .send()
                .await?;
            success(&response)?;
            let value: Value = response.json().await?;
            object(Some(&value))?;
            return Ok(value);
        }
        let mut headers = HeaderMap::new();
        let initialization = self.client.post(&self.url).json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
            "protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"marona","version":env!("CARGO_PKG_VERSION")}}})).send().await?;
        success(&initialization)?;
        if let Some(value) = initialization.headers().get("mcp-session-id") {
            headers.insert("mcp-session-id", value.clone());
        }
        let result = async {
            let initialized = rpc(initialization, 1).await?;
            let version = text(initialized.get("protocolVersion"))?;
            if !["2025-11-25", "2025-06-18", "2025-03-26"].contains(&version.as_str()) { return Err(bad("Unsupported MCP protocol version")); }
            headers.insert("MCP-Protocol-Version", HeaderValue::from_str(&version).map_err(|_| bad("Invalid MCP version"))?);
            let response = self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","method":"notifications/initialized"})).send().await?;
            success(&response)?; drop(response);
            let tool = if operation == "read_resource" { "read_resource" } else if operation == "decode" { &self.options.decode_tool } else { &self.options.encode_tool };
            let response = self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":tool,"arguments":arguments}})).send().await?;
            success(&response)?; let result = rpc(response, 2).await?;
            let structured = result.get("structuredContent").ok_or_else(|| bad("Missing MCP structured result"))?;
            if result.get("isError") == Some(&Value::Bool(true)) || structured.get("success") != Some(&Value::Bool(true)) { return Err(bad("Neural MCP tool failed")); }
            let data = structured.get("data").ok_or_else(|| bad("Missing neural result"))?; object(Some(data))?; Ok(data.clone())
        }.await;
        if headers.contains_key("mcp-session-id") {
            let _ = self
                .client
                .delete(&self.url)
                .headers(headers)
                .timeout(Duration::from_secs(1))
                .send()
                .await;
        }
        result
    }
}
fn bad(message: &str) -> Error {
    Error::Validation(message.into())
}
fn nonempty(value: &str) -> Result<()> {
    if value.trim().is_empty() {
        Err(bad("Expected nonempty codec text"))
    } else {
        Ok(())
    }
}
fn text(value: Option<&Value>) -> Result<String> {
    let text = value
        .and_then(Value::as_str)
        .ok_or_else(|| bad("Expected codec text"))?;
    nonempty(text)?;
    Ok(text.into())
}
fn object(value: Option<&Value>) -> Result<Map<String, Value>> {
    match value {
        None => Ok(Map::new()),
        Some(Value::Object(v)) => Ok(v.clone()),
        _ => Err(bad("Expected codec JSON object")),
    }
}
fn require_consent(value: bool) -> Result<()> {
    if value {
        Ok(())
    } else {
        Err(bad("Neural processing requires explicit consent"))
    }
}
fn success(response: &reqwest::Response) -> Result<()> {
    if response.status().is_success() {
        Ok(())
    } else {
        Err(bad(&format!(
            "Neural service returned HTTP {}",
            response.status().as_u16()
        )))
    }
}
fn rpc_value(value: Value, id: u64) -> Result<Option<Value>> {
    object(Some(&value))?;
    if value.get("id").and_then(Value::as_u64) != Some(id) {
        return Ok(None);
    }
    if value.get("jsonrpc").and_then(Value::as_str) != Some("2.0") || value.get("error").is_some() {
        return Err(bad("Neural MCP request failed"));
    }
    let result = value
        .get("result")
        .ok_or_else(|| bad("Missing MCP result"))?;
    object(Some(result))?;
    Ok(Some(result.clone()))
}
pub(crate) async fn rpc(mut response: reqwest::Response, id: u64) -> Result<Value> {
    if !response
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .contains("text/event-stream")
    {
        return rpc_value(response.json().await?, id)?
            .ok_or_else(|| bad("MCP response ID mismatch"));
    }
    let mut buffer = Vec::new();
    let mut data = Vec::new();
    let mut size = 0usize;
    while let Some(chunk) = response.chunk().await? {
        size += chunk.len();
        if size > 2_097_152 {
            return Err(bad("MCP response exceeds size limit"));
        }
        buffer.extend_from_slice(&chunk);
        while let Some(position) = buffer.iter().position(|v| *v == b'\n') {
            let line: Vec<u8> = buffer.drain(..=position).collect();
            let line = std::str::from_utf8(&line)
                .map_err(|_| bad("Invalid MCP UTF-8"))?
                .trim_end_matches(['\r', '\n']);
            if line.is_empty() {
                let payload = data.join("\n");
                if !payload.trim().is_empty() {
                    let value =
                        serde_json::from_str(&payload).map_err(|_| bad("Invalid MCP JSON"))?;
                    if let Some(result) = rpc_value(value, id)? {
                        return Ok(result);
                    }
                }
                data.clear();
            } else if let Some(value) = line.strip_prefix("data:") {
                data.push(value.strip_prefix(' ').unwrap_or(value).to_owned());
            }
        }
    }
    Err(bad("MCP stream ended without a matching response"))
}