use std::sync::Arc;
use a2a::{
AgentCapabilities, AgentCard, AgentInterface, AgentSkill, HttpAuthSecurityScheme,
SecurityScheme, TRANSPORT_PROTOCOL_HTTP_JSON, TRANSPORT_PROTOCOL_JSONRPC,
};
use a2a_server::agent_card::agent_card_router;
use a2a_server::jsonrpc::jsonrpc_router;
use a2a_server::rest::rest_router;
use a2a_server::{DefaultRequestHandler, InMemoryTaskStore, StaticAgentCard, TaskStore};
use axum::extract::{Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use rig_agent::Agent;
use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
use crate::A2aExecutor;
use crate::v03::{self, V03_PATH};
pub const JSONRPC_PATH: &str = "/jsonrpc";
pub const REST_PATH: &str = "/rest";
pub struct A2aServer<S = InMemoryTaskStore> {
executor: A2aExecutor,
card: AgentCard,
store: S,
url: String,
bearer: Option<String>,
max_request_bytes: usize,
}
pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;
impl A2aServer {
pub fn new(agent: Agent, url: impl AsRef<str>) -> Self {
let url = url.as_ref().trim_end_matches('/').to_owned();
Self {
card: default_card(&agent, &url),
executor: A2aExecutor::new(agent),
store: InMemoryTaskStore::new(),
url,
bearer: None,
max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
}
}
}
impl<S: TaskStore> A2aServer<S> {
#[must_use]
pub fn edit_card(mut self, edit: impl FnOnce(&mut AgentCard)) -> Self {
edit(&mut self.card);
self
}
#[must_use]
pub fn max_contexts(mut self, max: usize) -> Self {
self.executor = self.executor.max_contexts(max);
self
}
#[must_use]
pub fn typed<T>(mut self) -> Self
where
T: schemars::JsonSchema
+ serde::de::DeserializeOwned
+ serde::Serialize
+ WasmCompatSend
+ WasmCompatSync
+ 'static,
{
self.executor = self.executor.typed::<T>();
let schema = serde_json::to_string(&schemars::schema_for!(T)).unwrap_or_default();
let json = vec!["application/json".to_owned()];
self.card.default_output_modes = json.clone();
for skill in &mut self.card.skills {
skill.output_modes = Some(json.clone());
skill.description = format!(
"{} Answers with JSON matching this schema: {schema}",
skill.description
);
}
self
}
#[must_use]
pub fn history_store<T>(mut self, store: T) -> Self
where
T: rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
{
self.executor = self.executor.history_store(store);
self
}
#[must_use]
pub fn history_window(mut self, window: impl rig_memory::recent::Recent + 'static) -> Self {
self.executor = self.executor.history_window(window);
self
}
#[must_use]
pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
self.executor = self.executor.max_concurrent_tasks(max);
self
}
#[must_use]
pub fn max_run_duration(mut self, max: std::time::Duration) -> Self {
self.executor = self.executor.max_run_duration(max);
self
}
#[must_use]
pub fn max_request_bytes(mut self, bytes: usize) -> Self {
self.max_request_bytes = bytes;
self
}
#[must_use]
pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
self.bearer = Some(token.into());
let scheme = SecurityScheme::HttpAuth(HttpAuthSecurityScheme {
scheme: "bearer".to_owned(),
description: None,
bearer_format: None,
});
self.card.security_schemes = Some([("bearer".to_owned(), scheme)].into());
self.card.security_requirements = Some(vec![[("bearer".to_owned(), vec![])].into()]);
self
}
pub fn task_store<T: TaskStore>(self, store: T) -> A2aServer<T> {
A2aServer {
executor: self.executor,
card: self.card,
store,
url: self.url,
bearer: self.bearer,
max_request_bytes: self.max_request_bytes,
}
}
pub fn card(&self) -> &AgentCard {
&self.card
}
pub fn into_router(self) -> axum::Router {
let handler = Arc::new(
DefaultRequestHandler::new(self.executor, self.store)
.with_capabilities(self.card.capabilities.clone())
.with_default_input_modes(self.card.default_input_modes.clone()),
);
let v03_card = v03::card(
&self.card,
&format!("{}{V03_PATH}", self.url),
self.bearer.is_some(),
);
let expected: Option<Arc<str>> = self.bearer.map(|token| format!("Bearer {token}").into());
let auth = axum::middleware::from_fn_with_state(expected, guard);
let calls = axum::Router::new()
.nest(JSONRPC_PATH, jsonrpc_router(Arc::clone(&handler)))
.nest(REST_PATH, rest_router(Arc::clone(&handler)))
.nest(V03_PATH, v03::router(handler))
.route_layer(auth)
.layer(tower_http::limit::RequestBodyLimitLayer::new(
self.max_request_bytes,
));
calls
.merge(agent_card_router(Arc::new(StaticAgentCard::new(self.card))))
.route(
&format!("{V03_PATH}{}", a2a_server::WELL_KNOWN_AGENT_CARD_PATH),
axum::routing::get(move || async move { axum::Json(v03_card) }),
)
}
}
async fn guard(State(expected): State<Option<Arc<str>>>, request: Request, next: Next) -> Response {
let given = request
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok());
match (expected.as_deref(), given) {
(None, _) => next.run(request).await,
(Some(expected), Some(given)) if same(expected, given) => next.run(request).await,
_ => (
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
)
.into_response(),
}
}
fn same(a: &str, b: &str) -> bool {
a.len() == b.len()
&& a.bytes()
.zip(b.bytes())
.fold(0, |acc, (x, y)| acc | (x ^ y))
== 0
}
fn default_card(agent: &Agent, url: &str) -> AgentCard {
let url = url.trim_end_matches('/');
let name = agent.name().unwrap_or("Rig agent").to_owned();
let description = agent
.description()
.unwrap_or("An agent built with Rig.")
.to_owned();
AgentCard {
skills: vec![AgentSkill {
id: "chat".to_owned(),
name: name.clone(),
description: description.clone(),
tags: vec!["chat".to_owned()],
examples: None,
input_modes: None,
output_modes: None,
security_requirements: None,
}],
name,
description,
version: "1.0.0".to_owned(),
supported_interfaces: vec![
AgentInterface::new(format!("{url}{JSONRPC_PATH}"), TRANSPORT_PROTOCOL_JSONRPC),
AgentInterface::new(format!("{url}{REST_PATH}"), TRANSPORT_PROTOCOL_HTTP_JSON),
],
capabilities: AgentCapabilities {
streaming: Some(true),
push_notifications: Some(false),
extensions: None,
extended_agent_card: None,
},
default_input_modes: vec!["text/plain".to_owned(), "application/json".to_owned()],
default_output_modes: vec!["text/plain".to_owned()],
provider: None,
documentation_url: None,
icon_url: None,
security_schemes: None,
security_requirements: None,
signatures: None,
}
}