marona 4.0.0

Universal Model Gateway and MCP/Skill SDK with mandatory project-scoped Marona authentication
Documentation

Marona Rust SDK

Run Agents through one managed API, with structured output, local tools, Hub capabilities, streaming, realtime and A2A collaboration.

Install

Version 4.0.0. Package registry.

Rust 1.89+ with the bundled dependency lockfile. A2A servers require the a2a feature (enabled by default).

[dependencies]
marona = "4.0.0"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde_json = "1"
base64 = "0.22"

Set MARONA_API_KEY in your backend environment. Never commit it, log it, or embed a developer key in browser or mobile code. Use an exact accessible marona/* model alias from Marona Platform.

Agent quickstart

Save as examples/agent_example.rs. Run without arguments for text, or with a real PNG/JPEG path for document extraction. Use stable application user IDs and a distinct session ID for each conversation.

use base64::{engine::general_purpose::STANDARD, Engine as _};
use marona::{Agent, Input, Marona, Runner, ToolChoice};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let marona = Marona::builder()
        .runtime_url(
            std::env::var("MARONA_RUNTIME_URL").unwrap_or_else(|_| "https://edge.marona.ai".into()),
        )
        .build()?;
    let agent = Agent::new(&marona, "Document Assistant")
        .model(
            std::env::var("MARONA_MODEL").unwrap_or_else(|_| "marona/qwen-qwen3.8-max-0902".into()),
        )
        .instructions("Answer clearly and concisely.")
        .tool_choice(ToolChoice::None);
    let mut input = Input::from("Reply with exactly OK.");
    if let Some(path) = std::env::args().nth(1) {
        let extension = std::path::Path::new(&path)
            .extension()
            .and_then(|value| value.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        let mime = match extension.as_str() {
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            _ => return Err("Use a PNG or JPEG image.".into()),
        };
        let data_url = format!(
            "data:{mime};base64,{}",
            STANDARD.encode(std::fs::read(path)?)
        );
        input = Input::Message(json!({"role": "user", "content": [
            {"type": "input_text", "text": "Describe this image and transcribe any visible text."},
            {"type": "input_image", "image_url": data_url}
        ]}));
    }
    let result = Runner::run(&agent, input, Some("example-user"), Some("example-session")).await?;
    println!("{}", result.output);
    Ok(())
}
cargo run --example agent_example
cargo run --example agent_example -- image.png

Encode actual file bytes with standard Base64. Image and file blocks accept raw Base64 in image_data / file_data, or complete matching data URLs. Do not encode a path, encode twice, or send placeholder data. Remote URLs must be reachable by the runtime. PDF, audio and realtime support depend on the selected model; render PDF pages to images when native PDF is unavailable.

Structured output through Agent

The following fragment uses the authenticated client from the quickstart. document_input is your text or document message input.

use marona::{Agent, Runner};
use serde_json::json;

let agent = Agent::new(&marona, "Document Reader")
    .model("marona/qwen-qwen3.8-max-0902")
    .instructions("Extract the document text.")
    .output_schema(json!({
        "type": "object", "properties": {"text": {"type": "string"}},
        "required": ["text"], "additionalProperties": false
    })).output_schema_strict(true);
let result = Runner::run(&agent, document_input, Some("user-123"), Some("document-123")).await?;
println!("{}", result.output["text"]);

The explicit strict option asks the provider to enforce the supplied schema; the SDK also validates the final result before returning it. Strict mode requires a compatible model and schema. Declare every object property as required, use nullable values for optional fields, and set additionalProperties to false. Unsupported model capabilities or invalid output produce errors; they do not silently fall back to unstructured text. Input schemas, function tool schemas, guardrails, dynamic instructions and lifecycle hooks are also supported.

Apps and user connections

use marona::AppsListOptions;
use serde_json::json;

let page = marona.apps.list(AppsListOptions {
    user_id: Some("user-123".into()), limit: Some(20), ..Default::default()
}).await?;
let action = marona.apps.connect("calendar", json!({"user_id":"user-123"})).await?;
// Complete any returned authorization_url before calling protected tools.
marona.apps.disconnect("calendar").await?;

Listing an App does not authorize its protected operations. Follow the returned connection action for the end user. Use hub.connect to expose a scoped set of App or Skill capabilities to an Agent; Apps authorization and Hub tool discovery are separate operations.

A2A collaboration and serving

use marona::{A2APeer, A2AServer, A2ATaskStore, Agent};
use serde_json::json;

let peer = A2APeer::new("reviewer", "https://reviewer.example.com")?;
let agent = Agent::new(&marona, "Coordinator").peer(peer);
let server = A2AServer::from_agent(agent, vec![json!({
    "id":"review", "name":"Review", "description":"Review a document"
})], "https://coordinator.example.com")?
    .api_key(std::env::var("A2A_SERVER_KEY")?)?
    .task_store(A2ATaskStore::new("./data/a2a-tasks"));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8100").await?;
axum::serve(listener, server.router()).await?;

Peers support Agent Card discovery, REST/JSON-RPC messages, task retrieval, cancellation, continuation and streamed task events. Servers persist task state. Use explicit credentials, restricted skills, HTTPS, and an appropriate durable task directory for production. Local JSON stores are for a single service instance; multi-instance deployments require coordinated task storage.

Serving requires the a2a feature and an application axum = "0.8" dependency for the shown hosting code. Push notifications are not implemented.

Brain2Agent (B2A)

Native B2A v0.1 exchanges decoded semantic intent and agent responses. The independent neural service owns signal decoding and feedback encoding, with vendor-hosted MCP, HTTP or local plugin backends. Models and device drivers are supplied by the interface provider. Configure Agent.b2a and connect with B2ARunner, following the persistent realtime session lifecycle. These examples read one captured signal file using your configured provider.

Save as examples/b2a_intent.rs:

use marona::{
    Agent, B2ACodec, B2ACodecOptions, B2ACodecTransport, B2ARunner, ConnectOptions, Marona, B2A,
};
use serde_json::Value;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let signal: Value = serde_json::from_str(&std::fs::read_to_string(
        std::env::args()
            .nth(1)
            .ok_or("Provide a captured signal JSON file")?,
    )?)?;
    let client = Marona::builder().build()?;
    let options = B2ACodecOptions {
        transport: if std::env::var("B2A_CODEC_TRANSPORT").unwrap_or_else(|_| "mcp".into()) == "mcp"
        {
            B2ACodecTransport::Mcp
        } else {
            B2ACodecTransport::Http
        },
        ..Default::default()
    };
    let neural_service = B2ACodec::with_options(
        &std::env::var("B2A_CODEC_URL")?,
        &std::env::var("B2A_NEURAL_TOKEN")?,
        options,
    )?;
    let agent = Agent::new(&client, "B2A Intent Agent")
        .model(std::env::var("MARONA_MODEL").unwrap_or_else(|_| "marona/auto".into()))
        .instructions("Interpret decoded intent in context. Preserve uncertainty and use connected tools under Marona permissions.")
        .hub_tools(client.hub.connect(ConnectOptions::default()).await?)
        .b2a(B2A::new(neural_service, std::env::var("B2A_OUTPUT_PROFILE")?));
    let mut session = B2ARunner::connect(
        &agent,
        &std::env::var("B2A_USER_ID")?,
        &std::env::var("B2A_SESSION_ID")?,
    )
    .await?;
    let result = async {
        session.send_signal(&signal).await?;
        while let Some(event) = session.next_event().await? {
            println!("{event:?}");
            if ["feedback", "signal.status", "error"].contains(&event.event_type.as_str()) {
                break;
            }
        }
        Ok::<_, marona::Error>(())
    }
    .await;
    session.close().await?;
    result?;
    Ok(())
}

The SDK manages protocol messages, sequencing, event cursors, decoding and encoding. Set B2A_CODEC_URL, B2A_NEURAL_TOKEN, B2A_OUTPUT_PROFILE, B2A_USER_ID and B2A_SESSION_ID. Use B2A_CODEC_TRANSPORT=mcp or http. session_id identifies an application conversation; each connection gets a separate native transport session. The application authorizes processing before connecting; device and protocol scope fields are supplied internally. Closing revokes those scopes.

Keep the session open to send more signals. Feedback events contain encoded output; printing them does not deliver feedback. An interface driver acknowledges presentation only after delivery. Failed or uncertain sends are never replayed automatically. Native B2A supports server-hosted Hub tools and agent graphs; SDK-local functions, callbacks and peer callbacks require server-hosted equivalents. B2A v0.1 uses HTTP JSON and retained cursor events, not WebSocket transport. See the repository's docs/b2a-protocol.md for the complete wire contract.

Execution and errors

Use Runner::stream for streamed Agent events and RealtimeRunner for a live session. Delegation and handoffs use explicit Agent graphs. Set execution limits and validate permissions before tools with side effects; cancellation cannot roll back an operation that has already executed.

Inspect the canonical error code, HTTP status, request ID and retry metadata. Correct invalid input and authorization errors before retrying. Use bounded retries for transient failures. Never include credentials or document content in error reports.

See Platform documentation for language specific examples and migration guidance. These files are generated from docs/client-sdk-guides.json; verify them with python scripts/sync_client_sdk_docs.py --check.

Rust 4.0 renames the low-level B2A client to B2AClient. B2A now configures Agent.b2a; Marona.b2a continues to expose low-level operations.