rig_a2a/server.rs
1//! The agent card and the Axum router that serve an agent over A2A.
2
3use std::sync::Arc;
4
5use a2a::{
6 AgentCapabilities, AgentCard, AgentExtension, AgentInterface, AgentSkill,
7 HttpAuthSecurityScheme, SecurityScheme, TRANSPORT_PROTOCOL_HTTP_JSON,
8 TRANSPORT_PROTOCOL_JSONRPC,
9};
10use a2a_server::agent_card::agent_card_router;
11use a2a_server::jsonrpc::jsonrpc_router;
12use a2a_server::rest::rest_router;
13use a2a_server::{
14 DefaultRequestHandler, InMemoryTaskStore, PushConfigStore, StaticAgentCard, TaskStore,
15};
16use axum::extract::{Request, State};
17use axum::http::uri::Authority;
18use axum::http::{HeaderName, HeaderValue, StatusCode, header};
19use axum::middleware::Next;
20use axum::response::{IntoResponse, Response};
21use rig_agent::Agent;
22use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
23
24use crate::A2aExecutor;
25use crate::push::{PushSettings, SharedTasks};
26use crate::v03::{self, V03_PATH};
27
28/// The path of the JSON-RPC binding under the server's base URL.
29pub const JSONRPC_PATH: &str = "/jsonrpc";
30/// The path of the HTTP+JSON binding under the server's base URL.
31pub const REST_PATH: &str = "/rest";
32
33/// A Rig agent served over A2A: its agent card, its task store, and the
34/// router [`into_router`](Self::into_router) builds from them.
35///
36/// The router serves the card at `/.well-known/agent-card.json`, the JSON-RPC
37/// binding at [`JSONRPC_PATH`] and the HTTP+JSON binding at [`REST_PATH`].
38/// Streaming is on. Push notifications are off unless
39/// [`push_notifications`](Self::push_notifications) turns them on.
40///
41/// For peers still on A2A v0.3, the same agent is served under
42/// [`V03_PATH`](crate::V03_PATH): its v0.3 card at
43/// `/v03/.well-known/agent-card.json` and v0.3 JSON-RPC at `/v03`. Point a
44/// v0.3 client at `{url}/v03`.
45pub struct A2aServer<S = InMemoryTaskStore> {
46 executor: A2aExecutor,
47 card: AgentCard,
48 store: S,
49 url: String,
50 bearer: Option<String>,
51 extended_card: Option<AgentCard>,
52 allowed_hosts: Option<Vec<String>>,
53 max_request_bytes: usize,
54 push: PushSettings,
55}
56
57/// The largest request body a server reads by default: 2 MiB.
58pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;
59
60impl A2aServer {
61 /// Serve `agent` at `url`, the base URL clients reach this server at.
62 ///
63 /// The card takes the agent's name and description, lists both bindings
64 /// under `url`, accepts `text/plain` and `application/json` parts, and
65 /// declares one `chat` skill. Tasks live in an [`InMemoryTaskStore`],
66 /// which keeps finished tasks without limit unless
67 /// [`terminal_task_limit`](Self::terminal_task_limit) is set.
68 pub fn new(agent: Agent, url: impl AsRef<str>) -> Self {
69 let url = url.as_ref().trim_end_matches('/').to_owned();
70 Self {
71 card: default_card(&agent, &url),
72 executor: A2aExecutor::new(agent),
73 store: InMemoryTaskStore::new(),
74 url,
75 bearer: None,
76 extended_card: None,
77 allowed_hosts: None,
78 max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
79 push: PushSettings::new(),
80 }
81 }
82
83 /// Keep at most `max` finished tasks in memory, purging the oldest
84 /// first. A purged task answers `GetTask` with `TaskNotFound`. Tasks
85 /// still running are never purged. A `max` of 0 is treated as 1.
86 ///
87 /// Off by default: a client may fetch a finished task long after it ended,
88 /// and a limit would change that answer. Set it for a server that runs
89 /// for long and takes many tasks.
90 ///
91 /// Caveats:
92 /// - A late status update for a purged task can bring it back. The
93 /// executor's save path falls back to `create` when `update` finds no
94 /// task (in `a2a-server-lf`, not in this crate), so a cancel or event
95 /// that arrives after the purge re-creates the task as a finished one,
96 /// where it can be purged again. Set the limit well above the number of
97 /// tasks in flight.
98 /// - Only the default in-memory store has this limit. Call it before
99 /// [`task_store`](Self::task_store) or the limit is dropped; for a
100 /// custom store, set its own limit instead.
101 #[must_use]
102 pub fn terminal_task_limit(mut self, max: usize) -> Self {
103 self.store = InMemoryTaskStore::new().with_terminal_task_limit(max.max(1));
104 self
105 }
106}
107
108impl<S: TaskStore> A2aServer<S> {
109 /// Change the agent card, for example its skills, version or provider.
110 ///
111 /// The router serves the card as edited and refuses a part that declares
112 /// a media type outside its `default_input_modes`. The routes stay at
113 /// [`JSONRPC_PATH`] and [`REST_PATH`] whatever the card's interfaces say.
114 #[must_use]
115 pub fn edit_card(mut self, edit: impl FnOnce(&mut AgentCard)) -> Self {
116 edit(&mut self.card);
117 self
118 }
119
120 /// Remember at most `max` conversations; see [`A2aExecutor::max_contexts`].
121 #[must_use]
122 #[doc(alias = "max_sessions")]
123 pub fn max_contexts(mut self, max: usize) -> Self {
124 self.executor = self.executor.max_contexts(max);
125 self
126 }
127
128 /// Answer every task with a `T` as JSON; see [`A2aExecutor::typed`]. The
129 /// card then declares `application/json` output and, in each skill's
130 /// description, the JSON schema of `T`, for callers to know what comes back.
131 #[must_use]
132 pub fn typed<T>(mut self) -> Self
133 where
134 T: schemars::JsonSchema
135 + serde::de::DeserializeOwned
136 + serde::Serialize
137 + WasmCompatSend
138 + WasmCompatSync
139 + 'static,
140 {
141 self.executor = self.executor.typed::<T>();
142 let schema = serde_json::to_string(&schemars::schema_for!(T)).unwrap_or_default();
143 let json = vec!["application/json".to_owned()];
144 self.card.default_output_modes = json.clone();
145 for skill in &mut self.card.skills {
146 skill.output_modes = Some(json.clone());
147 skill.description = format!(
148 "{} Answers with JSON matching this schema: {schema}",
149 skill.description
150 );
151 }
152 self
153 }
154
155 /// Keep conversations in a [`rig_memory`] store; see
156 /// [`A2aExecutor::history_store`].
157 #[must_use]
158 pub fn history_store<T>(mut self, store: T) -> Self
159 where
160 T: rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
161 {
162 self.executor = self.executor.history_store(store);
163 self
164 }
165
166 /// How much of a conversation each request sends; see
167 /// [`A2aExecutor::history_window`].
168 #[must_use]
169 pub fn history_window(mut self, window: impl rig_memory::recent::Recent + 'static) -> Self {
170 self.executor = self.executor.history_window(window);
171 self
172 }
173
174 /// Run at most `max` tasks at once; see [`A2aExecutor::max_concurrent_tasks`].
175 #[must_use]
176 pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
177 self.executor = self.executor.max_concurrent_tasks(max);
178 self
179 }
180
181 /// Stop runs longer than `max`; see [`A2aExecutor::max_run_duration`].
182 #[must_use]
183 pub fn max_run_duration(mut self, max: std::time::Duration) -> Self {
184 self.executor = self.executor.max_run_duration(max);
185 self
186 }
187
188 /// Answer only requests whose `Host` header names one of `hosts`, and
189 /// refuse the rest with HTTP 403 before any agent work. This guards a
190 /// local server against DNS rebinding, where a web page on another site
191 /// is pointed at `localhost`. Cards are checked too.
192 ///
193 /// An entry is a host name such as `agent.example.com`, which matches
194 /// any port, or `host:port`, which matches only that port. Host names
195 /// compare without case. An empty list refuses every request.
196 ///
197 /// Off by default: without this call the `Host` header is not checked.
198 #[must_use]
199 pub fn allowed_hosts<I, H>(mut self, hosts: I) -> Self
200 where
201 I: IntoIterator<Item = H>,
202 H: Into<String>,
203 {
204 self.allowed_hosts = Some(hosts.into_iter().map(Into::into).collect());
205 self
206 }
207
208 /// Refuse request bodies over `bytes` with HTTP 413. Defaults to
209 /// [`DEFAULT_MAX_REQUEST_BYTES`].
210 #[must_use]
211 pub fn max_request_bytes(mut self, bytes: usize) -> Self {
212 self.max_request_bytes = bytes;
213 self
214 }
215
216 /// Require `Authorization: Bearer <token>` on every call. The agent
217 /// cards stay public, as discovery needs them, and declare the scheme;
218 /// calls without the token get HTTP 401.
219 #[must_use]
220 pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
221 self.bearer = Some(token.into());
222 let scheme = SecurityScheme::HttpAuth(HttpAuthSecurityScheme {
223 scheme: "bearer".to_owned(),
224 description: None,
225 bearer_format: None,
226 });
227 self.card.security_schemes = Some([("bearer".to_owned(), scheme)].into());
228 self.card.security_requirements = Some(vec![[("bearer".to_owned(), vec![])].into()]);
229 self
230 }
231
232 /// Serve `card` as the authenticated extended agent card. Callers get it
233 /// with the bearer token, from `GetExtendedAgentCard` on the JSON-RPC
234 /// binding and from `/extendedAgentCard` on the HTTP+JSON binding. Without
235 /// the token they get HTTP 401, as for any other call. Off by default.
236 ///
237 /// The card is served as given, to every caller with the token. Put
238 /// only what that caller may see here. The public card stays as it is.
239 ///
240 /// Needs [`bearer_token`](Self::bearer_token), since the token is the only
241 /// check on who gets the card. Without one, the server logs an error when
242 /// it is built and keeps the extended card off: the public card omits
243 /// `capabilities.extendedAgentCard`, and the methods refuse the call. The
244 /// card is never served unauthenticated.
245 ///
246 /// The v0.3 surface has no extended card.
247 ///
248 /// The extended card is not exempt from [`extension`](Self::extension):
249 /// a `required` extension must be activated to read it, even with the
250 /// token. The SDK checks it on every method, and the card method cannot
251 /// be told apart without reading the JSON-RPC body.
252 #[must_use]
253 pub fn extended_card(mut self, card: AgentCard) -> Self {
254 self.extended_card = Some(card);
255 self
256 }
257
258 /// Declare an A2A extension in the card's `capabilities.extensions`.
259 ///
260 /// A client activates an extension with the `A2A-Extensions` header. The
261 /// SDK refuses a request that does not activate an extension the card
262 /// marks `required`, with `ExtensionSupportRequiredError`. The server
263 /// echoes the activated extensions it declares in the response's
264 /// `A2A-Extensions` header. A tool or hook in the agent run reads the
265 /// activated URIs with [`activated_extensions`](crate::activated_extensions).
266 ///
267 /// Adding a URI that is already declared is ignored. The first declaration
268 /// is kept, and the card keeps the order of the first declarations.
269 ///
270 /// Unset, the card omits `extensions`.
271 #[must_use]
272 pub fn extension(mut self, extension: AgentExtension) -> Self {
273 let declared = self
274 .card
275 .capabilities
276 .extensions
277 .get_or_insert_with(Vec::new);
278 if !declared.iter().any(|known| known.uri == extension.uri) {
279 declared.push(extension);
280 }
281 self
282 }
283
284 /// Accept push notification configs, so a client can ask the server to
285 /// POST task updates to a webhook. Off by default.
286 ///
287 /// Push needs [`bearer_token`](Self::bearer_token): without one, the
288 /// server logs an error when it is built and keeps push off, so the card
289 /// says `pushNotifications: false` and a config set is refused with
290 /// `PushNotificationNotSupported`. With push on, the card declares
291 /// `pushNotifications: true`.
292 ///
293 /// Configs are kept in memory unless [`push_config_store`](Self::push_config_store)
294 /// is set. At most 10 configs per task are accepted, and 10,000 in all
295 /// counted since the server started. When the total is reached, configs
296 /// of tasks that [`terminal_task_limit`](Self::terminal_task_limit) has
297 /// purged are dropped, so the total counts live tasks.
298 /// Each config is checked when it is saved: its URL must be `https`, on
299 /// the list from [`push_allowed_hosts`](Self::push_allowed_hosts) if one
300 /// is set, and not a literal IP in 100.64.0.0/10, 64:ff9b::/96, 2002::/16
301 /// or ::a.b.c.d/96.
302 ///
303 /// The SDK's address guard runs when a webhook is called. It refuses
304 /// 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16,
305 /// 224.0.0.0/4, 0.0.0.0, ::1, ::, fc00::/7, fe80::/10, ff00::/8, the
306 /// IPv4-mapped forms of those IPv4 ranges, and the hosts `localhost`,
307 /// `metadata.google.internal` and `metadata.azure.com`. It checks the
308 /// address a name resolves to, and each redirect. It does not cover the
309 /// ranges listed above, so a name resolving to them is not refused.
310 /// Redirects are followed only to hosts that pass the same check.
311 ///
312 /// # Security
313 ///
314 /// - A webhook URL comes from the client. An open server with push on
315 /// lets any caller make it POST to any host the guard allows. Set an
316 /// allowlist when clients are not trusted.
317 /// - The server signs nothing: there is no JWT or JWKS. It forwards the
318 /// client's `token` as the `A2A-Notification-Token` header and its
319 /// `authentication` credentials as `Authorization`. A receiver must
320 /// check both itself.
321 /// - Each POST carries the full task update, including the agent's
322 /// output and any artifacts.
323 /// - Anyone who holds a task id can attach a webhook to it, and so
324 /// receive that task's updates. Push requires a bearer token for this
325 /// reason, and the bearer token is the only check on who may do so.
326 /// - A slow webhook delays the task. Delivery runs in the task's event
327 /// loop, one config at a time, and each POST has a 5 second timeout. A
328 /// task with 10 configs whose receivers all stall can take up to 50
329 /// seconds per update, and the client's stream waits for it.
330 /// - A finished task's configs stay until the total cap is reached. Set
331 /// [`terminal_task_limit`](Self::terminal_task_limit) too: then the
332 /// oldest finished tasks are purged, and their configs are dropped at
333 /// the next save that reaches the total cap.
334 ///
335 /// ```ignore
336 /// let server = A2aServer::new(agent, "https://agent.example.com")
337 /// .bearer_token(token)
338 /// .push_notifications(true)
339 /// .push_allowed_hosts(["hooks.example.com"])
340 /// .terminal_task_limit(1_000);
341 /// ```
342 #[must_use]
343 pub fn push_notifications(mut self, enabled: bool) -> Self {
344 self.push.enabled = enabled;
345 self.card.capabilities.push_notifications = Some(enabled);
346 self
347 }
348
349 /// Keep push configs in `store` instead of in memory. Also turns push
350 /// notifications on, as [`push_notifications(true)`](Self::push_notifications)
351 /// does. Every config still goes through the URL checks and the caps.
352 #[must_use]
353 pub fn push_config_store<P: PushConfigStore>(mut self, store: P) -> Self {
354 self.push.store = Some(Arc::new(store));
355 self.push_notifications(true)
356 }
357
358 /// Accept webhook URLs only on these hosts, compared without regard to
359 /// case. A config naming another host is refused when it is saved. Takes
360 /// effect only while push notifications are on.
361 #[must_use]
362 pub fn push_allowed_hosts<I, H>(mut self, hosts: I) -> Self
363 where
364 I: IntoIterator<Item = H>,
365 H: Into<String>,
366 {
367 self.push.allowed_hosts = Some(hosts.into_iter().map(Into::into).collect());
368 self
369 }
370
371 /// Drop the checks that keep a webhook URL from reaching a private
372 /// target: the `https` requirement, the refusal on save of the literal
373 /// ranges 100.64.0.0/10, 64:ff9b::/96, 2002::/16 and ::a.b.c.d/96, and
374 /// the SDK's address guard (loopback, private and link-local addresses,
375 /// DNS and redirects). Also lets the SDK send webhooks through the
376 /// proxies named in the environment. For tests against a webhook on this
377 /// machine only. The host allowlist still applies.
378 #[must_use]
379 pub fn allow_unguarded_push_urls(mut self) -> Self {
380 self.push.allow_unguarded = true;
381 self
382 }
383
384 /// Keep tasks in `store` instead of in memory.
385 ///
386 /// This replaces the default store, and with it any limit set by
387 /// [`terminal_task_limit`](A2aServer::terminal_task_limit) called before
388 /// it: that limit is dropped. Set the limit on `store` itself, for
389 /// example with `InMemoryTaskStore::with_terminal_task_limit`.
390 pub fn task_store<T: TaskStore>(self, store: T) -> A2aServer<T> {
391 A2aServer {
392 executor: self.executor,
393 card: self.card,
394 store,
395 url: self.url,
396 bearer: self.bearer,
397 extended_card: self.extended_card,
398 allowed_hosts: self.allowed_hosts,
399 max_request_bytes: self.max_request_bytes,
400 push: self.push,
401 }
402 }
403
404 /// The agent card the router serves.
405 pub fn card(&self) -> &AgentCard {
406 &self.card
407 }
408
409 /// The Axum router serving the card and both bindings.
410 pub fn into_router(self) -> axum::Router {
411 let mut card = self.card;
412 // Push needs a bearer token; without one it stays off and the card says so.
413 let push_on = self.push.enabled && self.bearer.is_some();
414 if self.push.enabled && !push_on {
415 tracing::error!(
416 "push notifications need a bearer_token on the A2aServer; push stays off"
417 );
418 }
419 card.capabilities.push_notifications = Some(push_on);
420 // The extended card needs a bearer token too; without one it stays off.
421 let configured = self.extended_card.is_some();
422 let extended = self.extended_card.filter(|_| self.bearer.is_some());
423 if configured && extended.is_none() {
424 tracing::error!(
425 "an extended agent card needs a bearer_token on the A2aServer; the extended card stays off"
426 );
427 }
428 card.capabilities.extended_agent_card = extended.as_ref().map(|_| true);
429 // The handler and the push wrapper read one task store: the wrapper
430 // needs it to tell live tasks from purged ones.
431 let tasks: Arc<dyn TaskStore> = Arc::new(self.store);
432 let declared: Arc<[String]> = card
433 .capabilities
434 .extensions
435 .iter()
436 .flatten()
437 .map(|extension| extension.uri.clone())
438 .collect();
439 let mut handler = DefaultRequestHandler::new(
440 self.executor.declaring(Arc::clone(&declared)),
441 SharedTasks(Arc::clone(&tasks)),
442 )
443 .with_capabilities(card.capabilities.clone())
444 .with_default_input_modes(card.default_input_modes.clone());
445 if let Some(extended) = extended {
446 handler = handler.with_extended_agent_card(extended);
447 }
448 if push_on {
449 handler = handler.with_push_notifications(
450 self.push.checked_store(Arc::clone(&tasks)),
451 self.push.sender(),
452 );
453 }
454 let handler = Arc::new(handler);
455 let v03_card = v03::card(
456 &card,
457 &format!("{}{V03_PATH}", self.url),
458 self.bearer.is_some(),
459 );
460 let expected: Option<Arc<str>> = self.bearer.map(|token| format!("Bearer {token}").into());
461 let auth = axum::middleware::from_fn_with_state(expected, guard);
462 // The echo sits inside the guard, so a 401 from it is never echoed.
463 let calls = axum::Router::new()
464 .nest(JSONRPC_PATH, jsonrpc_router(Arc::clone(&handler)))
465 .nest(REST_PATH, rest_router(Arc::clone(&handler)))
466 .nest(V03_PATH, v03::router(handler, Arc::clone(&declared)))
467 .layer(axum::middleware::from_fn_with_state(
468 Arc::clone(&declared),
469 echo_extensions,
470 ))
471 .route_layer(auth)
472 // At the body itself, so it holds whichever way a handler reads it.
473 .layer(tower_http::limit::RequestBodyLimitLayer::new(
474 self.max_request_bytes,
475 ));
476 // The cards are routed after the guard, so discovery needs no token.
477 let cards = agent_card_router(Arc::new(StaticAgentCard::new(card)))
478 .route(
479 &format!("{V03_PATH}{}", a2a_server::WELL_KNOWN_AGENT_CARD_PATH),
480 axum::routing::get(move || async move { axum::Json(v03_card) }),
481 )
482 .layer(axum::middleware::from_fn_with_state(
483 declared,
484 echo_extensions,
485 ));
486 // Outermost, so a refused request never reaches an agent or a card.
487 let host_guard = self.allowed_hosts.map(Arc::new);
488 calls
489 .merge(cards)
490 .layer(axum::middleware::from_fn_with_state(host_guard, check_host))
491 }
492}
493
494/// The header that carries activated extensions on the v1.0 surface, in both directions.
495pub(crate) const EXTENSIONS_HEADER: HeaderName = HeaderName::from_static("a2a-extensions");
496
497/// The header that carries activated extensions on the v0.3 surface, in both directions.
498pub(crate) const V03_EXTENSIONS_HEADER: HeaderName = HeaderName::from_static("x-a2a-extensions");
499
500/// The URIs in `name` that a request activates and the card declares, sorted and
501/// without repeats. The header may hold several values, each comma-separated.
502pub(crate) fn activated_extensions(
503 headers: &axum::http::HeaderMap,
504 name: &HeaderName,
505 declared: &[String],
506) -> Vec<String> {
507 activated_in(
508 headers
509 .get_all(name)
510 .iter()
511 .filter_map(|value| value.to_str().ok()),
512 declared,
513 )
514}
515
516/// The URIs in the header `values` (each comma-separated) that `declared` holds,
517/// sorted and without repeats. The HTTP surfaces and the executor both read
518/// activation through this, so they cannot drift apart.
519pub(crate) fn activated_in<'a>(
520 values: impl IntoIterator<Item = &'a str>,
521 declared: &[String],
522) -> Vec<String> {
523 let mut activated: Vec<String> = values
524 .into_iter()
525 .flat_map(|value| value.split(','))
526 .map(str::trim)
527 .filter(|uri| declared.iter().any(|d| d.as_str() == *uri))
528 .map(str::to_owned)
529 .collect();
530 activated.sort_unstable();
531 activated.dedup();
532 activated
533}
534
535/// Echoes, in the `A2A-Extensions` response header, the activated extensions
536/// the card declares. Passes every request through when none are declared.
537/// Placed inside the bearer guard and the body limit, so a refusal by either
538/// carries no echo.
539async fn echo_extensions(
540 State(declared): State<Arc<[String]>>,
541 request: Request,
542 next: Next,
543) -> Response {
544 if declared.is_empty() {
545 return next.run(request).await;
546 }
547 let activated = activated_extensions(request.headers(), &EXTENSIONS_HEADER, &declared);
548 let mut response = next.run(request).await;
549 if let Ok(value) = HeaderValue::from_str(&activated.join(", "))
550 && !activated.is_empty()
551 {
552 response.headers_mut().insert(EXTENSIONS_HEADER, value);
553 }
554 response
555}
556
557/// Answers 403 when `Host` is not one of the allowed hosts, or passes every
558/// request when no list is set.
559async fn check_host(
560 State(allowed): State<Option<Arc<Vec<String>>>>,
561 request: Request,
562 next: Next,
563) -> Response {
564 let Some(allowed) = allowed else {
565 return next.run(request).await;
566 };
567 let given = request
568 .headers()
569 .get(header::HOST)
570 .and_then(|value| value.to_str().ok());
571 if host_allowed(&allowed, given) {
572 next.run(request).await
573 } else {
574 (
575 StatusCode::FORBIDDEN,
576 [(header::CONTENT_TYPE, "application/json")],
577 r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Host not allowed"}}"#,
578 )
579 .into_response()
580 }
581}
582
583/// Matches a `Host` value against the list the way rmcp does for MCP: the
584/// host compares without case or brackets, and an entry without a port
585/// matches any port.
586fn host_allowed(allowed: &[String], given: Option<&str>) -> bool {
587 let Some(given) = given.and_then(|value| Authority::try_from(value.trim()).ok()) else {
588 return false;
589 };
590 let host = normalize_host(given.host());
591 let port = given.port_u16();
592 allowed.iter().any(|entry| {
593 let entry = entry.trim();
594 let (entry_host, entry_port) = match Authority::try_from(entry) {
595 Ok(authority) => (normalize_host(authority.host()), authority.port_u16()),
596 Err(_) => (normalize_host(entry), None),
597 };
598 entry_host == host && entry_port.is_none_or(|entry_port| port == Some(entry_port))
599 })
600}
601
602fn normalize_host(host: &str) -> String {
603 host.trim_matches(['[', ']']).to_ascii_lowercase()
604}
605
606/// Answers 401 to a call without the expected `Authorization` header, or
607/// passes every call when no token is set.
608async fn guard(State(expected): State<Option<Arc<str>>>, request: Request, next: Next) -> Response {
609 let given = request
610 .headers()
611 .get(header::AUTHORIZATION)
612 .and_then(|value| value.to_str().ok());
613 match (expected.as_deref(), given) {
614 (None, _) => next.run(request).await,
615 (Some(expected), Some(given)) if same(expected, given) => next.run(request).await,
616 _ => (
617 StatusCode::UNAUTHORIZED,
618 [(header::WWW_AUTHENTICATE, "Bearer")],
619 )
620 .into_response(),
621 }
622}
623
624/// Compares in time independent of where the strings differ.
625fn same(a: &str, b: &str) -> bool {
626 a.len() == b.len()
627 && a.bytes()
628 .zip(b.bytes())
629 .fold(0, |acc, (x, y)| acc | (x ^ y))
630 == 0
631}
632
633fn default_card(agent: &Agent, url: &str) -> AgentCard {
634 let url = url.trim_end_matches('/');
635 let name = agent.name().unwrap_or("Rig agent").to_owned();
636 let description = agent
637 .description()
638 .unwrap_or("An agent built with Rig.")
639 .to_owned();
640 AgentCard {
641 skills: vec![AgentSkill {
642 id: "chat".to_owned(),
643 name: name.clone(),
644 description: description.clone(),
645 tags: vec!["chat".to_owned()],
646 examples: None,
647 input_modes: None,
648 output_modes: None,
649 security_requirements: None,
650 }],
651 name,
652 description,
653 version: "1.0.0".to_owned(),
654 supported_interfaces: vec![
655 AgentInterface::new(format!("{url}{JSONRPC_PATH}"), TRANSPORT_PROTOCOL_JSONRPC),
656 AgentInterface::new(format!("{url}{REST_PATH}"), TRANSPORT_PROTOCOL_HTTP_JSON),
657 ],
658 capabilities: AgentCapabilities {
659 streaming: Some(true),
660 push_notifications: Some(false),
661 extensions: None,
662 extended_agent_card: None,
663 },
664 default_input_modes: vec!["text/plain".to_owned(), "application/json".to_owned()],
665 default_output_modes: vec!["text/plain".to_owned()],
666 provider: None,
667 documentation_url: None,
668 icon_url: None,
669 security_schemes: None,
670 security_requirements: None,
671 signatures: None,
672 }
673}