Interop
Reach agents over A2A, MCP, and AG-UI without changing their messages
This page is the reference for the protocol bridges. For the agents behind them, start with Agents.
Bridges connect external A2A, MCP, and AG-UI clients to agents that speak AGDX. A bridge maps the shared fields into an AGDX command and keeps the protocol's own data in the body. The agents behind a bridge do not change. Bridges work on plain Apache Iggy and need no model provider.
Put a worker behind a bridge
A bridge publishes an AGDX command on its request topic and waits for a correlated AGDX response on its reply topic. The worker is an ordinary agent that listens on the request topic and answers with respond. respond needs the agent's respond_on topic, which must be the bridge's reply topic. It answers an AGDX command with a typed response that carries the correlation and is addressed to the bridge.
import { Agent, AgentId, AgentTopic, agentMessageBody } from "@laserdata/laser-sdk"
const text = new TextEncoder()
const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes)
await using assistant = Agent.builder()
.id(AgentId.new("assistant"))
.listenOn(AgentTopic.Sessions)
.respondOn(AgentTopic.Sessions)
.handler({
handle: (message, ctx) =>
ctx.respond(text.encode(`handled: ${decode(agentMessageBody(message))}`))
})
.build()
.spawn(laser)
await assistant.ready()use laser_sdk::prelude::full::*;
struct Assistant;
impl AgentHandler for Assistant {
async fn handle(&self, message: &AgentMessage, ctx: &AgentCtx<'_>) -> Result<(), LaserError> {
let text = String::from_utf8_lossy(message.body()).into_owned();
ctx.respond(format!("handled: {text}")).await
}
}
let mut assistant = Agent::builder()
.id("assistant".parse()?)
.listen_on(AgentTopic::Sessions)
.respond_on(AgentTopic::Sessions)
.handler(Assistant)
.build()
.spawn(laser.clone());
assistant.ready().await?;async def assistant(ctx, message):
await ctx.respond(b"handled: " + bytes(message.body()))
worker = laser.spawn_agent(
"assistant",
ls.AgentTopic.Sessions,
assistant,
respond_on=ls.AgentTopic.Sessions,
)
await worker.ready()Bridge constructors take the request topic and the reply topic explicitly. The samples on this page use agent.sessions for both. Every topic lives on the stream of the Laser you pass, so pass laser.with_default_stream(stream) to run a bridge on another stream.
A2A
A2aBridge serves an internal agent through A2A v1.0 JSON-RPC. card() returns its A2A v1.0 Agent Card. The card names the absolute URL clients reach the bridge at, so set it with with_public_url (TypeScript: withPublicUrl, Python: public_url=) before you build the card. with_description and with_version fill in the card's description and agent version. The card does not advertise streaming.
Tasks use the A2A v1.0 shapes. A task has an id, a contextId, and a status.state such as TASK_STATE_COMPLETED. An answer with a body adds one artifact, { artifactId, parts: [{ text }] }. The contextId is the client's message.contextId, or the task's own ID when the client sent none.
| A2A method | Mapping |
|---|---|
SendMessage | Without message.taskId, publishes an AGDX command on a new task conversation and returns { "task": ... } in TASK_STATE_SUBMITTED. The task ID is the conversation ID. The A2A params ride in the body as JSON. With message.taskId, it continues that task: the message goes into the task's conversation, addressed to the agent the task went to, and the task returns in TASK_STATE_WORKING. |
SendStreamingMessage | Not served, since the card does not advertise streaming. Readers consume a chunk stream from the log. |
GetTask | Reads the log from the time the task was created and maps the response or error with the task's correlation to the A2A task. The first finished answer settles the task, else the latest answer in progress, so an input-required answer gives way to the next one. Returns TASK_STATE_WORKING until an answer arrives, and TASK_STATE_UNSPECIFIED when the lookup could not reach the end of the topic. |
CancelTask | Publishes an AGDX error terminal with code Cancelled for a task still in progress and returns TASK_STATE_CANCELED. |
The bridge does not serve ListTasks, because it keeps no state outside the log.
import { A2aBridge, AgentId, AgentTopic } from "@laserdata/laser-sdk"
const bridge = new A2aBridge(
laser,
AgentId.new("a2a-gateway"),
AgentTopic.Sessions,
AgentTopic.Sessions
).withPublicUrl("https://agents.example.com/a2a")
const card = bridge.card()use laser_sdk::prelude::full::*;
use std::sync::Arc;
let bridge = Arc::new(
A2aBridge::new(
laser.clone(),
"a2a-gateway".parse::<AgentId>()?,
AgentTopic::Sessions,
AgentTopic::Sessions,
)
.with_public_url("https://agents.example.com/a2a")?,
);
let card = bridge.card()?;
let app = bridge.clone().router();import laser_sdk as ls
bridge = ls.A2aBridge(
laser,
"a2a-gateway",
ls.AgentTopic.Sessions,
ls.AgentTopic.Sessions,
public_url="https://agents.example.com/a2a",
)
card = bridge.card()The A2A bridge exposes submit, task, cancel, card, and signed_card (TypeScript: signedCard). handle_rpc(request) (TypeScript: handleRpc) serves a whole JSON-RPC request without HTTP. Rust's a2a-http feature adds router(), an Axum router with the JSON-RPC endpoint at / and the Agent Card at /.well-known/agent-card.json, which delegates to handle_rpc. router() consumes an Arc, so call it on a clone. TypeScript and Python have no router, so route HTTP requests to handle_rpc yourself.
const response = await bridge.handleRpc({
jsonrpc: "2.0",
id: 1,
method: "GetTask",
params: { id: taskId }
})let response = bridge
.handle_rpc(serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": "GetTask",
"params": { "id": task_id },
}))
.await;response = await bridge.handle_rpc(
{
"jsonrpc": "2.0",
"id": 1,
"method": "GetTask",
"params": {"id": task_id},
}
)What to expect from the A2A bridge:
submittakes theSendMessageparams as raw JSON bytes in Rust. TypeScript and Python also accept a JSON string, which rides byte for byte, or a value they encode as JSON. Throughhandle_rpcand the router the params are parsed and encoded again, so key order and spacing can change.GetTaskandCancelTasklook for the bridge's own command for the task. A task ID the bridge never published answers-32001task not found, and the programmatictaskandcancelraise a handler configuration error.CancelTaskon a task that already finished answers-32002task not cancelable, and the programmaticcancelraises a rejected error. Without task binding, anyone who knows a task ID can read or cancel the task.GetTaskreads from the time in the task ID, less five minutes for clock differences, up to 32 passes of up to 10,000 records per partition each. When the lookup stops before the end of the topic, the task readsTASK_STATE_UNSPECIFIED, so ask again later.- The task lookup needs a default stream on the
Laser. - A Python task is a dictionary, such as
task["id"]. TypeScript reports the task state as an object, such as{ kind: "known", name: "Completed" }. The JSON-RPC output is the same in all three.
Bind tasks to callers
Task binding ties each task ID to the caller that submitted it. Turn it on with a secret 32-byte key and a lifetime. Each task ID then carries an expiry and a keyed digest over the caller, the stream, the conversation, and the expiry. Another caller, an expired ID, a changed ID, and an ID from a deleted and recreated stream are all refused like a malformed ID, and nothing is published.
With binding on, every task call needs the authenticated caller. Calls without one are refused. The Rust router reads the caller from an A2aCallerPrincipal request extension that your authentication layer inserts. Use the same key on every bridge that serves the same stream. A new key ends every open task ID. All three SDKs make the same digest, so their task IDs work across languages.
const bridge = new A2aBridge(laser, AgentId.new("a2a-gateway"), AgentTopic.Sessions, AgentTopic.Sessions)
.withTaskBinding(taskKey, 3_600_000)
const task = await bridge.caller("user-42").submit(params)
const current = await bridge.caller("user-42").task(task.id)let bridge = A2aBridge::new(laser.clone(), "a2a-gateway".parse::<AgentId>()?, AgentTopic::Sessions, AgentTopic::Sessions)
.with_task_binding(task_key, std::time::Duration::from_secs(3600));
let task = bridge.caller("user-42").submit(params).await?;
let current = bridge.caller("user-42").task(&task.id).await?;bridge = ls.A2aBridge(
laser, "a2a-gateway", ls.AgentTopic.Sessions, ls.AgentTopic.Sessions,
task_binding_key=task_key, task_binding_ttl_ms=3_600_000,
)
task = await bridge.submit(params, caller="user-42")
current = await bridge.task(task["id"], caller="user-42")Sign and verify the Agent Card
with_capabilities puts the agent's capability descriptors on the card as A2A skills. signed_card(key) adds a detached JWS signature to the card, so clients can check it before they trust it. with_signing_key signs every record the bridge publishes, the task commands and the CancelTask terminal, so an agent that verifies its input accepts them. TypeScript uses withCapabilities, withSigningKey, and signedCard. Python passes capabilities= and signing_key= to A2aBridge(laser, ..) and calls bridge.signed_card(key).
The Rust router serves the card signed with the bridge's signing key when it has one, and the unsigned card otherwise. Until the public URL is set, the card path answers 404.
A client checks a signed card with verify_card. It rebuilds the signed payload from the card itself, so a changed field fails verification. The payload is the RFC 8785 canonical JSON of the card without signatures, with members sorted by the UTF-16 code units of their names and numbers limited to integers up to 2^53 - 1, so every language produces the same bytes. The protected header names EdDSA and the signing key's id (kid). verify_card refuses a header that names another algorithm, carries crit, or names a different key.
import { SigningKey, verifyCard } from "@laserdata/laser-sdk"
const key = SigningKey.fromBytes(secret)
const signed = bridge.signedCard(key)
const [signature] = signed.signatures ?? []
if (signature !== undefined) {
verifyCard(signed, signature, key.verifyingKey())
}use laser_sdk::sign::{SigningKey, verify_card};
let key = SigningKey::from_bytes(&secret);
let signed = bridge.signed_card(&key)?;
let value = serde_json::to_value(&signed)
.map_err(|error| LaserError::Codec(error.to_string()))?;
verify_card(&value, &signed.signatures[0], &key.verifying_key())?;key = ls.SigningKey(secret)
signed = bridge.signed_card(key)
ls.verify_card(signed, signed["signatures"][0], key.verifying_key)secret is a 32-byte Ed25519 seed. Rust needs the sign and a2a-bridge features for the card helpers.
MCP
McpBridge maps MCP JSON-RPC tool calls to AGDX commands. It waits for a response or error with the matching correlation and returns it as a tool result.
| MCP method | Mapping |
|---|---|
initialize | Answers the client's protocol version when the bridge serves it (2025-11-25, 2025-06-18, or 2025-03-26), and 2025-11-25 otherwise. Always advertises tools, and advertises resources and prompts only when configured. |
ping | Answers an empty result. |
tools/list / tools/call | Serves the tools added with with_tool. A call publishes an AGDX command with the tool name and returns the correlated reply as a tool result. A tool the bridge does not list answers -32602 and publishes nothing. |
resources/list / resources/read | Serves the text resources added with with_resource. An unknown URI answers -32002. |
prompts/list / prompts/get | Serves the prompts added with with_prompt. Arguments are listed but not substituted. A prompt without a description renders no description, and an unknown prompt answers -32602. |
A notification, any message without an id such as notifications/initialized, gets no response: handle_rpc returns nothing (TypeScript: undefined, Python: None), and the Rust router answers 202 Accepted with no body. Any other method answers -32601. JSON-RPC batch arrays are rejected.
The Rust router also follows the Streamable HTTP rules. It applies the browser origin guard described under Browser origins, which stops a web page from reaching a local bridge through DNS rebinding. A request whose MCP-Protocol-Version header names a version the bridge does not serve is refused with 400.
A tool call waits 30 seconds for its reply by default. Change it with with_timeout (TypeScript: withTimeout(ms), Python: timeout_ms=). with_memory_tools adds remember and recall tools with fixed input schemas (TypeScript: withMemoryTools, Python: memory_tools=True).
import { AgentId, AgentTopic, McpBridge } from "@laserdata/laser-sdk"
const mcp = new McpBridge(
laser,
AgentId.new("mcp-gateway"),
AgentTopic.Sessions,
AgentTopic.Sessions,
"ops-tools"
).withTool("ask", "ask the assistant", { type: "object" })
const tools = mcp.listTools()let mcp = Arc::new(
McpBridge::new(
laser.clone(),
"mcp-gateway".parse::<AgentId>()?,
AgentTopic::Sessions,
AgentTopic::Sessions,
"ops-tools",
)
.with_tool(
"ask",
Some("ask the assistant".into()),
serde_json::json!({ "type": "object" }),
)?,
);
let tools = mcp.list_tools();
let app = mcp.clone().router();mcp = ls.McpBridge(
laser,
"mcp-gateway",
ls.AgentTopic.Sessions,
ls.AgentTopic.Sessions,
"ops-tools",
tools=[
{
"name": "ask",
"description": "ask the assistant",
"input_schema": {"type": "object"},
}
],
)
tools = mcp.list_tools()Rust and TypeScript add tools, resources, and prompts with with_tool, with_resource, and with_prompt (TypeScript: withTool, withResource, withPrompt). Python passes tools=, resources=, and prompts= lists of dictionaries. A resource dictionary has uri, name, mime_type, and text. A prompt dictionary has a prompt entry and a messages list of role and text pairs. Every language requires the input schema to be a JSON object. A missing schema, or one that is not an object, is an InvalidError, and Rust with_tool returns a Result for that reason.
Every language also exposes initialize, list_tools, call_tool, list_resources, read_resource, list_prompts, and get_prompt (camelCase in TypeScript). call_tool(name, params) takes the arguments as raw JSON bytes in Rust. Python and TypeScript also take raw JSON text, sent as is, or a value they encode as JSON, such as { question: "status?" }. Through handle_rpc the body is the whole MCP params object, with name and arguments.
A tool that answers with an AGDX error returns a successful JSON-RPC result with isError: true. Each content item names its type in a kind field in Rust and TypeScript, and the JSON-RPC output and Python use type.
Rust's mcp-http feature adds an Axum router(). The mcp-bridge feature alone has no HTTP dependency. handle_rpc(request) (TypeScript: handleRpc) dispatches one JSON-RPC request without HTTP.
Browser origins
The Rust A2A and MCP routers guard their JSON-RPC endpoint the same way:
- A request without an
Originheader comes from a non-browser client and is accepted. - A browser request is accepted when its
Originis listed inwith_allowed_origins(origins), as exact values such ashttps://app.example.com. - A same-origin page is accepted when the
Hostis an IP literal orlocalhost, such as a page the bridge serves itself onhttp://127.0.0.1:8080. - Every other browser request is refused with
403.
A same-origin page on a named host needs the allowlist. In a DNS rebinding attack the browser sends the attacker's own name as both Origin and Host, so accepting every same-origin request would let a rebound page through. The A2A card path stays open to any origin, because the card is public discovery. TypeScript and Python have no HTTP router, so when you serve handle_rpc from your own framework, apply your own origin policy there.
Address one agent
A bridge call goes to every agent unless you name one. On the shared agent.sessions topic every listening agent receives an unaddressed task or tool call, so each of them would handle it. Name the agent, and only that agent takes the command as work.
const worker = AgentId.new("assistant")
const task = await bridge.submit(
'{"message":{"messageId":"m-1","role":"ROLE_USER","parts":[{"text":"summarize"}]}}',
{ target: worker }
)
const result = await mcp.callTool("ask", { question: "status?" }, { target: worker })let task = bridge
.submit_to(
"assistant".parse::<AgentId>()?,
br#"{"message":{"messageId":"m-1","role":"ROLE_USER","parts":[{"text":"summarize"}]}}"#.to_vec(),
)
.await?;
let result = mcp
.call_tool_to("assistant".parse::<AgentId>()?, "ask", br#"{"question":"status?"}"#.to_vec())
.await?;task = await bridge.submit(
b'{"message":{"messageId":"m-1","role":"ROLE_USER","parts":[{"text":"summarize"}]}}',
target="assistant",
)
result = await mcp.call_tool("ask", b'{"question":"status?"}', target="assistant")The Rust submit_to and call_tool_to take any agent ID that converts into the wire ID, so the prelude AgentId works directly. Give an inline parse its type, as in "assistant".parse::<AgentId>()?.
with_target(agent) (TypeScript: withTarget, Python: target= on the constructor) names the agent the bridge fronts. Every call that names no agent goes to it, including the requests that arrive through the JSON-RPC routes. Without it those requests are unaddressed, so put one worker on the request topic behind them.
Both bridges sign the commands they publish when they have a signing key (with_signing_key, TypeScript: withSigningKey, Python: signing_key=). An agent with a verifier refuses unsigned commands, so a bridge in front of such an agent needs the key. When the bridge's Laser verifies replies, the answer to an addressed call must be signed by the agent it went to, so another agent's key cannot answer for it. An unaddressed call is a broadcast that any listening agent may take, so an answer signed by any enrolled key is a valid answer. Address the call when the answer must come from one agent.
Run a bridge call as a child session
A bridge call can run as a child session of a session you hold. The child gets a submitted start on agent.sessions with its parent and root before the command, and the command carries the same ancestry, so a session view rolls the call up under its parent. submit_in leaves the end to the agent that handles the task. If the command send fails after the start, the child stays open. call_tool_in ends the child by the result: completed on a tool result, failed on a tool error, a timeout, or a transport error.
const parent = session.conversation
const root = session.root ?? parent
const task = await bridge.submitIn(
parent,
root,
'{"message":{"messageId":"m-1","role":"ROLE_USER","parts":[{"text":"summarize"}]}}',
{ target: worker }
)
const result = await mcp.callToolIn(parent, root, "ask", { question: "status?" }, { target: worker })let parent = session.conversation();
let root = session.root().unwrap_or(parent);
let task = bridge
.submit_in_to(
"assistant".parse::<AgentId>()?,
parent.into(),
root.into(),
br#"{"message":{"messageId":"m-1","role":"ROLE_USER","parts":[{"text":"summarize"}]}}"#.to_vec(),
)
.await?;
let result = mcp
.call_tool_in_to(
"assistant".parse::<AgentId>()?,
parent.into(),
root.into(),
"ask",
br#"{"question":"status?"}"#.to_vec(),
)
.await?;parent = session.conversation
root = session.root or parent
task = await bridge.submit_in(
parent,
b'{"message":{"messageId":"m-1","role":"ROLE_USER","parts":[{"text":"summarize"}]}}',
root=root,
target="assistant",
)
result = await mcp.call_tool_in(
parent, "ask", b'{"question":"status?"}', root=root, target="assistant"
)Rust also has submit_in and call_tool_in without a target. Python and TypeScript make the target optional. Child lifecycle records carry neither the loop guard nor a signature.
AG-UI
AG-UI gives frontends state and events. publish_state_snapshot and publish_state_delta write the session state document of a conversation, the same records that session.state() writes, so every reader folds one state model. A snapshot must be a JSON object, and a delta must be an RFC 6902 JSON Patch array. reconstruct_state returns that document. It folds agent.sessions first, and reads the managed state view only when the lane no longer holds the document's baseline and the view is not behind the lane. It returns nothing until a state record exists.
agui_events reads every retained record of a conversation on the topic, never a recent window, and converts it into AG-UI events:
- Chat chunks become
TEXT_MESSAGE_*events, and reasoning chunks becomeREASONING_MESSAGE_*events. - Tool argument chunks become
TOOL_CALL_START,TOOL_CALL_ARGS, andTOOL_CALL_END. A response or error that names a tool becomesTOOL_CALL_RESULT, with the answering record's id asmessageId. - A task status of
SubmittedbecomesRUN_STARTED. Completed or canceled status becomesRUN_FINISHED. Failed or rejected status becomesRUN_ERROR, with the status detail ortask failed. Another error also becomesRUN_ERROR. Only status records with operationtaskrender. - State records become
STATE_SNAPSHOTandSTATE_DELTA. - Every event sits inside a run, so an AG-UI client verifier accepts the stream. An event outside a run opens one with the record's correlation as
runId. A message or tool call whose opening chunk is no longer retained opens before its first content. A run closes its open messages and tool calls beforeRUN_FINISHED, and the rendering ends with no run open.
AG-UI events with no AGDX source, such as MESSAGES_SNAPSHOT, ACTIVITY_*, RAW, and CUSTOM, are never produced.
const conversation = ConversationId.new()
await laser.publishStateSnapshot(AgentId.new("ui"), conversation, { count: 0 })
const events = await laser.aguiEvents(conversation, AgentTopic.Sessions)let conversation = ConversationId::new();
laser
.publish_state_snapshot("ui".parse::<AgentId>()?, conversation, &serde_json::json!({ "count": 0 }))
.await?;
let events = laser.agui_events(conversation, AgentTopic::Sessions).await?;conversation_id = ls.new_conversation_id()
await laser.publish_state_snapshot("ui", conversation_id, {"count": 0})
events = await laser.agui_events(conversation_id, ls.AgentTopic.Sessions)Pause for a human decision
request_input publishes an input-required task status and the prompt as an input_request command, then waits for the correlated response on the reply topic, up to the timeout. The approver answers with respond_input. If the approver rejects with an error, the wait fails with LaserError::Rejected in Rust and RejectedError in TypeScript and Python. Both calls use the existing command and response records and need no bridge.
Name the approver so that only it receives the prompt and only its answer counts. Without a target every approver on agent.sessions receives it, and any of them could answer. Rust uses request_input_from(target, ..), Python target=, and TypeScript a { target } option. With a target, a reply from any other agent is ignored, and with a verifier configured the reply must also be signed by the approver.
const decision = await laser
.agdx(AgentTopic.Sessions, AgentId.new("orchestrator"), conversation)
.requestInput(
AgentTopic.Sessions,
new TextEncoder().encode("restart the metrics service on node-7?"),
300_000,
{ target: AgentId.new("approver") }
)let decision = laser
.agdx(AgentTopic::Sessions, "orchestrator".parse::<AgentId>()?, conversation.into())
.request_input_from(
"approver".parse::<AgentId>()?,
AgentTopic::Sessions,
b"restart the metrics service on node-7?".to_vec(),
Duration::from_secs(300),
)
.await?;decision = await laser.agdx(
ls.AgentTopic.Sessions,
"orchestrator",
conversation_id,
).request_input(
ls.AgentTopic.Sessions,
b"restart the metrics service on node-7?",
timeout_ms=300_000,
target="approver",
)The timeout is required in every SDK and has no default. Python takes it as timeout_ms= in milliseconds. TypeScript also accepts a signal option, and an aborted signal throws CancelledError.
The approver is an agent that listens on agent.sessions and lists input_request among the operations it serves. An agent that serves every operation never receives an input request, so a worker never answers a prompt by accident. Its handler answers with respond_input, which needs the handled message to be an AGDX command with a correlation and the agent to have an ID. An agent with a signing key signs the response, so a caller that verifies signatures accepts only that agent's decision. request_input does not sign the prompt.
const approver = Agent.builder()
.id(AgentId.new("approver"))
.listenOn(AgentTopic.Sessions)
.operations(["input_request"])
.handler({
handle: (_message: AgentMessage, ctx: AgentCtx) =>
ctx.respondInput(AgentTopic.Sessions, new TextEncoder().encode("approved"))
})
.build()
.spawn(laser)struct Approver;
impl AgentHandler for Approver {
async fn handle(&self, _message: &AgentMessage, ctx: &AgentCtx<'_>) -> Result<(), LaserError> {
ctx.respond_input(AgentTopic::Sessions, b"approved".to_vec()).await
}
}
let approver = Agent::builder()
.id("approver".parse()?)
.listen_on(AgentTopic::Sessions)
.operations(vec![OPERATION_INPUT_REQUEST.to_owned()])
.handler(Approver)
.build()
.spawn(laser.clone());async def approve(ctx, message):
await ctx.respond_input(ls.AgentTopic.Sessions, b"approved")
approver = laser.spawn_agent(
"approver", ls.AgentTopic.Sessions, approve, operations=["input_request"]
)Inside a handler, ctx.approval_gate(approver, reply_topic, prompt, timeout) (TypeScript: approvalGate) does the same from the handled conversation, addressed to the named approver, and returns an approval grant with the approver and its decision. When an action governor asks for a step-up, re-send the action with the grant (Rust with_grant(&grant), TypeScript withGrant(grant), Python grant=) and it proceeds, recorded as a step-up that was approved. When the stream has agent.control and the decision arrives on the topic the agent reads, the gate does not hold the agent: its first pass publishes the prompt and ends the handler, the agent parks the session and keeps handling other sessions, and the decision runs the handler again, where the gate returns the grant. The code before the gate runs again, so keep it idempotent. Without agent.control the gate waits in place.
Authorize edge requests
The JSON-RPC bridges do not authenticate HTTP requests. Add authentication in your HTTP framework. Your HTTP layer decodes the token, and authorize_edge (TypeScript: authorizeEdge) checks the audience and scope of the decoded claims. The SDK does not parse tokens.
import { authorizeEdge, edgeDenialChallenge } from "@laserdata/laser-sdk"
const denial = authorizeEdge(
{ audience: ["agents.example"], scopes: ["tool:read"] },
"agents.example",
"tool:write"
)
if (denial !== undefined) {
const challenge = edgeDenialChallenge(denial)
}use laser_sdk::edge_auth::{EdgeClaims, authorize_edge};
let claims = EdgeClaims {
audience: vec!["agents.example".to_owned()],
scopes: vec!["tool:read".to_owned()],
};
if let Err(denial) = authorize_edge(&claims, "agents.example", "tool:write") {
let challenge = denial.challenge();
}denial = ls.authorize_edge(
["agents.example"],
["tool:read"],
"agents.example",
"tool:write",
)
if denial is not None:
challenge = denial.challengeA token for another audience is a hard reject with the challenge Bearer error="invalid_token", which maps to 401. A token for the right audience without the required scope returns the challenge Bearer error="insufficient_scope", scope="tool:write", which maps to 403 with a step-up. These are the RFC 6750 error codes MCP clients read to start re-authorization, and a " or \ in a scope is escaped. Rust returns the denial as the error, with expected or required_scope on its variant. TypeScript returns the denial or undefined, with kind wrongAudience or stepUp and the fields expected and requiredScope. Python returns an EdgeDenial with kind (wrong_audience or step_up), code, challenge, expected, and required_scope, or None. In Rust, authorize_edge needs the a2a-bridge or mcp-bridge feature. Governance covers delegated grants.
with_default_stream (TypeScript: withDefaultStream) points a bridge at another stream on the same connection. Use separate credentials when Iggy permissions must keep the streams apart.
Loop guard
Each bridge stamps its own ID in the bridge_hops metadata of the commands and cancels it publishes. Use with_bridge_hops(previous) (TypeScript: withBridgeHops) to continue a path for every call of the bridge. Rust's with_bridge_hops consumes the bridge and returns a result. TypeScript and Python change the bridge in place, and Python refuses while a call is in flight.
A single call can carry the path of the work it came from. A JSON-RPC request names it under laserdata.com/bridge_hops in params._meta for MCP or params.metadata for A2A. In code, pass it to submit_with_hops(previous, target, params) and call_tool_with_hops(previous, target, name, params) (TypeScript: submitWithHops, callToolWithHops, Python: previous_hops= on submit and call_tool). An agent that handles bridged work passes the bridge_hops of the record it handles. A path that already holds the bridge's ID is rejected before anything is published, with an invalid error in code and -32602 over JSON-RPC, so a cycle such as A2A to MCP to A2A stops at its second A2A entry.
Errors
A failed bridge call still returns a JSON-RPC response envelope with a code and a fixed public message.
| Code | Meaning |
|---|---|
-32600 | Invalid request: not a JSON-RPC object, or no method. |
-32601 | Method not found. |
-32602 | Invalid params, an unknown MCP tool or prompt, or a bridge loop. |
-32603 | Internal error, such as a tool call timeout. The message is one of unsupported operation, conflict, unauthenticated, forbidden, step-up authorization required, not found, or internal error. |
-32001 | A2A task not found. |
-32002 | A2A task not cancelable, or an unknown MCP resource. |
-32004 | A2A unsupported operation: streaming, or a message to a finished task. |
Over the Rust routers, a body that is not JSON is rejected with an HTTP 4xx before handle_rpc runs.
With a key registry verifier on the Laser (Rust sign feature), GetTask, MCP calls, and request_input skip replies that fail verification.
Standalone helpers
These helpers need no connection and behave the same in every language.
| Helper | Rust | TypeScript | Python |
|---|---|---|---|
| A2A request to AGDX command | a2a::command_from_message_send | commandFromMessageSend | command_from_message_send |
| AGDX envelope to A2A task | a2a::task_from_envelope | taskFromEnvelope | task_from_envelope |
| MCP tool call to AGDX command | mcp::tool_call_from_request | toolCallFromRequest | tool_call_from_request |
| AGDX envelope to MCP tool result | mcp::tool_result_from_envelope | toolResultFromEnvelope | tool_result_from_envelope |
| Bridge loop guard | a2a::enter_bridge | enterBridge | enter_bridge |
| Edge token check | edge_auth::authorize_edge | authorizeEdge | authorize_edge |
| Sign an Agent Card | sign::sign_card_value | signCardValue | sign_card_value |
| Verify an Agent Card | sign::verify_card | verifyCard | verify_card |
| Verify a signed delegation | sign::verify_delegation | verifyDelegation | verify_delegation |
| Claim check in and out | blob::check_in, blob::resolve_body | checkIn, resolveBody | check_in, resolve_body |
| Snapshot bytes | snapshot::encode, snapshot::decode | encodeSnapshot, decodeSnapshot | encode_snapshot, decode_snapshot |
| Resume offsets of a snapshot | agent::resume_offsets | resumeOffsets | resume_offsets |
| Reciprocal-rank fusion | memory::fuse_reciprocal_rank | fuseReciprocalRank | fuse_reciprocal_rank |
| Clocks | agent::SystemClock, agent::TestClock | SystemClock, TestClock | SystemClock, TestClock |
- The converters keep the original JSON bytes. Set the JSON content type when you publish the resulting envelope.
enter_bridgerejects an empty bridge ID and a path that already contains this bridge. In Rust it needs thea2a-bridgeor themcp-bridgefeature.verify_delegationchecks that the envelope signature verifies against an enrolled key, binds theagdx.ctandagdx.avheaders observed on the record, and was made while the key was valid at the record's server timestamp. It returns the signer and the delegated user from the signed metadata, or nothing when the envelope carries no delegation. Rust and TypeScript take the observed context and the time, Python takesat_microswithcontent_typeandagent_versionkeywords. The server authorizes only the authenticated caller and never reads the claim, so authorize the pair yourself withdelegated_allow.resume_offsetsreturns one past the last offset a snapshot folded for each partition, and stops at the unsigned 64-bit ceiling. The snapshot byte helpers read and write the named-field CBOR storage form, and fail with an invalid error on a bad snapshot.SystemClockandTestClockcount epoch microseconds as unsigned 64-bit values, andadvancewraps around at the ceiling.advancetakes aDurationin Rust and milliseconds in TypeScript and Python, kept to the microsecond. A TypeScriptTestClockneeds abigintstart, and Python defaults the start to 0. Both raiseInvalidErroroutside the range or on a negative advance.- The card helpers need the
signanda2a-bridgefeatures in Rust. Thesignfeature alone coversverify_delegation.
Where it runs
Bridges work on plain Apache Iggy, Laser Stack, and LaserData Cloud. reconstruct_state reads the managed state view only on a deployment that has one. The SDK does not host a model loop or a sandbox. A provider's event subscription is not an Iggy stream, so an adapter in front of one must map event IDs and cursors, record tool results with their correlation, and collect child results explicitly.
In Rust, enable a2a-bridge, mcp-bridge, or agui for the adapters, and add a2a-http or mcp-http for the Axum routers.