marona 5.5.0

Marona Agents, MCP server and App authoring, B2A, D2A, realtime and A2A
Documentation

Marona Rust SDK

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

Install

Version 5.5.0. Package registry.

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

[dependencies]
marona = "5.5.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.

Build MCP servers and Apps

Use the same marona package to author MCP servers and register Apps on Marona Platform. The SDK owns the transport dependencies; do not add marona-sdk or a separate MCP package to application requirements. Existing marona-sdk applications can migrate their imports and dependency to marona; no platform migration is required.

MCPServer combines callable tools with /health, /manifest, and /hub-registration. HTTP uses the standard /mcp endpoint; stdio supports local MCP hosts. Hosting defaults to loopback. For a public service, configure the bind address, explicit allowed hosts/origins and authentication behind your HTTPS service boundary. A configured but missing server key rejects requests. Python MCP hosting requires Python 3.10+, TypeScript requires Node 20+, Dart HTTP hosting requires Dart IO, and Java requires Java 17+. The MCP wire version is negotiated with the client; these APIs support the 2025-11-25 protocol family.

use marona::{MCPServer, ToolBuilder};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = MCPServer::builder("Greeting Tools", "greeting-tools")
        .description("Return a greeting for a supplied name.")
        .api_key_env("MCP_SERVER_KEY")
        .tool(
            ToolBuilder::new(
                "greet",
                "Greet someone by name.",
                json!({
                    "type":"object", "properties":{"name":{"type":"string"}},
                    "required":["name"], "additionalProperties":false
                }),
            ),
            |args, _| async move {
                Ok(json!({"greeting": format!(
                    "Hello, {}.",
                    args["name"].as_str().unwrap()
                )}))
            },
        )?
        .build()?;
    if std::env::args().any(|arg| arg == "--stdio") {
        app.run_stdio().await?;
    } else {
        let port = std::env::var("MCP_PORT").unwrap_or_else(|_| "62900".into());
        app.serve(format!("127.0.0.1:{port}").parse()?).await?;
    }
    Ok(())
}

HTTP endpoint: /mcp Metadata: /health, /manifest, /hub-registration Set MCP_SERVER_KEY to a server token. Use Bearer or x-marona-api-key. Pass --stdio for a local MCP subprocess.

Register with Marona Platform

DeveloperPlatformClient uses a platform developer token. Register the metadata from the same running server, sync its tools, then submit for marketplace review when ready. Registration, submission and deployment are explicit API calls. The client also creates, lists, inspects and stops hosted deployments.

use marona::mcp::DeveloperPlatformClient;
let platform = DeveloperPlatformClient::for_platform(std::env::var("MARONA_PLATFORM_TOKEN")?)?;
// Obtain /hub-registration from the running server at its public HTTPS URL.
let registration = reqwest::get("https://tools.example.com/hub-registration").await?.json().await?;
let created = platform.create_agent_app(registration).await?;

Tools return ordinary JSON values; the SDK formats MCP responses and platform metadata automatically. Objects are preserved in structuredContent.data; other JSON values are preserved in structuredContent.data.value. Existing AgentApp and result helpers remain compatibility APIs.

Python exposes app.mcp for native tools, resources and prompts. TypeScript, Java and Dart expose app.configure(...); Rust exposes marona::mcp::sdk for advanced native server capabilities. C++ provides resource(...) and prompt(...). These are MCP server capabilities. A Marona App is its platform registration; displaying an MCP Apps UI resource additionally requires a host supporting that optional UI extension.

Brain2Agent (B2A)

Native B2A 1.0 uses one multimodal message contract in both directions. 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.protocols and connect with Runner.connect, following the persistent realtime session lifecycle. These examples read one captured signal file using your configured provider.

One configured protocol is selected automatically. Several compatible protocols open a coordinated session automatically. Explicit selection remains available (protocol="b2a" in Python and the corresponding option in other SDKs). Canonical message protocol fields or unambiguous registered input predicates select the input; ambiguous raw input is rejected. Implement AgentProtocol and the coordinated session lifecycle to add protocols without adding Agent properties. Existing A2A peers and servers retain their agent-to-agent role; they are not automatically converted into input protocols. Agent.b2a and B2ARunner remain compatibility APIs.

