Skip to main content

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, 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
23/// The path of the JSON-RPC binding under the server's base URL.
24pub const JSONRPC_PATH: &str = "/jsonrpc";
25/// The path of the HTTP+JSON binding under the server's base URL.
26pub const REST_PATH: &str = "/rest";
27
28/// A Rig agent served over A2A: its agent card, its task store, and the
29/// router [`into_router`](Self::into_router) builds from them.
30///
31/// The router serves the card at `/.well-known/agent-card.json`, the JSON-RPC
32/// binding at [`JSONRPC_PATH`] and the HTTP+JSON binding at [`REST_PATH`].
33/// Streaming is on; push notifications are off.
34///
35/// For peers still on A2A v0.3, the same agent is served under
36/// [`V03_PATH`](crate::V03_PATH): its v0.3 card at
37/// `/v03/.well-known/agent-card.json` and v0.3 JSON-RPC at `/v03`. Point a
38/// v0.3 client at `{url}/v03`.
39pub 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
48/// The largest request body a server reads by default: 2 MiB.
49pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;
50
51impl A2aServer {
52    /// Serve `agent` at `url`, the base URL clients reach this server at.
53    ///
54    /// The card takes the agent's name and description, lists both bindings
55    /// under `url`, accepts `text/plain` and `application/json` parts, and
56    /// declares one `chat` skill. Tasks live in an [`InMemoryTaskStore`].
57    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    /// Change the agent card, for example its skills, version or provider.
72    ///
73    /// The router serves the card as edited and refuses a part that declares
74    /// a media type outside its `default_input_modes`. The routes stay at
75    /// [`JSONRPC_PATH`] and [`REST_PATH`] whatever the card's interfaces say.
76    #[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    /// Remember at most `max` conversations; see [`A2aExecutor::max_contexts`].
83    #[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    /// Answer every task with a `T` as JSON; see [`A2aExecutor::typed`]. The
90    /// card then declares `application/json` output and, in each skill's
91    /// description, the JSON schema of `T`, for callers to know what comes back.
92    #[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    /// Keep conversations in a [`rig_memory`] store; see
117    /// [`A2aExecutor::history_store`].
118    #[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    /// How much of a conversation each request sends; see
128    /// [`A2aExecutor::history_window`].
129    #[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    /// Run at most `max` tasks at once; see [`A2aExecutor::max_concurrent_tasks`].
136    #[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    /// Stop runs longer than `max`; see [`A2aExecutor::max_run_duration`].
143    #[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    /// Refuse request bodies over `bytes` with HTTP 413. Defaults to
150    /// [`DEFAULT_MAX_REQUEST_BYTES`].
151    #[must_use]
152    pub fn max_request_bytes(mut self, bytes: usize) -> Self {
153        self.max_request_bytes = bytes;
154        self
155    }
156
157    /// Require `Authorization: Bearer <token>` on every call. The agent
158    /// cards stay public, as discovery needs them, and declare the scheme;
159    /// calls without the token get HTTP 401.
160    #[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    /// Keep tasks in `store` instead of in memory.
174    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    /// The agent card the router serves.
186    pub fn card(&self) -> &AgentCard {
187        &self.card
188    }
189
190    /// The Axum router serving the card and both bindings.
191    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            // At the body itself, so it holds whichever way a handler reads it.
210            .layer(tower_http::limit::RequestBodyLimitLayer::new(
211                self.max_request_bytes,
212            ));
213        // The cards are routed after the guard, so discovery needs no token.
214        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
223/// Answers 401 to a call without the expected `Authorization` header, or
224/// passes every call when no token is set.
225async 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
241/// Compares in time independent of where the strings differ.
242fn 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}