use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use greentic_a2a::fetch::{CardCache, require_secure_interface};
use greentic_a2a::message::{Message, Part, Role, Task, TaskProgress, TaskState};
use greentic_a2a::rpc::{
JsonRpcRequest, JsonRpcResponse, METHOD_SEND_MESSAGE, SendMessageParams, SendMessageResult,
};
use greentic_secrets_lib::SecretsManager;
use super::auth::{CredentialScope, ensure_same_host};
use super::continuation::A2aContinuation;
use super::outcome::A2aOutcome;
use super::types::{A2aRoute, A2aToolCatalog, A2aToolEntry};
const CARD_TTL: Duration = Duration::from_secs(5 * 60);
const CALL_TIMEOUT: Duration = Duration::from_secs(30);
const SUPPORTED_EXTENSIONS: &[&str] = &[];
fn unsupported_required_extensions(card: &greentic_a2a::card::AgentCard) -> Option<String> {
let missing: Vec<&str> = card
.capabilities
.required_extension_uris()
.into_iter()
.filter(|uri| !SUPPORTED_EXTENSIONS.contains(uri))
.collect();
(!missing.is_empty()).then(|| {
format!(
"requires protocol extension(s) this client does not implement: {}",
missing.join(", ")
)
})
}
pub struct A2aToolSource {
transport: Arc<Transport>,
}
pub(super) struct Transport {
agents: HashMap<String, A2aRoute>,
cards: CardCache,
client: reqwest::Client,
credentials: CredentialScope,
}
impl std::fmt::Debug for Transport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Transport")
.field("agents", &self.agents.keys().collect::<Vec<_>>())
.finish_non_exhaustive()
}
}
impl A2aToolSource {
pub fn new(agents: Vec<(String, String)>) -> Result<Self, reqwest::Error> {
let routes = agents
.into_iter()
.map(|(agent_id, base)| A2aRoute::unauthenticated(agent_id, base))
.collect();
Self::build(routes, CredentialScope::none())
}
pub fn from_routes(
routes: Vec<A2aRoute>,
secrets: Option<Arc<dyn SecretsManager>>,
tenant: impl Into<String>,
unit: Option<String>,
) -> Result<Self, reqwest::Error> {
Self::build(routes, CredentialScope::new(secrets, tenant.into(), unit))
}
fn build(routes: Vec<A2aRoute>, credentials: CredentialScope) -> Result<Self, reqwest::Error> {
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(CALL_TIMEOUT)
.build()?;
let mut agents = HashMap::with_capacity(routes.len());
for route in routes {
agents.entry(route.agent_id.clone()).or_insert(route);
}
Ok(Self {
transport: Arc::new(Transport {
agents,
cards: CardCache::new(CARD_TTL)?,
client,
credentials,
}),
})
}
pub async fn catalog(&self) -> Arc<A2aToolCatalog> {
let mut catalog = self.transport.fetch_cards().await;
catalog.caller = Some(Arc::clone(&self.transport));
Arc::new(catalog)
}
pub async fn call(&self, agent_id: &str, text: &str) -> Result<String, String> {
match self.transport.send(agent_id, text, None).await? {
A2aReply {
outcome: A2aOutcome::Answered { text },
..
} => Ok(text),
other => Err(flatten_non_answer(agent_id, &other.outcome)),
}
}
}
pub(super) struct A2aReply {
pub(super) outcome: A2aOutcome,
pub(super) context_id: Option<String>,
pub(super) task_id: Option<String>,
}
fn flatten_non_answer(agent_id: &str, outcome: &A2aOutcome) -> String {
match outcome.to_value(agent_id) {
serde_json::Value::Object(map) => map
.get("error")
.or_else(|| map.get("question"))
.or_else(|| map.get("detail"))
.and_then(|v| v.as_str())
.map(str::to_string)
.unwrap_or_else(|| format!("a2a agent {agent_id} did not answer")),
_ => format!("a2a agent {agent_id} did not answer"),
}
}
impl Transport {
async fn fetch_cards(&self) -> A2aToolCatalog {
let fetched =
futures::future::join_all(self.agents.iter().map(|(agent_id, route)| async move {
(agent_id, self.cards.get(&route.base_url).await)
}))
.await;
let mut tools = HashMap::new();
let mut errors = HashMap::new();
for (agent_id, result) in fetched {
match result {
Ok(card) => match unsupported_required_extensions(&card) {
Some(reason) => {
tracing::warn!(
agent = %agent_id,
reason = %reason,
"a2a agent requires an unimplemented protocol extension"
);
errors.insert(agent_id.clone(), reason);
}
None => {
tools.insert(
agent_id.clone(),
A2aToolEntry {
description: card.description.clone(),
},
);
}
},
Err(err) => {
tracing::warn!(agent = %agent_id, error = %err, "a2a agent card unavailable");
errors.insert(agent_id.clone(), err.to_string());
}
}
}
A2aToolCatalog {
tools,
errors,
caller: None,
}
}
pub(super) async fn send(
&self,
agent_id: &str,
text: &str,
prior: Option<&A2aContinuation>,
) -> Result<A2aReply, String> {
let route = self
.agents
.get(agent_id)
.ok_or_else(|| format!("unknown a2a agent: {agent_id}"))?;
let card = self
.cards
.get(&route.base_url)
.await
.map_err(|err| format!("fetching card for a2a agent {agent_id} failed: {err}"))?;
if let Some(reason) = unsupported_required_extensions(&card) {
return Err(format!("a2a agent {agent_id} {reason}"));
}
let interface = card
.supported_interfaces
.first()
.ok_or_else(|| format!("a2a agent {agent_id} advertises no interfaces"))?;
let target = require_secure_interface(&route.base_url, &interface.url)
.map_err(|err| format!("a2a agent {agent_id} names an unusable interface: {err}"))?;
if !target.username().is_empty() || target.password().is_some() {
return Err(format!(
"a2a agent {agent_id} names an interface URL carrying userinfo; refusing it"
));
}
if route.requires_auth {
ensure_same_host(agent_id, &route.base_url, &target)?;
}
let auth = self.credentials.header_for(route).await?;
let message = Message {
message_id: uuid::Uuid::new_v4().to_string(),
context_id: prior.map(|c| c.context_id.clone()),
task_id: prior.and_then(|c| c.task_id.clone()),
role: Role::User,
parts: vec![Part::text(text)],
metadata: None,
};
let params = SendMessageParams {
message,
tenant: interface.tenant.clone(),
metadata: None,
};
let request = JsonRpcRequest::new(1, METHOD_SEND_MESSAGE, params);
let mut post = self.client.post(target).json(&request);
if let Some((name, value)) = auth {
post = post.header(name, value);
}
let response = post
.send()
.await
.map_err(|err| format!("calling a2a agent {agent_id} failed: {err}"))?;
let status = response.status();
if !status.is_success() {
return Err(format!("a2a agent {agent_id} answered HTTP {status}"));
}
let body: JsonRpcResponse<SendMessageResult> = response
.json()
.await
.map_err(|err| format!("a2a agent {agent_id} sent an unreadable reply: {err}"))?;
if let Some(error) = body.error {
return Err(format!(
"a2a agent {agent_id} returned an error: {}",
error.message
));
}
match body.result {
Some(SendMessageResult::Message(reply)) => Ok(A2aReply {
outcome: A2aOutcome::Answered {
text: reply_text(agent_id, &reply.parts, "replied with no text part")?,
},
context_id: reply.context_id,
task_id: None,
}),
Some(SendMessageResult::Task(task)) => Ok(task_reply(agent_id, task)),
None => Err(format!(
"a2a agent {agent_id} returned neither a result nor an error"
)),
}
}
}
fn reply_text(agent_id: &str, parts: &[Part], empty: &str) -> Result<String, String> {
let texts: Vec<&str> = parts
.iter()
.filter_map(|part| part.text.as_deref())
.collect();
if texts.is_empty() {
return Err(format!("a2a agent {agent_id} {empty}"));
}
Ok(texts.join("\n"))
}
fn artifact_answer(agent_id: &str, parts: &[Part]) -> Result<String, String> {
let mut lines: Vec<String> = parts.iter().filter_map(|part| part.text.clone()).collect();
lines.extend(parts.iter().filter_map(structured_text));
if lines.is_empty() {
return Err(format!(
"a2a agent {agent_id} completed a task with no text artifact"
));
}
Ok(lines.join("\n"))
}
fn structured_text(part: &Part) -> Option<String> {
let value = part.data.as_ref()?;
if part.media_type.as_deref() != Some(STRUCTURED_OUTPUT_MEDIA_TYPE) {
return None;
}
serde_json::to_string(value).ok()
}
const STRUCTURED_OUTPUT_MEDIA_TYPE: &str = "application/json";
fn task_reply(agent_id: &str, task: Task) -> A2aReply {
let detail = task
.status
.message
.as_ref()
.and_then(|m| reply_text(agent_id, &m.parts, "").ok());
let state = task.status.state;
let open = matches!(state.progress(), TaskProgress::Open);
let outcome = match state.progress() {
TaskProgress::Done => {
let parts: Vec<Part> = task
.artifacts
.iter()
.flat_map(|artifact| artifact.parts.iter().cloned())
.collect();
match artifact_answer(agent_id, &parts) {
Ok(text) => A2aOutcome::Answered { text },
Err(reason) => A2aOutcome::Ended {
state: TaskState::Completed,
detail: Some(reason),
},
}
}
TaskProgress::Open if state == TaskState::InputRequired => {
A2aOutcome::InputRequired { question: detail }
}
TaskProgress::Open => A2aOutcome::Working { state, detail },
TaskProgress::Ended => A2aOutcome::Ended { state, detail },
};
A2aReply {
outcome,
context_id: task.context_id,
task_id: open.then_some(task.id),
}
}