Save as examples/b2a_message.rs:

use marona::{
    Agent, B2ACodec, B2ACodecOptions, B2ACodecTransport, ConnectOptions, Marona, Runner, B2A,
};
use serde_json::Value;
use std::sync::Arc;
#[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 Message Agent")
        .model(std::env::var("MARONA_MODEL").unwrap_or_else(|_| "marona/auto".into()))
        .instructions("Interpret decoded messages in context. Preserve uncertainty and use connected tools under Marona permissions.")
        .hub_tools(client.hub.connect(ConnectOptions::default()).await?)
        .protocols(vec![Arc::new(B2A::new(neural_service, std::env::var("B2A_OUTPUT_PROFILE")?))]);
    let mut session = Runner::connect(
        &agent,
        &std::env::var("B2A_USER_ID")?,
        &std::env::var("B2A_SESSION_ID")?,
    )
    .await?;
    let result = async {
        session.send(&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(())
}

Single run with structured output

Save as examples/b2a_structured.rs. This opens a connection, decodes the signal, runs the agent, validates the response, encodes feedback, and closes the connection.

use marona::{
    Agent, B2ACodec, B2ACodecOptions, B2ACodecTransport, ConnectOptions, Marona, Runner, B2A,
};
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NeuralResponse {
    text: String,
}
use std::sync::Arc;
#[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 Message Agent")
        .model(std::env::var("MARONA_MODEL").unwrap_or_else(|_| "marona/auto".into()))
        .instructions("Interpret decoded messages in context. Preserve uncertainty and use connected tools under Marona permissions.")
        .hub_tools(client.hub.connect(ConnectOptions::default()).await?)
        .output_schema(json!({"type":"object","properties":{"text":{"type":"string"}},"required":["text"],"additionalProperties":false}))
        .output_schema_strict(true)
        .protocols(vec![Arc::new(B2A::new(neural_service, std::env::var("B2A_OUTPUT_PROFILE")?))]);
    let result = Runner::run(
        &agent,
        signal,
        Some(&std::env::var("B2A_USER_ID")?),
        Some(&std::env::var("B2A_SESSION_ID")?),
    )
    .await?;
    let output: NeuralResponse = serde_json::from_value(result.output)?;
    println!("{}", output.text);
    Ok(())
}

Python returns the declared Pydantic model in result.output. Other SDKs validate the declared JSON schema and expose their language's structured output representation. Invalid output is rejected before encoding. Decoder abstention, required approval, or failure does not become a successful typed result; use a persistent connection for interactive clarification, approvals, and feedback delivery acknowledgments.

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 connections automatically negotiate HTTP SSE with current runtimes. Sending a signal returns when accepted. message events carry the standard envelope during generation and at completion; agent.delta remains a text-preview compatibility event. Validated, encoded output arrives as feedback. Keep consuming the session stream for subsequent turns. The SDK handles transport and sequencing; no background task or polling loop is required in application code. Heartbeats keep an active stream alive without imposing a generation-wide timeout. Runner.run collects the completed result and retains its configured run limit. New connections require a B2A 1.0 runtime; the connection's streaming flag reports whether HTTP SSE is available.

One message format in both directions

{
  "protocol": "b2a",
  "version": "1.0",
  "type": "message",
  "source": "neural_decoder",
  "message_id": "message-123",
  "timestamp": "2026-11-12T08:00:00Z",
  "payload": {"content": [
    {"type": "text", "data": "Explain this observation"},
    {"type": "audio", "mime_type": "audio/wav", "uri": "b2a://session-123/audio-001"}
  ]}
}

Brain → Agent and Agent → Brain use this same schema; source identifies the sender (brain, neural_decoder, agent, or a provider-defined source). The SDK binds the session ID, sequence and context revision. Source labels do not grant authority. payload.content supports text, audio, image, video, control, features and namespaced extensions. Binary inline data uses encoding: "base64" and a matching mime_type; numerical values stay structured. Multiple representations of one utterance can share representation_id and timing in milliseconds.

Providers return status, message, provenance and uncertainty from decode. Encode receives that same message envelope with the agent source, under the existing request.response argument. Models and neural hardware determine actual modality support. The protocol does not promise that a text-only model can process audio/video.

