Skip to main content

adk_server/a2a/
convenience.rs

1//! Convenience API for quickly starting an A2A-capable server.
2//!
3//! This module provides [`A2aServer`], a high-level wrapper that hides the
4//! complexity of wiring up A2A routes, agent cards, and session services.
5//!
6//! # Quick Start
7//!
8//! ```rust,ignore
9//! use adk_server::a2a::convenience::A2aServer;
10//! use std::sync::Arc;
11//!
12//! let agent: Arc<dyn adk_core::Agent> = /* your agent */;
13//! let app = A2aServer::quick_start(agent);
14//! // Serve with axum::serve(listener, app).await
15//! ```
16//!
17//! # Builder
18//!
19//! ```rust,ignore
20//! use adk_server::a2a::convenience::A2aServer;
21//! use std::sync::Arc;
22//!
23//! let server = A2aServer::builder()
24//!     .agent(my_agent)
25//!     .bind_addr("0.0.0.0:9090")
26//!     .agent_card_name("My Agent")
27//!     .streaming(true)
28//!     .build()?;
29//!
30//! server.serve().await?;
31//! ```
32
33use std::sync::Arc;
34
35use adk_core::{AdkError, Agent, ErrorCategory, ErrorComponent, SingleAgentLoader};
36use adk_session::{InMemorySessionService, SessionService};
37use axum::Router;
38
39use crate::a2a::types::{AgentCapabilities, AgentCard};
40use crate::config::{SecurityConfig, ServerConfig};
41use crate::rest::{ServerBuilder, create_app_with_a2a};
42
43/// Convenience wrapper for quickly starting an A2A-capable server.
44///
45/// Provides two entry points:
46/// - [`A2aServer::quick_start`] for zero-config usage
47/// - [`A2aServer::builder`] for custom configuration
48///
49/// # Example
50///
51/// ```rust,ignore
52/// use adk_server::a2a::convenience::A2aServer;
53/// use std::sync::Arc;
54///
55/// let app = A2aServer::quick_start(my_agent);
56/// let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
57/// axum::serve(listener, app).await?;
58/// ```
59pub struct A2aServer;
60
61impl A2aServer {
62    /// Create an A2A-ready Axum app with sensible defaults.
63    ///
64    /// Uses an in-memory session service, binds to `http://localhost:8080`,
65    /// enables streaming, and auto-generates the agent card from agent metadata.
66    ///
67    /// # Arguments
68    ///
69    /// * `agent` - The agent to expose via A2A protocol
70    ///
71    /// # Example
72    ///
73    /// ```rust,ignore
74    /// use adk_server::a2a::convenience::A2aServer;
75    /// use std::sync::Arc;
76    ///
77    /// let app = A2aServer::quick_start(my_agent);
78    /// let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
79    /// axum::serve(listener, app).await?;
80    /// ```
81    pub fn quick_start(agent: Arc<dyn Agent>) -> Router {
82        let base_url = "http://localhost:8080";
83        let session_service: Arc<dyn SessionService> = Arc::new(InMemorySessionService::new());
84        let agent_loader = Arc::new(SingleAgentLoader::new(agent));
85
86        let config = ServerConfig::new(agent_loader, session_service);
87        create_app_with_a2a(config, Some(base_url))
88    }
89
90    /// Create a builder for custom A2A server configuration.
91    ///
92    /// # Example
93    ///
94    /// ```rust,ignore
95    /// use adk_server::a2a::convenience::A2aServer;
96    /// use std::sync::Arc;
97    ///
98    /// let server = A2aServer::builder()
99    ///     .agent(my_agent)
100    ///     .bind_addr("0.0.0.0:9090")
101    ///     .streaming(false)
102    ///     .build()?;
103    ///
104    /// server.serve().await?;
105    /// ```
106    pub fn builder() -> A2aServerBuilder {
107        A2aServerBuilder::default()
108    }
109}
110
111/// Builder for configuring an A2A server with custom settings.
112///
113/// Allows customization of the agent card metadata, session service,
114/// bind address, and capabilities before building the server app.
115///
116/// # Defaults
117///
118/// - Session service: [`InMemorySessionService`]
119/// - Bind address: `127.0.0.1:8080` (loopback; call `bind_addr` to expose it)
120/// - Agent card name: from `agent.name()`
121/// - Agent card description: from `agent.description()`
122/// - Agent card version: `"1.0.0"`
123/// - Agent card URL: `http://localhost:8080`
124/// - Streaming: enabled
125/// - Push notifications: disabled
126pub struct A2aServerBuilder {
127    agent: Option<Arc<dyn Agent>>,
128    session_service: Option<Arc<dyn SessionService>>,
129    bind_addr: String,
130    agent_card_name: Option<String>,
131    agent_card_description: Option<String>,
132    agent_card_version: Option<String>,
133    agent_card_url: Option<String>,
134    streaming_enabled: bool,
135    push_notifications_enabled: bool,
136    skill_index: Option<Arc<adk_skill::SkillIndex>>,
137    security: Option<SecurityConfig>,
138}
139
140impl Default for A2aServerBuilder {
141    fn default() -> Self {
142        Self {
143            agent: None,
144            session_service: None,
145            // Loopback, not every interface. An A2A server executes agent and tool work, so
146            // exposing it beyond this host is a decision the operator should make explicitly
147            // — the previous default published it to the network on `build()`.
148            bind_addr: "127.0.0.1:8080".to_string(),
149            agent_card_name: None,
150            agent_card_description: None,
151            agent_card_version: None,
152            agent_card_url: None,
153            streaming_enabled: true,
154            push_notifications_enabled: false,
155            skill_index: None,
156            security: None,
157        }
158    }
159}
160
161impl A2aServerBuilder {
162    /// Set the agent to expose via A2A protocol.
163    ///
164    /// This is required — the builder will return an error if no agent is set.
165    pub fn agent(mut self, agent: Arc<dyn Agent>) -> Self {
166        self.agent = Some(agent);
167        self
168    }
169
170    /// Set a custom session service implementation.
171    ///
172    /// Defaults to [`InMemorySessionService`] if not specified.
173    pub fn session_service(mut self, service: Arc<dyn SessionService>) -> Self {
174        self.session_service = Some(service);
175        self
176    }
177
178    /// Set the bind address for the server.
179    ///
180    /// Defaults to `"127.0.0.1:8080"` (loopback only). Pass `"0.0.0.0:8080"` to
181    /// accept connections on every interface; the server then answers IP addresses,
182    /// `localhost`, and the host of the agent card URL, plus any host listed in
183    /// [`SecurityConfig::allowed_hosts`](crate::SecurityConfig::allowed_hosts) via
184    /// [`security_config`](Self::security_config).
185    pub fn bind_addr(mut self, addr: impl Into<String>) -> Self {
186        self.bind_addr = addr.into();
187        self
188    }
189
190    /// Override the agent card name.
191    ///
192    /// Defaults to `agent.name()`.
193    pub fn agent_card_name(mut self, name: impl Into<String>) -> Self {
194        self.agent_card_name = Some(name.into());
195        self
196    }
197
198    /// Override the agent card description.
199    ///
200    /// Defaults to `agent.description()`.
201    pub fn agent_card_description(mut self, desc: impl Into<String>) -> Self {
202        self.agent_card_description = Some(desc.into());
203        self
204    }
205
206    /// Override the agent card version.
207    ///
208    /// Defaults to `"1.0.0"`.
209    pub fn agent_card_version(mut self, version: impl Into<String>) -> Self {
210        self.agent_card_version = Some(version.into());
211        self
212    }
213
214    /// Override the agent card URL.
215    ///
216    /// Defaults to `"http://localhost:8080"`.
217    pub fn agent_card_url(mut self, url: impl Into<String>) -> Self {
218        self.agent_card_url = Some(url.into());
219        self
220    }
221
222    /// Enable or disable streaming support.
223    ///
224    /// Defaults to `true`.
225    pub fn streaming(mut self, enabled: bool) -> Self {
226        self.streaming_enabled = enabled;
227        self
228    }
229
230    /// Enable or disable push notifications.
231    ///
232    /// Defaults to `false`.
233    pub fn push_notifications(mut self, enabled: bool) -> Self {
234        self.push_notifications_enabled = enabled;
235        self
236    }
237
238    /// Expose the skills in `skill_index` on the served agent card.
239    ///
240    /// The served agent card appends one `skills[]` entry per
241    /// indexed skill, mapped by
242    /// [`agent_skills_from_index`](crate::a2a::agent_skills_from_index).
243    ///
244    /// # Example
245    ///
246    /// ```rust,ignore
247    /// use std::sync::Arc;
248    ///
249    /// let index = adk_skill::load_skill_index(".")?;
250    /// let server = A2aServer::builder()
251    ///     .agent(my_agent)
252    ///     .skill_index(Arc::new(index))
253    ///     .build()?;
254    /// ```
255    pub fn skill_index(mut self, skill_index: Arc<adk_skill::SkillIndex>) -> Self {
256        self.skill_index = Some(skill_index);
257        self
258    }
259
260    /// Set the server's CORS, host, body-size, and timeout settings.
261    ///
262    /// Defaults to [`SecurityConfig::default`]: no cross-origin access, and only
263    /// loopback names, IP addresses, and the agent card URL's host are answered.
264    ///
265    /// # Example
266    ///
267    /// ```rust,ignore
268    /// use adk_server::SecurityConfig;
269    ///
270    /// let server = A2aServer::builder()
271    ///     .agent(my_agent)
272    ///     .bind_addr("0.0.0.0:8080")
273    ///     .agent_card_url("https://agents.example.com")
274    ///     .security_config(SecurityConfig::default().with_allowed_hosts(["agents.internal"]))
275    ///     .build()?;
276    /// ```
277    pub fn security_config(mut self, security: SecurityConfig) -> Self {
278        self.security = Some(security);
279        self
280    }
281
282    /// Build the configured A2A server application.
283    ///
284    /// # Errors
285    ///
286    /// Returns an error if:
287    /// - No agent was provided (call `.agent(my_agent)`)
288    /// - The agent has an empty name
289    ///
290    /// # Example
291    ///
292    /// ```rust,ignore
293    /// let server = A2aServer::builder()
294    ///     .agent(my_agent)
295    ///     .build()?;
296    /// ```
297    pub fn build(self) -> Result<A2aServerApp, AdkError> {
298        let agent = self.agent.ok_or_else(|| {
299            AdkError::new(
300                ErrorComponent::Server,
301                ErrorCategory::InvalidInput,
302                "server.a2a.missing_agent",
303                "A2aServer requires an agent. Call .agent(my_agent) on the builder.",
304            )
305        })?;
306
307        if agent.name().is_empty() {
308            return Err(AdkError::new(
309                ErrorComponent::Server,
310                ErrorCategory::InvalidInput,
311                "server.a2a.missing_agent_name",
312                "A2A server requires an agent with a non-empty name. Set a name via LlmAgentBuilder::new(\"my-agent\")",
313            ));
314        }
315
316        let session_service: Arc<dyn SessionService> =
317            self.session_service.unwrap_or_else(|| Arc::new(InMemorySessionService::new()));
318
319        let base_url = self
320            .agent_card_url
321            .unwrap_or_else(|| format!("http://localhost:{}", extract_port(&self.bind_addr)));
322
323        let agent_loader = Arc::new(SingleAgentLoader::new(agent.clone()));
324        let mut config = ServerConfig::new(agent_loader, session_service);
325        if let Some(security) = self.security {
326            config = config.with_security(security);
327        }
328
329        // Build a custom agent card if any overrides were specified
330        let _agent_card = build_custom_agent_card(
331            agent.as_ref(),
332            &base_url,
333            self.agent_card_name,
334            self.agent_card_description,
335            self.agent_card_version,
336            self.streaming_enabled,
337            self.push_notifications_enabled,
338        );
339
340        let router = match self.skill_index {
341            // `ServerBuilder` with only A2A enabled builds the same router as
342            // `create_app_with_a2a`, and is the wiring path for indexed skills.
343            Some(skill_index) => {
344                ServerBuilder::new(config).with_a2a(&base_url).with_skill_index(skill_index).build()
345            }
346            None => create_app_with_a2a(config, Some(&base_url)),
347        };
348
349        Ok(A2aServerApp { router, bind_addr: self.bind_addr })
350    }
351}
352
353/// A configured A2A server application ready to serve.
354///
355/// Created via [`A2aServerBuilder::build`]. Provides access to the
356/// underlying Axum router and a convenience [`serve`](A2aServerApp::serve)
357/// method for binding and listening.
358pub struct A2aServerApp {
359    router: Router,
360    bind_addr: String,
361}
362
363impl std::fmt::Debug for A2aServerApp {
364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365        f.debug_struct("A2aServerApp").field("bind_addr", &self.bind_addr).finish_non_exhaustive()
366    }
367}
368
369impl A2aServerApp {
370    /// Consume the app and return the underlying Axum router.
371    ///
372    /// Use this when you need to compose the A2A routes with other
373    /// Axum routers or middleware.
374    pub fn into_router(self) -> Router {
375        self.router
376    }
377
378    /// Get the configured bind address.
379    pub fn bind_addr(&self) -> &str {
380        &self.bind_addr
381    }
382
383    /// Start serving the A2A application.
384    ///
385    /// Binds to the configured address and serves until the process is
386    /// terminated.
387    ///
388    /// # Errors
389    ///
390    /// Returns an error if the port is already in use or binding fails.
391    ///
392    /// # Example
393    ///
394    /// ```rust,ignore
395    /// let server = A2aServer::builder()
396    ///     .agent(my_agent)
397    ///     .build()?;
398    ///
399    /// server.serve().await?;
400    /// ```
401    pub async fn serve(self) -> Result<(), AdkError> {
402        let listener =
403            tokio::net::TcpListener::bind(&self.bind_addr).await.map_err(|e| {
404                let port = extract_port(&self.bind_addr);
405                let alt_port = port + 1;
406                AdkError::new(
407                    ErrorComponent::Server,
408                    ErrorCategory::Unavailable,
409                    "server.a2a.port_in_use",
410                    format!(
411                        "Port {port} is already in use. Try a different port with .bind_addr(\"127.0.0.1:{alt_port}\")"
412                    ),
413                )
414                .with_source(e)
415            })?;
416
417        axum::serve(listener, self.router).await.map_err(|e| {
418            AdkError::new(
419                ErrorComponent::Server,
420                ErrorCategory::Internal,
421                "server.a2a.serve_failed",
422                format!("A2A server encountered an error: {e}"),
423            )
424            .with_source(e)
425        })
426    }
427}
428
429/// Build a custom agent card with optional overrides.
430fn build_custom_agent_card(
431    agent: &dyn Agent,
432    base_url: &str,
433    name_override: Option<String>,
434    description_override: Option<String>,
435    version_override: Option<String>,
436    streaming: bool,
437    push_notifications: bool,
438) -> AgentCard {
439    let name = name_override.unwrap_or_else(|| agent.name().to_string());
440    let description = description_override.unwrap_or_else(|| agent.description().to_string());
441    let version = version_override.unwrap_or_else(|| "1.0.0".to_string());
442
443    let skills = crate::a2a::agent_card::build_agent_skills(agent);
444
445    AgentCard::builder()
446        .name(name)
447        .description(description)
448        .url(base_url.to_string())
449        .version(version)
450        .capabilities(AgentCapabilities {
451            streaming,
452            push_notifications,
453            state_transition_history: true,
454            extensions: None,
455        })
456        .skills(skills)
457        .build()
458        .expect("build_custom_agent_card: name, description, and url must be non-empty")
459}
460
461/// Extract the port number from a bind address string.
462///
463/// Handles formats like `"0.0.0.0:8080"`, `":8080"`, or `"8080"`.
464fn extract_port(addr: &str) -> u16 {
465    addr.rsplit(':').next().and_then(|p| p.parse().ok()).unwrap_or(8080)
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use adk_core::{Agent, EventStream, InvocationContext, Result as AdkResult};
472    use async_trait::async_trait;
473    use futures::stream;
474
475    struct TestAgent {
476        name: String,
477        description: String,
478    }
479
480    impl TestAgent {
481        fn new(name: &str, description: &str) -> Self {
482            Self { name: name.to_string(), description: description.to_string() }
483        }
484    }
485
486    #[async_trait]
487    impl Agent for TestAgent {
488        fn name(&self) -> &str {
489            &self.name
490        }
491
492        fn description(&self) -> &str {
493            &self.description
494        }
495
496        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
497            &[]
498        }
499
500        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> AdkResult<EventStream> {
501            Ok(Box::pin(stream::empty()))
502        }
503    }
504
505    #[test]
506    fn test_quick_start_returns_router() {
507        let agent: Arc<dyn Agent> = Arc::new(TestAgent::new("test-agent", "A test agent"));
508        let _router = A2aServer::quick_start(agent);
509    }
510
511    #[test]
512    fn test_builder_defaults() {
513        let builder = A2aServer::builder();
514        // Loopback, deliberately. An A2A server runs agent and tool work, so publishing it
515        // to every interface is an explicit `bind_addr` call, not a default.
516        assert_eq!(builder.bind_addr, "127.0.0.1:8080");
517        assert!(builder.streaming_enabled);
518        assert!(!builder.push_notifications_enabled);
519        assert!(builder.agent.is_none());
520        assert!(builder.session_service.is_none());
521        assert!(builder.agent_card_name.is_none());
522        assert!(builder.agent_card_description.is_none());
523        assert!(builder.agent_card_version.is_none());
524        assert!(builder.agent_card_url.is_none());
525    }
526
527    #[test]
528    fn test_builder_missing_agent_error() {
529        let result = A2aServer::builder().build();
530        assert!(result.is_err());
531        let err = result.unwrap_err();
532        assert_eq!(err.code, "server.a2a.missing_agent");
533        assert!(err.message.contains("agent"));
534    }
535
536    #[test]
537    fn test_builder_empty_agent_name_error() {
538        let agent: Arc<dyn Agent> = Arc::new(TestAgent::new("", "A test agent"));
539        let result = A2aServer::builder().agent(agent).build();
540        assert!(result.is_err());
541        let err = result.unwrap_err();
542        assert_eq!(err.code, "server.a2a.missing_agent_name");
543        assert!(err.message.contains("non-empty name"));
544    }
545
546    #[test]
547    fn test_builder_with_valid_agent_succeeds() {
548        let agent: Arc<dyn Agent> = Arc::new(TestAgent::new("my-agent", "My agent description"));
549        let result = A2aServer::builder().agent(agent).build();
550        assert!(result.is_ok());
551        let app = result.unwrap();
552        assert_eq!(app.bind_addr(), "127.0.0.1:8080", "the default must stay on loopback");
553    }
554
555    #[test]
556    fn test_builder_custom_bind_addr() {
557        let agent: Arc<dyn Agent> = Arc::new(TestAgent::new("my-agent", "My agent"));
558        let result = A2aServer::builder().agent(agent).bind_addr("127.0.0.1:9090").build();
559        assert!(result.is_ok());
560        let app = result.unwrap();
561        assert_eq!(app.bind_addr(), "127.0.0.1:9090");
562    }
563
564    #[test]
565    fn test_builder_into_router() {
566        let agent: Arc<dyn Agent> = Arc::new(TestAgent::new("my-agent", "My agent"));
567        let app = A2aServer::builder().agent(agent).build().unwrap();
568        let _router = app.into_router();
569    }
570
571    #[test]
572    fn test_extract_port() {
573        assert_eq!(extract_port("0.0.0.0:8080"), 8080);
574        assert_eq!(extract_port("127.0.0.1:9090"), 9090);
575        assert_eq!(extract_port(":3000"), 3000);
576        assert_eq!(extract_port("invalid"), 8080);
577    }
578
579    #[test]
580    fn test_builder_all_options() {
581        let agent: Arc<dyn Agent> = Arc::new(TestAgent::new("my-agent", "My agent"));
582        let session_service: Arc<dyn SessionService> = Arc::new(InMemorySessionService::new());
583
584        let result = A2aServer::builder()
585            .agent(agent)
586            .session_service(session_service)
587            .bind_addr("0.0.0.0:3000")
588            .agent_card_name("Custom Name")
589            .agent_card_description("Custom description")
590            .agent_card_version("2.0.0")
591            .agent_card_url("https://my-agent.example.com")
592            .streaming(false)
593            .push_notifications(true)
594            .build();
595
596        assert!(result.is_ok());
597        let app = result.unwrap();
598        assert_eq!(app.bind_addr(), "0.0.0.0:3000");
599    }
600}