1use std::sync::Arc;
4
5use a2a::{
6 AgentCapabilities, AgentCard, AgentInterface, AgentSkill, HttpAuthSecurityScheme,
7 SecurityScheme, TRANSPORT_PROTOCOL_HTTP_JSON, TRANSPORT_PROTOCOL_JSONRPC,
8};
9use a2a_server::agent_card::agent_card_router;
10use a2a_server::jsonrpc::jsonrpc_router;
11use a2a_server::rest::rest_router;
12use a2a_server::{DefaultRequestHandler, InMemoryTaskStore, StaticAgentCard, TaskStore};
13use axum::extract::{Request, State};
14use axum::http::{StatusCode, header};
15use axum::middleware::Next;
16use axum::response::{IntoResponse, Response};
17use rig_agent::Agent;
18use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
19
20use crate::A2aExecutor;
21use crate::v03::{self, V03_PATH};
22
23pub const JSONRPC_PATH: &str = "/jsonrpc";
25pub const REST_PATH: &str = "/rest";
27
28pub struct A2aServer<S = InMemoryTaskStore> {
40 executor: A2aExecutor,
41 card: AgentCard,
42 store: S,
43 url: String,
44 bearer: Option<String>,
45 max_request_bytes: usize,
46}
47
48pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;
50
51impl A2aServer {
52 pub fn new(agent: Agent, url: impl AsRef<str>) -> Self {
58 let url = url.as_ref().trim_end_matches('/').to_owned();
59 Self {
60 card: default_card(&agent, &url),
61 executor: A2aExecutor::new(agent),
62 store: InMemoryTaskStore::new(),
63 url,
64 bearer: None,
65 max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
66 }
67 }
68}
69
70impl<S: TaskStore> A2aServer<S> {
71 #[must_use]
77 pub fn edit_card(mut self, edit: impl FnOnce(&mut AgentCard)) -> Self {
78 edit(&mut self.card);
79 self
80 }
81
82 #[must_use]
84 pub fn max_contexts(mut self, max: usize) -> Self {
85 self.executor = self.executor.max_contexts(max);
86 self
87 }
88
89 #[must_use]
93 pub fn typed<T>(mut self) -> Self
94 where
95 T: schemars::JsonSchema
96 + serde::de::DeserializeOwned
97 + serde::Serialize
98 + WasmCompatSend
99 + WasmCompatSync
100 + 'static,
101 {
102 self.executor = self.executor.typed::<T>();
103 let schema = serde_json::to_string(&schemars::schema_for!(T)).unwrap_or_default();
104 let json = vec!["application/json".to_owned()];
105 self.card.default_output_modes = json.clone();
106 for skill in &mut self.card.skills {
107 skill.output_modes = Some(json.clone());
108 skill.description = format!(
109 "{} Answers with JSON matching this schema: {schema}",
110 skill.description
111 );
112 }
113 self
114 }
115
116 #[must_use]
119 pub fn history_store<T>(mut self, store: T) -> Self
120 where
121 T: rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
122 {
123 self.executor = self.executor.history_store(store);
124 self
125 }
126
127 #[must_use]
130 pub fn history_window(mut self, window: impl rig_memory::recent::Recent + 'static) -> Self {
131 self.executor = self.executor.history_window(window);
132 self
133 }
134
135 #[must_use]
137 pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
138 self.executor = self.executor.max_concurrent_tasks(max);
139 self
140 }
141
142 #[must_use]
144 pub fn max_run_duration(mut self, max: std::time::Duration) -> Self {
145 self.executor = self.executor.max_run_duration(max);
146 self
147 }
148
149 #[must_use]
152 pub fn max_request_bytes(mut self, bytes: usize) -> Self {
153 self.max_request_bytes = bytes;
154 self
155 }
156
157 #[must_use]
161 pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
162 self.bearer = Some(token.into());
163 let scheme = SecurityScheme::HttpAuth(HttpAuthSecurityScheme {
164 scheme: "bearer".to_owned(),
165 description: None,
166 bearer_format: None,
167 });
168 self.card.security_schemes = Some([("bearer".to_owned(), scheme)].into());
169 self.card.security_requirements = Some(vec![[("bearer".to_owned(), vec![])].into()]);
170 self
171 }
172
173 pub fn task_store<T: TaskStore>(self, store: T) -> A2aServer<T> {
175 A2aServer {
176 executor: self.executor,
177 card: self.card,
178 store,
179 url: self.url,
180 bearer: self.bearer,
181 max_request_bytes: self.max_request_bytes,
182 }
183 }
184
185 pub fn card(&self) -> &AgentCard {
187 &self.card
188 }
189
190 pub fn into_router(self) -> axum::Router {
192 let handler = Arc::new(
193 DefaultRequestHandler::new(self.executor, self.store)
194 .with_capabilities(self.card.capabilities.clone())
195 .with_default_input_modes(self.card.default_input_modes.clone()),
196 );
197 let v03_card = v03::card(
198 &self.card,
199 &format!("{}{V03_PATH}", self.url),
200 self.bearer.is_some(),
201 );
202 let expected: Option<Arc<str>> = self.bearer.map(|token| format!("Bearer {token}").into());
203 let auth = axum::middleware::from_fn_with_state(expected, guard);
204 let calls = axum::Router::new()
205 .nest(JSONRPC_PATH, jsonrpc_router(Arc::clone(&handler)))
206 .nest(REST_PATH, rest_router(Arc::clone(&handler)))
207 .nest(V03_PATH, v03::router(handler))
208 .route_layer(auth)
209 .layer(tower_http::limit::RequestBodyLimitLayer::new(
211 self.max_request_bytes,
212 ));
213 calls
215 .merge(agent_card_router(Arc::new(StaticAgentCard::new(self.card))))
216 .route(
217 &format!("{V03_PATH}{}", a2a_server::WELL_KNOWN_AGENT_CARD_PATH),
218 axum::routing::get(move || async move { axum::Json(v03_card) }),
219 )
220 }
221}
222
223async fn guard(State(expected): State<Option<Arc<str>>>, request: Request, next: Next) -> Response {
226 let given = request
227 .headers()
228 .get(header::AUTHORIZATION)
229 .and_then(|value| value.to_str().ok());
230 match (expected.as_deref(), given) {
231 (None, _) => next.run(request).await,
232 (Some(expected), Some(given)) if same(expected, given) => next.run(request).await,
233 _ => (
234 StatusCode::UNAUTHORIZED,
235 [(header::WWW_AUTHENTICATE, "Bearer")],
236 )
237 .into_response(),
238 }
239}
240
241fn same(a: &str, b: &str) -> bool {
243 a.len() == b.len()
244 && a.bytes()
245 .zip(b.bytes())
246 .fold(0, |acc, (x, y)| acc | (x ^ y))
247 == 0
248}
249
250fn default_card(agent: &Agent, url: &str) -> AgentCard {
251 let url = url.trim_end_matches('/');
252 let name = agent.name().unwrap_or("Rig agent").to_owned();
253 let description = agent
254 .description()
255 .unwrap_or("An agent built with Rig.")
256 .to_owned();
257 AgentCard {
258 skills: vec![AgentSkill {
259 id: "chat".to_owned(),
260 name: name.clone(),
261 description: description.clone(),
262 tags: vec!["chat".to_owned()],
263 examples: None,
264 input_modes: None,
265 output_modes: None,
266 security_requirements: None,
267 }],
268 name,
269 description,
270 version: "1.0.0".to_owned(),
271 supported_interfaces: vec![
272 AgentInterface::new(format!("{url}{JSONRPC_PATH}"), TRANSPORT_PROTOCOL_JSONRPC),
273 AgentInterface::new(format!("{url}{REST_PATH}"), TRANSPORT_PROTOCOL_HTTP_JSON),
274 ],
275 capabilities: AgentCapabilities {
276 streaming: Some(true),
277 push_notifications: Some(false),
278 extensions: None,
279 extended_agent_card: None,
280 },
281 default_input_modes: vec!["text/plain".to_owned(), "application/json".to_owned()],
282 default_output_modes: vec!["text/plain".to_owned()],
283 provider: None,
284 documentation_url: None,
285 icon_url: None,
286 security_schemes: None,
287 security_requirements: None,
288 signatures: None,
289 }
290}