Private b2a:// references are resolved automatically through the configured provider's read_resource MCP tool or POST /v1/resources/read HTTP endpoint, with the provider's credential. The request is {"uri":"b2a://session-123/audio-001","consent":true}; the result is one content block of the same type/MIME, containing inline data or a scoped HTTPS URL. No arbitrary URL receives the provider bearer token. Large media should use scoped HTTPS references; providers enforce resource ownership and expiry.

Streaming metadata is stream: {"id":"utterance-1","index":0,"final":false}. Indices start at zero. Snapshots replace previous content; mode: "delta" appends one text block. Only final decoder messages run the agent. Sequence/source conflicts, finalized stream reuse and oversized accumulated input are rejected without execution. See the repository's docs/b2a-protocol.md for the complete wire contract.

Neural provider connection options

B2ACodec supports optional overrides for provider tool names and HTTP paths. Omit them when your provider uses the SDK defaults.

Configuration Applies to SDK defaults
decode_tool, encode_tool MCP tool names decode, encode
decode_path, encode_path HTTP endpoint paths /v1/decode, /v1/encode

For MCP, configure the provider's complete MCP endpoint URL and select the MCP transport. Tool names identify the provider's tools; HTTP path overrides do not affect MCP calls. These illustrative names must match your provider.

let neural_service = B2ACodec::with_options(
    &codec_url,
    &codec_token,
    B2ACodecOptions {
        transport: B2ACodecTransport::Mcp,
        decode_tool: "neural_decode".into(),
        encode_tool: "neural_encode".into(),
        ..Default::default()
    },
)?;

For HTTP, configure the provider base URL. Paths start with / and are appended to that URL after removing its trailing slash. For example, https://neural.example/api plus /neural/decode calls https://neural.example/api/neural/decode. MCP tool names do not affect HTTP calls.

let neural_service = B2ACodec::with_options(
    &service_url,
    &codec_token,
    B2ACodecOptions {
        transport: B2ACodecTransport::Http,
        decode_path: "/neural/decode".into(),
        encode_path: "/neural/encode".into(),
        ..Default::default()
    },
)?;

The SDK defaults to HTTP when transport is omitted; the B2A quickstarts above explicitly select MCP. Pass the resulting service as the B2A provider in the same Agent.protocols configuration. These options change routing only: request and response schemas still follow the B2A provider contract. Implement B2AProvider when a vendor needs payload translation. These are neural-service routes, separate from Marona's /runtime/b2a/... endpoints.

Device2Agent (D2A)

D2A 1.0 is an independent bidirectional device protocol. Configure it on an Agent without B2A, or combine it with any compatible protocol. Device types and capability names come from discovery. IoT sensors, robots, industrial systems and vendor SDKs connect through a D2AProvider adapter implementing discovery, continuous events, action execution, action lookup and cancellation. The protocol does not supply hardware drivers automatically.

D2ADevice connects a compatible HTTP/SSE gateway. Its MCP mode maps discovery and actions to tools and requires a real continuous event adapter or event endpoint. Request polling is not presented as realtime. Provider credentials stay in the SDK process and are never sent in the Agent configuration.

Save as examples/d2a.rs. With a canonical message JSON file, run one exchange. Without a file, the SDK subscribes to device events and keeps the session open. Set MARONA_API_KEY, D2A_DEVICE_URL, D2A_DEVICE_TOKEN, D2A_USER_ID and D2A_SESSION_ID.

use marona::{Agent, ConnectOptions, D2ADevice, D2AMessage, D2APolicy, Marona, Runner, D2A};
use std::sync::Arc;

