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