use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use greentic_a2a::fetch::{CardCache, require_secure_interface};
use greentic_a2a::message::{
ADAPTIVE_CARD_MEDIA_TYPE, Message, Part, Role, Task, TaskProgress, TaskState,
};
use greentic_a2a::rpc::{
JsonRpcRequest, JsonRpcResponse, METHOD_SEND_MESSAGE, SendMessageConfiguration,
SendMessageParams, SendMessageResult,
};
use greentic_secrets_lib::SecretsManager;
use serde_json::Value;
use super::auth::{CredentialScope, ensure_same_host};
use super::continuation::A2aContinuation;
use super::outcome::A2aOutcome;
use super::types::{A2aRoute, A2aToolCatalog, A2aToolEntry};
use crate::oauth::TokenProvider;
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::from_routes_with_provider(routes, secrets, tenant, unit, TokenProvider::shared())
}
pub fn from_routes_with_provider(
routes: Vec<A2aRoute>,
secrets: Option<Arc<dyn SecretsManager>>,
tenant: impl Into<String>,
unit: Option<String>,
provider: Arc<TokenProvider>,
) -> Result<Self, reqwest::Error> {
Self::build(
routes,
CredentialScope::new(secrets, tenant.into(), unit, provider),
)
}
fn build(routes: Vec<A2aRoute>, credentials: CredentialScope) -> Result<Self, reqwest::Error> {
let client = build_http_client(crate::outbound_guard::HttpGuard::from_env())?;
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, false, 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>,
want_card: bool,
answer: Option<&Value>,
) -> Result<A2aReply, String> {
let first = self
.send_once(agent_id, text, prior, want_card, answer)
.await;
match (first, prior) {
(Err(SendError::Rejected(reason)), Some(held)) if held.task_id.is_some() => {
tracing::warn!(
agent = %agent_id,
error = %reason,
"a2a agent rejected a message naming a task; retrying once without the task id"
);
let without_task = A2aContinuation {
task_id: None,
..held.clone()
};
self.send_once(agent_id, text, Some(&without_task), want_card, answer)
.await
.map_err(SendError::into_message)
}
(result, _) => result.map_err(SendError::into_message),
}
}
async fn send_once(
&self,
agent_id: &str,
text: &str,
prior: Option<&A2aContinuation>,
want_card: bool,
answer: Option<&Value>,
) -> Result<A2aReply, SendError> {
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}").into());
}
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"
)
.into());
}
check_target_literal(agent_id, &target)?;
let oauth = CredentialScope::is_oauth(route);
if route.requires_auth || oauth {
ensure_same_host(agent_id, &route.base_url, &target)?;
}
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: message_parts(text, answer),
metadata: None,
};
let configuration = want_card.then(|| SendMessageConfiguration {
accepted_output_modes: vec![
ADAPTIVE_CARD_MEDIA_TYPE.to_string(),
"text/plain".to_string(),
],
});
let params = SendMessageParams {
message,
tenant: interface.tenant.clone(),
configuration,
metadata: None,
};
let request = JsonRpcRequest::new(1, METHOD_SEND_MESSAGE, params);
let mut retried = false;
let response = loop {
let auth = self.credentials.header_for(route).await?;
let mut post = self.client.post(target.clone()).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.without_url())
})?;
if oauth && !retried && response.status() == reqwest::StatusCode::UNAUTHORIZED {
self.credentials.invalidate(route).await;
retried = true;
continue;
}
break response;
};
let status = response.status();
if !status.is_success() {
let message = format!("a2a agent {agent_id} answered HTTP {status}");
return Err(
if status.is_client_error() && !is_auth_or_rate_limit(status) {
SendError::Rejected(message)
} else {
SendError::Failed(message)
},
);
}
let bytes = read_capped(response, MAX_REPLY_BYTES)
.await
.map_err(|err| format!("a2a agent {agent_id} sent an unreadable reply: {err}"))?;
let body: JsonRpcResponse<SendMessageResult> = serde_json::from_slice(&bytes)
.map_err(|err| format!("a2a agent {agent_id} sent an unreadable reply: {err}"))?;
if let Some(error) = body.error {
return Err(SendError::Rejected(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")?,
card: card_of(&reply.parts),
},
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").into())
}
}
}
}
const MAX_REPLY_BYTES: usize = 4 * 1024 * 1024;
enum SendError {
Rejected(String),
Failed(String),
}
impl SendError {
fn into_message(self) -> String {
match self {
Self::Rejected(message) | Self::Failed(message) => message,
}
}
}
impl From<String> for SendError {
fn from(message: String) -> Self {
Self::Failed(message)
}
}
fn is_auth_or_rate_limit(status: reqwest::StatusCode) -> bool {
matches!(status.as_u16(), 401 | 403 | 429)
}
async fn read_capped(mut response: reqwest::Response, cap: usize) -> Result<Vec<u8>, String> {
if response
.content_length()
.is_some_and(|declared| declared > cap as u64)
{
return Err(format!("reply larger than {cap} bytes"));
}
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
if body.len() + chunk.len() > cap {
return Err(format!("reply larger than {cap} bytes"));
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
fn message_parts(text: &str, answer: Option<&Value>) -> Vec<Part> {
let answer = answer.filter(|a| a.as_object().is_some_and(|m| !m.is_empty()));
let mut parts = Vec::new();
if !text.trim().is_empty() || answer.is_none() {
parts.push(Part::text(text));
}
if let Some(answer) = answer {
parts.push(Part::data(answer.clone()));
}
parts
}
fn card_of(parts: &[Part]) -> Option<Value> {
parts.iter().find_map(|part| part.adaptive_card().cloned())
}
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 card = task.status.message.as_ref().and_then(|m| card_of(&m.parts));
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, card },
Err(reason) => A2aOutcome::Ended {
state: TaskState::Completed,
detail: Some(reason),
},
}
}
TaskProgress::Open if state == TaskState::InputRequired => A2aOutcome::InputRequired {
question: detail,
card,
},
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),
}
}
fn check_target_literal(agent_id: &str, target: &url::Url) -> Result<(), String> {
crate::outbound_guard::HttpGuard::from_env()
.check_url_literal(target)
.map_err(|reason| format!("a2a agent {agent_id} interface URL refused: {reason}"))
}
fn build_http_client(
guard: crate::outbound_guard::HttpGuard,
) -> Result<reqwest::Client, reqwest::Error> {
reqwest::Client::builder()
.no_proxy()
.dns_resolver(Arc::new(crate::outbound_guard::GuardedResolver { guard }))
.redirect(reqwest::redirect::Policy::none())
.timeout(CALL_TIMEOUT)
.build()
}
#[cfg(test)]
mod proxy_tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::io::{Read, Write};
use std::net::TcpListener;
use std::process::Command;
const CHILD_FLAG: &str = "GREENTIC_TEST_PROXY_CHILD";
fn spawn_stub(listener: TcpListener) -> std::thread::JoinHandle<bool> {
listener.set_nonblocking(true).unwrap();
std::thread::spawn(move || {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
while std::time::Instant::now() < deadline {
if let Ok((mut stream, _)) = listener.accept() {
stream.set_nonblocking(false).ok();
let mut buf = [0u8; 1024];
let _ = stream.read(&mut buf);
let _ = stream.write_all(
b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok",
);
return true;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
false
})
}
#[test]
fn a2a_client_ignores_the_environment_proxy() {
if std::env::var_os(CHILD_FLAG).is_none() {
let proxy = TcpListener::bind("127.0.0.1:0").unwrap();
let target = TcpListener::bind("127.0.0.1:0").unwrap();
let proxy_url = format!("http://{}", proxy.local_addr().unwrap());
let target_url = format!("http://{}/", target.local_addr().unwrap());
let proxy_hit = spawn_stub(proxy);
let target_hit = spawn_stub(target);
let status = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"a2a_source::source::proxy_tests::a2a_client_ignores_the_environment_proxy",
"--test-threads=1",
])
.env(CHILD_FLAG, &target_url)
.env("HTTP_PROXY", &proxy_url)
.env("http_proxy", &proxy_url)
.env("ALL_PROXY", &proxy_url)
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.status()
.unwrap();
assert!(status.success(), "child failed");
assert!(
target_hit.join().unwrap(),
"target must be reached directly"
);
assert!(!proxy_hit.join().unwrap(), "the env proxy must not be used");
return;
}
let url = std::env::var(CHILD_FLAG).unwrap();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let client =
super::build_http_client(crate::outbound_guard::HttpGuard::from_env()).unwrap();
let body =
rt.block_on(async { client.get(&url).send().await.unwrap().text().await.unwrap() });
assert_eq!(body, "ok");
}
}
#[cfg(test)]
mod literal_guard_tests {
use super::check_target_literal;
fn refused(raw: &str) -> bool {
match url::Url::parse(raw) {
Ok(u) => check_target_literal("a1", &u).is_err(),
Err(_) => false,
}
}
fn allowed(raw: &str) -> bool {
match url::Url::parse(raw) {
Ok(u) => check_target_literal("a1", &u).is_ok(),
Err(_) => false,
}
}
#[test]
fn metadata_and_link_local_literals_are_refused() {
assert!(refused("http://169.254.169.254/latest/meta-data/"));
assert!(refused("http://[fd00:ec2::254]/"));
assert!(refused("http://169.254.1.1:8080/rpc"));
}
#[test]
fn ordinary_hosts_and_loopback_pass() {
assert!(allowed("https://agent.example.com/rpc"));
assert!(allowed("http://127.0.0.1:9000/rpc"));
}
}