/// Pass a canonical message JSON file for one run; omit it for the device event stream.
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Marona::builder().build()?;
    let provider = D2ADevice::new(
        std::env::var("D2A_DEVICE_URL")?,
        std::env::var("D2A_DEVICE_TOKEN")?,
    )?;
    let config = D2A::new(provider).with_policy(D2APolicy {
        allow_actions: std::env::var("D2A_ALLOW_ACTIONS").as_deref() == Ok("true"),
        ..D2APolicy::default()
    });
    let agent = Agent::new(&client, "Device Agent")
        .model(std::env::var("MARONA_MODEL").unwrap_or_else(|_| "marona/auto".into()))
        .instructions("Interpret device observations, use advertised capabilities and report confirmed device outcomes. Respect approval requirements.")
        .hub_tools(client.hub.connect(ConnectOptions::default()).await?)
        .protocols(vec![Arc::new(config)]);
    let user = std::env::var("D2A_USER_ID")?;
    let application_session = std::env::var("D2A_SESSION_ID")?;
    if let Some(path) = std::env::args().nth(1) {
        let message =
            D2AMessage::from_value(serde_json::from_str(&std::fs::read_to_string(path)?)?)?;
        let result = Runner::run(
            &agent,
            message.to_value(),
            Some(&user),
            Some(&application_session),
        )
        .await?;
        println!("{}", result.output);
    } else {
        let mut session = Runner::connect(&agent, &user, &application_session).await?;
        let result = async {
            while let Some(event) = session.next_event().await? {
                println!("{}", serde_json::to_string(&event)?);
            }
            Ok::<(), Box<dyn std::error::Error>>(())
        }
        .await;
        session.close().await?;
        result?;
    }
    Ok(())
}

Message and action lifecycle

Both directions use protocol, version, type, source, message_id, timestamp and payload. payload.kind is data for device content and agent replies; action, feedback and coordination identify protocol control messages; payload.content contains typed text, media, control, features or namespaced blocks. Only action messages can execute device capabilities. Data messages require content; action, feedback and coordination metadata can use an empty content array. The SDK assigns IDs and timestamps, then binds the native session and sequence. Device resource references use HTTPS; adapters materialize private resources. Legacy observation and state inputs remain readable; new messages use data. A data payload may include a device state snapshot and revision. No simulation property is defined or inserted. Use the direct message constructor with source and payload, as with B2A; an observation helper is not required.

let message = D2AMessage::from_payload("laptop-camera", json!({
    "kind": "data", "content": [{"type": "image", "mime_type": "image/jpeg",
        "encoding": "base64", "data": frame_base64}]
}))?;
session.send_message(&message).await?;

Actions are disabled by default. These examples deliberately enable execution of advertised capabilities. Restrict allowed devices and capabilities for your application. The runtime reserves an action before provider execution. Both boundaries validate capability schemas, expiry, revision and policy. requires_approval still requires an explicit session approval call; a model or provider cannot grant approval to itself.

Accepted and executing acknowledgments are not completion. A successful action needs succeeded feedback with a schema validated result. Single runs surface pending, approval required, rejected, failed, cancelled, expired or unknown outcomes instead of reporting successful execution. Persistent sessions expose these events and support approval, action lookup and cancellation. An uncertain action ID is retained and never automatically executed again. Cancellation cannot undo a completed action.

Provider event streams accept only advertised device data or correlated feedback. Providers cannot inject agent actions, cross protocol routes or approval flags. Queues are bounded, sequence assignment is serialized, and closing a session cancels its readers and native connection. Streaming delivers messages as generation progresses; applications do not implement polling or a background routing loop.

Automatic protocol coordination

Attach B2A and D2A directly to one Agent. The neural service and device provider are configured using the connections shown above; model, instructions and identity values come from your application. This example enables advertised device actions; capabilities requiring approval still require it. Either protocol also works alone, and other compatible AgentProtocol implementations can join the same list.

use marona::{Agent, B2A, D2A, D2APolicy, ConnectOptions, Runner};
use std::sync::Arc;

let agent = Agent::new(&client, "Connected Agent")
    .model(model)
    .instructions(instructions)
    .hub_tools(client.hub.connect(ConnectOptions::default()).await?)
    .protocols(vec![
        Arc::new(B2A::new(neural_service, profile)),
        Arc::new(D2A::new(device).with_policy(D2APolicy {
            allow_actions: true,
            ..D2APolicy::default()
        })),
    ]);
let mut session = Runner::connect(&agent, &user_id, &session_id).await?;
let result = async {
    session.send(&canonical_message).await?;
    while let Some(event) = session.next_event().await? {
        println!("{:?}", event);
    }
    Ok::<(), marona::Error>(())
}.await;
session.close().await?;
result?;

