use std::sync::Arc;
use a2a::{
AgentCapabilities, AgentCard, AgentExtension, 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, PushConfigStore, StaticAgentCard, TaskStore,
};
use axum::extract::{Request, State};
use axum::http::uri::Authority;
use axum::http::{HeaderName, HeaderValue, 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::push::{PushSettings, SharedTasks};
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>,
extended_card: Option<AgentCard>,
allowed_hosts: Option<Vec<String>>,
max_request_bytes: usize,
push: PushSettings,
}
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,
extended_card: None,
allowed_hosts: None,
max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
push: PushSettings::new(),
}
}
#[must_use]
pub fn terminal_task_limit(mut self, max: usize) -> Self {
self.store = InMemoryTaskStore::new().with_terminal_task_limit(max.max(1));
self
}
}
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]
#[doc(alias = "max_sessions")]
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 allowed_hosts<I, H>(mut self, hosts: I) -> Self
where
I: IntoIterator<Item = H>,
H: Into<String>,
{
self.allowed_hosts = Some(hosts.into_iter().map(Into::into).collect());
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
}
#[must_use]
pub fn extended_card(mut self, card: AgentCard) -> Self {
self.extended_card = Some(card);
self
}
#[must_use]
pub fn extension(mut self, extension: AgentExtension) -> Self {
let declared = self
.card
.capabilities
.extensions
.get_or_insert_with(Vec::new);
if !declared.iter().any(|known| known.uri == extension.uri) {
declared.push(extension);
}
self
}
#[must_use]
pub fn push_notifications(mut self, enabled: bool) -> Self {
self.push.enabled = enabled;
self.card.capabilities.push_notifications = Some(enabled);
self
}
#[must_use]
pub fn push_config_store<P: PushConfigStore>(mut self, store: P) -> Self {
self.push.store = Some(Arc::new(store));
self.push_notifications(true)
}
#[must_use]
pub fn push_allowed_hosts<I, H>(mut self, hosts: I) -> Self
where
I: IntoIterator<Item = H>,
H: Into<String>,
{
self.push.allowed_hosts = Some(hosts.into_iter().map(Into::into).collect());
self
}
#[must_use]
pub fn allow_unguarded_push_urls(mut self) -> Self {
self.push.allow_unguarded = true;
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,
extended_card: self.extended_card,
allowed_hosts: self.allowed_hosts,
max_request_bytes: self.max_request_bytes,
push: self.push,
}
}
pub fn card(&self) -> &AgentCard {
&self.card
}
pub fn into_router(self) -> axum::Router {
let mut card = self.card;
let push_on = self.push.enabled && self.bearer.is_some();
if self.push.enabled && !push_on {
tracing::error!(
"push notifications need a bearer_token on the A2aServer; push stays off"
);
}
card.capabilities.push_notifications = Some(push_on);
let configured = self.extended_card.is_some();
let extended = self.extended_card.filter(|_| self.bearer.is_some());
if configured && extended.is_none() {
tracing::error!(
"an extended agent card needs a bearer_token on the A2aServer; the extended card stays off"
);
}
card.capabilities.extended_agent_card = extended.as_ref().map(|_| true);
let tasks: Arc<dyn TaskStore> = Arc::new(self.store);
let declared: Arc<[String]> = card
.capabilities
.extensions
.iter()
.flatten()
.map(|extension| extension.uri.clone())
.collect();
let mut handler = DefaultRequestHandler::new(
self.executor.declaring(Arc::clone(&declared)),
SharedTasks(Arc::clone(&tasks)),
)
.with_capabilities(card.capabilities.clone())
.with_default_input_modes(card.default_input_modes.clone());
if let Some(extended) = extended {
handler = handler.with_extended_agent_card(extended);
}
if push_on {
handler = handler.with_push_notifications(
self.push.checked_store(Arc::clone(&tasks)),
self.push.sender(),
);
}
let handler = Arc::new(handler);
let v03_card = v03::card(
&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, Arc::clone(&declared)))
.layer(axum::middleware::from_fn_with_state(
Arc::clone(&declared),
echo_extensions,
))
.route_layer(auth)
.layer(tower_http::limit::RequestBodyLimitLayer::new(
self.max_request_bytes,
));
let cards = agent_card_router(Arc::new(StaticAgentCard::new(card)))
.route(
&format!("{V03_PATH}{}", a2a_server::WELL_KNOWN_AGENT_CARD_PATH),
axum::routing::get(move || async move { axum::Json(v03_card) }),
)
.layer(axum::middleware::from_fn_with_state(
declared,
echo_extensions,
));
let host_guard = self.allowed_hosts.map(Arc::new);
calls
.merge(cards)
.layer(axum::middleware::from_fn_with_state(host_guard, check_host))
}
}
pub(crate) const EXTENSIONS_HEADER: HeaderName = HeaderName::from_static("a2a-extensions");
pub(crate) const V03_EXTENSIONS_HEADER: HeaderName = HeaderName::from_static("x-a2a-extensions");
pub(crate) fn activated_extensions(
headers: &axum::http::HeaderMap,
name: &HeaderName,
declared: &[String],
) -> Vec<String> {
let mut activated: Vec<String> = headers
.get_all(name)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.map(str::trim)
.filter(|uri| declared.iter().any(|d| d.as_str() == *uri))
.map(str::to_owned)
.collect();
activated.sort_unstable();
activated.dedup();
activated
}
async fn echo_extensions(
State(declared): State<Arc<[String]>>,
request: Request,
next: Next,
) -> Response {
if declared.is_empty() {
return next.run(request).await;
}
let activated = activated_extensions(request.headers(), &EXTENSIONS_HEADER, &declared);
let mut response = next.run(request).await;
if let Ok(value) = HeaderValue::from_str(&activated.join(", "))
&& !activated.is_empty()
{
response.headers_mut().insert(EXTENSIONS_HEADER, value);
}
response
}
async fn check_host(
State(allowed): State<Option<Arc<Vec<String>>>>,
request: Request,
next: Next,
) -> Response {
let Some(allowed) = allowed else {
return next.run(request).await;
};
let given = request
.headers()
.get(header::HOST)
.and_then(|value| value.to_str().ok());
if host_allowed(&allowed, given) {
next.run(request).await
} else {
(
StatusCode::FORBIDDEN,
[(header::CONTENT_TYPE, "application/json")],
r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Host not allowed"}}"#,
)
.into_response()
}
}
fn host_allowed(allowed: &[String], given: Option<&str>) -> bool {
let Some(given) = given.and_then(|value| Authority::try_from(value.trim()).ok()) else {
return false;
};
let host = normalize_host(given.host());
let port = given.port_u16();
allowed.iter().any(|entry| {
let entry = entry.trim();
let (entry_host, entry_port) = match Authority::try_from(entry) {
Ok(authority) => (normalize_host(authority.host()), authority.port_u16()),
Err(_) => (normalize_host(entry), None),
};
entry_host == host && entry_port.is_none_or(|entry_port| port == Some(entry_port))
})
}
fn normalize_host(host: &str) -> String {
host.trim_matches(['[', ']']).to_ascii_lowercase()
}
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,
}
}