Skip to main content

a2a_server/
lib.rs

1// Copyright AGNTCY Contributors (https://github.com/agntcy)
2// Copyright A2A Contributors (https://github.com/a2aproject)
3// SPDX-License-Identifier: Apache-2.0
4//! Server framework for implementing A2A v1 agents.
5//!
6//! Published as `a2a-server-lf` and imported as `a2a_server`. The protocol
7//! types come from the [`a2a`] crate.
8//!
9//! # How a request flows
10//!
11//! A protocol binding turns a wire request into a call on a
12//! [`RequestHandler`]. [`DefaultRequestHandler`] is the implementation most
13//! agents use: it manages the task lifecycle, saves tasks in a [`TaskStore`],
14//! and hands the work to your [`AgentExecutor`], which returns a stream of
15//! events.
16//!
17//! # Where to start
18//!
19//! 1. Implement [`AgentExecutor`] with the agent's logic. [`ExecutorContext`]
20//!    describes the request being served.
21//! 2. Build a [`DefaultRequestHandler`] from the executor and a
22//!    [`TaskStore`]. [`InMemoryTaskStore`] is provided.
23//! 3. Mount a binding on an axum router with [`jsonrpc::jsonrpc_router`] or
24//!    [`rest::rest_router`]. The gRPC and SLIMRPC bindings are in the
25//!    `a2a-grpc` and `a2a-slimrpc` crates.
26//! 4. Serve the agent card at [`WELL_KNOWN_AGENT_CARD_PATH`] with
27//!    [`agent_card::agent_card_router`], from a [`StaticAgentCard`] or your
28//!    own [`AgentCardProducer`].
29//!
30//! # Also in this crate
31//!
32//! - [`sse`]: streaming responses as server-sent events.
33//! - [`push`]: push notification configs ([`PushConfigStore`]) and their
34//!   delivery ([`HttpPushSender`]).
35//! - [`middleware`]: [`CallInterceptor`]s around a handler, applied with
36//!   [`InterceptedHandler`].
37//! - [`RequestAuthorizer`]: decides whether a request may proceed; set it
38//!   with [`DefaultRequestHandler::with_authorizer`].
39//! - [`pagination`]: the page limits the list endpoints share.
40//!
41//! # Feature flags
42//!
43//! - `rustls-tls` (default): rustls, with its default crypto provider, for
44//!   push notification delivery and for serving over HTTPS through the `tls`
45//!   module.
46//! - `rustls-no-provider`: the same, with the crypto provider installed by
47//!   the application.
48//! - `native-tls`: the platform's native TLS stack for push notification
49//!   delivery. The `tls` module is not available with this flag alone.
50//!
51//! `fuzzing` is for the fuzz targets in this repository, not for dependents.
52
53pub mod agent_card;
54pub mod executor;
55pub mod handler;
56pub mod jsonrpc;
57pub mod middleware;
58pub mod pagination;
59pub mod push;
60pub mod rest;
61pub mod sse;
62pub mod task_store;
63
64// Push-URL validation internals reached by the fuzz target in fuzz/ — see
65// #238. Thin wrappers, not re-exports: the originals stay crate-private.
66#[cfg(feature = "fuzzing")]
67#[doc(hidden)]
68pub mod fuzz_support {
69    use a2a::A2AError;
70
71    pub fn validate_push_url(url: &str) -> Result<(), A2AError> {
72        crate::push::sender::validate_push_url(url)
73    }
74
75    pub fn is_blocked_ip(ip: std::net::IpAddr) -> bool {
76        crate::push::sender::is_blocked_ip(ip)
77    }
78}
79
80#[cfg(any(feature = "rustls-tls", feature = "rustls-no-provider"))]
81pub mod tls;
82
83pub use agent_card::{AgentCardProducer, StaticAgentCard, WELL_KNOWN_AGENT_CARD_PATH};
84pub use executor::{AgentExecutor, ExecutorContext};
85pub use handler::{
86    DefaultRequestHandler, ExtendedAgentCardResolver, RequestAuthorizer, RequestHandler,
87};
88pub use middleware::{CallContext, CallInterceptor, InterceptedHandler, ServiceParams, User};
89pub use push::{HttpPushSender, HttpPushSenderConfig, InMemoryPushConfigStore, PushConfigStore};
90pub use task_store::{InMemoryTaskStore, TaskStore};
91
92/// Build an `INTERNAL_ERROR` whose client-visible message is generic, while
93/// the real cause is logged server-side (BUG-12 / CWE-209).
94///
95/// Call this where the **server itself** failed — a serialization fault, a
96/// broken invariant — and never at a response boundary. A2A gives an
97/// `AgentExecutor` no code other than `INTERNAL_ERROR` to report its own
98/// failure with (`error_code` has nothing between `INVALID_AGENT_RESPONSE`
99/// and the JSON-RPC generics), and `A2AError` carries no marker for where an
100/// error came from. Sanitizing by code at the boundary therefore cannot tell
101/// a serialization fault from an agent saying why it failed, and would
102/// replace both with "Internal error".
103pub(crate) fn sanitized_internal_error(detail: impl std::fmt::Display) -> a2a::A2AError {
104    tracing::error!(error = %detail, "internal error; returning a generic message to the client");
105    a2a::A2AError::internal("Internal error")
106}
107
108#[cfg(test)]
109pub(crate) mod test_util {
110    use std::collections::HashMap;
111    use std::sync::{Arc, Mutex};
112
113    use a2a::*;
114    use async_trait::async_trait;
115    use futures::stream::BoxStream;
116
117    use crate::handler::RequestHandler;
118    use crate::middleware::ServiceParams;
119
120    pub fn install_crypto_provider() {
121        #[cfg(feature = "rustls-tls")]
122        {
123            let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
124        }
125    }
126
127    pub(crate) type CapturedParams = Arc<Mutex<HashMap<&'static str, ServiceParams>>>;
128
129    /// `RequestHandler` stub that records the `ServiceParams` it sees per method.
130    ///
131    /// Used by transport-layer tests to assert that incoming request headers
132    /// are surfaced through to the `RequestHandler` boundary — which is exactly
133    /// what the HTTP / JSON-RPC transports are responsible for. Returns minimal
134    /// stub responses so tests don't depend on `DefaultRequestHandler` behavior.
135    pub(crate) struct CapturingHandler {
136        captured: CapturedParams,
137        tenants: Mutex<HashMap<&'static str, Option<String>>>,
138        ids: Mutex<HashMap<&'static str, String>>,
139    }
140
141    impl CapturingHandler {
142        pub fn new() -> (Arc<Self>, CapturedParams) {
143            let captured = Arc::new(Mutex::new(HashMap::new()));
144            let handler = Arc::new(CapturingHandler {
145                captured: captured.clone(),
146                tenants: Mutex::new(HashMap::new()),
147                ids: Mutex::new(HashMap::new()),
148            });
149            (handler, captured)
150        }
151
152        fn record(&self, method: &'static str, params: &ServiceParams, tenant: Option<&str>) {
153            self.captured.lock().unwrap().insert(method, params.clone());
154            self.tenants
155                .lock()
156                .unwrap()
157                .insert(method, tenant.map(str::to_owned));
158        }
159
160        /// The tenant of `method`'s last call; `None` if it was not called since.
161        pub fn take_tenant(&self, method: &str) -> Option<Option<String>> {
162            self.tenants.lock().unwrap().remove(method)
163        }
164
165        pub fn take_id(&self, method: &str) -> Option<String> {
166            self.ids.lock().unwrap().remove(method)
167        }
168    }
169
170    #[async_trait]
171    impl RequestHandler for CapturingHandler {
172        async fn send_message(
173            &self,
174            params: &ServiceParams,
175            req: SendMessageRequest,
176        ) -> Result<SendMessageResponse, A2AError> {
177            self.record("send_message", params, req.tenant.as_deref());
178            Err(A2AError::internal("stub"))
179        }
180
181        async fn send_streaming_message(
182            &self,
183            params: &ServiceParams,
184            req: SendMessageRequest,
185        ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError> {
186            self.record("send_streaming_message", params, req.tenant.as_deref());
187            Ok(Box::pin(futures::stream::empty()))
188        }
189
190        async fn get_task(
191            &self,
192            params: &ServiceParams,
193            req: GetTaskRequest,
194        ) -> Result<Task, A2AError> {
195            self.ids.lock().unwrap().insert("get_task", req.id.clone());
196            self.record("get_task", params, req.tenant.as_deref());
197            Err(A2AError::task_not_found("stub"))
198        }
199
200        async fn list_tasks(
201            &self,
202            params: &ServiceParams,
203            req: ListTasksRequest,
204        ) -> Result<ListTasksResponse, A2AError> {
205            self.record("list_tasks", params, req.tenant.as_deref());
206            Ok(ListTasksResponse {
207                tasks: Vec::new(),
208                next_page_token: String::new(),
209                page_size: 0,
210                total_size: 0,
211            })
212        }
213
214        async fn cancel_task(
215            &self,
216            params: &ServiceParams,
217            req: CancelTaskRequest,
218        ) -> Result<Task, A2AError> {
219            self.ids
220                .lock()
221                .unwrap()
222                .insert("cancel_task", req.id.clone());
223            self.record("cancel_task", params, req.tenant.as_deref());
224            Err(A2AError::task_not_found("stub"))
225        }
226
227        async fn subscribe_to_task(
228            &self,
229            params: &ServiceParams,
230            req: SubscribeToTaskRequest,
231        ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError> {
232            self.ids
233                .lock()
234                .unwrap()
235                .insert("subscribe_to_task", req.id.clone());
236            self.record("subscribe_to_task", params, req.tenant.as_deref());
237            Ok(Box::pin(futures::stream::empty()))
238        }
239
240        async fn create_push_config(
241            &self,
242            params: &ServiceParams,
243            req: TaskPushNotificationConfig,
244        ) -> Result<TaskPushNotificationConfig, A2AError> {
245            self.record("create_push_config", params, req.tenant.as_deref());
246            Ok(req)
247        }
248
249        async fn get_push_config(
250            &self,
251            params: &ServiceParams,
252            req: GetTaskPushNotificationConfigRequest,
253        ) -> Result<TaskPushNotificationConfig, A2AError> {
254            self.record("get_push_config", params, req.tenant.as_deref());
255            Err(A2AError::internal("stub"))
256        }
257
258        async fn list_push_configs(
259            &self,
260            params: &ServiceParams,
261            req: ListTaskPushNotificationConfigsRequest,
262        ) -> Result<ListTaskPushNotificationConfigsResponse, A2AError> {
263            self.record("list_push_configs", params, req.tenant.as_deref());
264            Ok(ListTaskPushNotificationConfigsResponse {
265                configs: Vec::new(),
266                next_page_token: None,
267            })
268        }
269
270        async fn delete_push_config(
271            &self,
272            params: &ServiceParams,
273            req: DeleteTaskPushNotificationConfigRequest,
274        ) -> Result<(), A2AError> {
275            self.record("delete_push_config", params, req.tenant.as_deref());
276            Ok(())
277        }
278
279        async fn get_extended_agent_card(
280            &self,
281            params: &ServiceParams,
282            req: GetExtendedAgentCardRequest,
283        ) -> Result<AgentCard, A2AError> {
284            self.record("get_extended_agent_card", params, req.tenant.as_deref());
285            Err(A2AError::internal("stub"))
286        }
287    }
288
289    /// Assert that `method` was called with a service-params entry matching `header = expected`.
290    #[track_caller]
291    pub(crate) fn assert_header_captured(
292        captured: &CapturedParams,
293        method: &'static str,
294        header: &str,
295        expected: &str,
296    ) {
297        let captured = captured.lock().unwrap();
298        let params = captured
299            .get(method)
300            .unwrap_or_else(|| panic!("{method} should have been called; captured={captured:?}"));
301        assert_eq!(
302            params.get(header),
303            Some(&vec![expected.to_string()]),
304            "{header} should be propagated to {method}; got {params:?}",
305        );
306    }
307}