The protocol list is not an execution order. With multiple protocols, Runner.connect opens a coordinated session and listens to their events concurrently. Incoming canonical messages select their protocol; ambiguous input requires explicit selection. The Agent uses advertised capabilities to decide which actions or routes the task needs. The SDK dispatches validated routes and returns correlated feedback to the origin. For example, a decoded B2A request can invoke a permitted D2A device capability and receive its confirmed result through B2A. Each protocol name must be unique; one D2A provider can expose multiple devices.

All attached protocols share the authenticated user and application conversation, with separate native session IDs. Discovery runs before any native connection opens. The runtime receives advertised capabilities and emits final protocol.route decisions. The SDK delivers each canonical message to its target, then calls the origin session's deliverFeedback / deliver_feedback hook with correlated terminal feedback. Partial model output never actuates devices. Pending acknowledgments stay pending.

Compatible sessions implement send, canonical deliver, deliver feedback, event iteration and close. Input recognition is optional; unclassified ambiguous input fails instead of being broadcast. Routes enforce target attachment, correlation, bounded deduplication and an eight hop limit with visited protocol lineage. Exceeding retention fails closed; old route IDs are never evicted to permit duplicate actions. Partial setup failures close already opened sessions. Explicit protocol selection preserves the single protocol API.

Canonical D2A message schema.

Standard realtime audio

Use RealtimeMedia to negotiate WebM/Opus, Ogg/Opus or MP3 with the runtime. The runtime encodes before transmission; applications do not install an encoder or schedule PCM chunks. This optional media layer leaves Agent tools, B2A messages, schemas, and existing PCM sessions unchanged.

use marona::{RealtimeMedia, RealtimeRunner};

let media = RealtimeMedia::default();
let session = RealtimeRunner::connect_with_media(
    &agent, Some("user-123"), Some("voice-123"), Some(&media),
).await?;
session.send_message("Explain this observation briefly.").await?;
while let Some(event) = session.next_event().await {
    let event = event?;
    if event.event_type == "output_audio.stream" {
        if let Some(audio) = event.audio()? { println!("{}", audio.uri); }
    }
    if event.event_type == "response.completed" { break; }
}
session.close().await?;
// Headless consumers can use audio.chunks() or audio.write_to(&mut sink).await?.

output_audio.stream exposes a scoped, expiring audio URL and typed format metadata. output_audio.done reports encoding completion, not playback completion. Wait for your media output to finish before starting the next conversational turn. Closing a session or cancelling a response stops active generation; stop your output adapter to discard audio already delivered. The SDK never replays a response automatically. RealtimeAudio.content() returns an existing B2A audio block for HTTPS media URLs.

The optional browser adapter is AudioPlayer from marona/media. Python ships the same module through RealtimeMedia.browser_module() for serving from your application. Use player.media for negotiation and await player.play(audio) for playback completion; player.stop() cancels playback. A backend keeps its API key private and forwards only typed media descriptors to the output. Native and headless consumers use the same HTTP media resources without depending on a browser. These examples print a resource reference; printing a URL alone does not play it.

Media contract and lifecycle.

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.

5.5.0

The main Marona package now builds MCP servers and Marona Apps. AgentApp registers tools and platform metadata, hosts HTTP or stdio, and exposes advanced MCP capabilities. DeveloperPlatformClient registers Apps and manages hosted deployments. Applications no longer need marona-sdk or a direct MCP transport dependency. Existing Agent, B2A and D2A APIs remain supported.

5.3.0

D2A device content and agent responses use payload.kind: "data" with the shared multimodal content array. Direct source/payload constructors are available across SDKs. Legacy observation and state inputs remain accepted; action, approval, feedback and B2A behavior are preserved.

5.2.0

D2A adds independent device communication, persistent provider events, schema checked actions, approval and outcome reconciliation. Multiple compatible Agent protocols now coordinate automatically through generic canonical delivery and feedback hooks. Existing B2A and core Agent APIs remain supported.

B2A 1.0 uses the same multimodal message envelope in both directions. The source identifies the sender. SDK-managed streaming, resource resolution and encoder return messages are built in. Existing v0.1 runtime sessions remain supported; new SDK connections require a runtime advertising B2A 1.0.