Skip to main content

adk_server/a2a/
interceptor.rs

1//! A2A interceptor framework for request/response middleware.
2//!
3//! This module provides an interceptor chain that can inspect, modify, or reject
4//! A2A requests before and after delegation to the executor. Interceptors enable
5//! cross-cutting concerns like authentication, rate limiting, and audit logging.
6//!
7//! # Architecture
8//!
9//! Interceptors execute in registration order for `before_delegation` (first registered
10//! runs first) and in reverse order for `after_delegation` (last registered runs first).
11//! This follows the standard middleware onion model.
12//!
13//! # Example
14//!
15//! ```rust
16//! use adk_server::a2a::interceptor::{
17//!     A2aDelegationContext, A2aError, A2aInterceptor, InterceptorChain, InterceptorDecision,
18//! };
19//! use async_trait::async_trait;
20//!
21//! struct LoggingInterceptor;
22//!
23//! #[async_trait]
24//! impl A2aInterceptor for LoggingInterceptor {
25//!     async fn before_delegation(
26//!         &self,
27//!         ctx: &mut A2aDelegationContext,
28//!     ) -> Result<InterceptorDecision, A2aError> {
29//!         println!("Before: method={}", ctx.method);
30//!         Ok(InterceptorDecision::Continue)
31//!     }
32//!
33//!     async fn after_delegation(
34//!         &self,
35//!         ctx: &A2aDelegationContext,
36//!         response: &mut serde_json::Value,
37//!     ) -> Result<(), A2aError> {
38//!         println!("After: method={}", ctx.method);
39//!         Ok(())
40//!     }
41//! }
42//!
43//! # tokio_test::block_on(async {
44//! let chain = InterceptorChain::new().add(LoggingInterceptor);
45//!
46//! let mut ctx = A2aDelegationContext {
47//!     method: "tasks/send".to_string(),
48//!     params: serde_json::json!({}),
49//!     caller_id: None,
50//!     metadata: std::collections::HashMap::new(),
51//! };
52//!
53//! let decision = chain.run_before(&mut ctx).await.unwrap();
54//! assert!(matches!(decision, InterceptorDecision::Continue));
55//! # });
56//! ```
57
58use std::collections::HashMap;
59use std::fmt;
60
61use async_trait::async_trait;
62
63/// Error type for A2A interceptor operations.
64///
65/// Represents failures that can occur during interceptor execution,
66/// including validation errors, authentication failures, and internal errors.
67///
68/// # Example
69///
70/// ```rust
71/// use adk_server::a2a::interceptor::A2aError;
72///
73/// let err = A2aError::new("authentication failed: invalid token");
74/// assert_eq!(err.to_string(), "A2A interceptor error: authentication failed: invalid token");
75///
76/// let rejected = A2aError::rejected(-32001, "rate limit exceeded");
77/// assert_eq!(rejected.code(), Some(-32001));
78/// ```
79#[derive(Debug, Clone)]
80pub struct A2aError {
81    message: String,
82    code: Option<i32>,
83}
84
85impl A2aError {
86    /// Creates a new `A2aError` with the given message.
87    pub fn new(message: impl Into<String>) -> Self {
88        Self { message: message.into(), code: None }
89    }
90
91    /// Creates a new `A2aError` representing a JSON-RPC rejection with a code and message.
92    pub fn rejected(code: i32, message: impl Into<String>) -> Self {
93        Self { message: message.into(), code: Some(code) }
94    }
95
96    /// Returns the optional JSON-RPC error code associated with this error.
97    pub fn code(&self) -> Option<i32> {
98        self.code
99    }
100}
101
102impl fmt::Display for A2aError {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        if let Some(code) = self.code {
105            write!(f, "A2A interceptor error (code {code}): {}", self.message)
106        } else {
107            write!(f, "A2A interceptor error: {}", self.message)
108        }
109    }
110}
111
112impl std::error::Error for A2aError {}
113
114impl From<A2aError> for adk_core::AdkError {
115    fn from(err: A2aError) -> Self {
116        adk_core::AdkError::agent(err.to_string())
117    }
118}
119
120/// Context available to interceptors during A2A request processing.
121///
122/// Contains the JSON-RPC method, parameters, optional caller identity,
123/// and arbitrary metadata that interceptors can read or modify.
124///
125/// # Example
126///
127/// ```rust
128/// use adk_server::a2a::interceptor::A2aDelegationContext;
129/// use std::collections::HashMap;
130///
131/// let ctx = A2aDelegationContext {
132///     method: "tasks/send".to_string(),
133///     params: serde_json::json!({"message": "hello"}),
134///     caller_id: Some("agent-123".to_string()),
135///     metadata: HashMap::from([("tenant".to_string(), "acme".to_string())]),
136/// };
137///
138/// assert_eq!(ctx.method, "tasks/send");
139/// assert_eq!(ctx.caller_id.as_deref(), Some("agent-123"));
140/// ```
141#[derive(Debug, Clone)]
142pub struct A2aDelegationContext {
143    /// The JSON-RPC method being invoked (e.g., `"tasks/send"`).
144    pub method: String,
145    /// The JSON-RPC parameters for the request.
146    pub params: serde_json::Value,
147    /// Optional identifier of the calling agent or client.
148    pub caller_id: Option<String>,
149    /// Arbitrary key-value metadata that interceptors can read or modify.
150    pub metadata: HashMap<String, String>,
151}
152
153/// Decision returned by an interceptor's `before_delegation` method.
154///
155/// Controls whether the request continues through the chain, is short-circuited
156/// with a pre-built response, or is rejected with a JSON-RPC error.
157///
158/// # Example
159///
160/// ```rust
161/// use adk_server::a2a::interceptor::InterceptorDecision;
162///
163/// // Allow the request to proceed
164/// let decision = InterceptorDecision::Continue;
165///
166/// // Short-circuit with a cached response
167/// let decision = InterceptorDecision::ShortCircuit(serde_json::json!({"cached": true}));
168///
169/// // Reject with a JSON-RPC error
170/// let decision = InterceptorDecision::Reject { code: -32001, message: "unauthorized".to_string() };
171/// ```
172#[derive(Debug, Clone)]
173pub enum InterceptorDecision {
174    /// Pass the request to the next interceptor or to the executor.
175    Continue,
176    /// Return the given response immediately without calling subsequent
177    /// interceptors or the executor.
178    ShortCircuit(serde_json::Value),
179    /// Return a JSON-RPC error response with the given code and message.
180    Reject {
181        /// JSON-RPC error code.
182        code: i32,
183        /// Human-readable error message.
184        message: String,
185    },
186}
187
188/// Trait for A2A request/response interceptors.
189///
190/// Interceptors can inspect, modify, or reject requests before they reach the
191/// executor, and can inspect or modify responses after the executor completes.
192///
193/// # Execution Order
194///
195/// - `before_delegation` runs in registration order (first added → first called).
196/// - `after_delegation` runs in reverse registration order (last added → first called).
197///
198/// # Example
199///
200/// ```rust
201/// use adk_server::a2a::interceptor::{
202///     A2aDelegationContext, A2aError, A2aInterceptor, InterceptorDecision,
203/// };
204/// use async_trait::async_trait;
205///
206/// struct AuthInterceptor {
207///     valid_token: String,
208/// }
209///
210/// #[async_trait]
211/// impl A2aInterceptor for AuthInterceptor {
212///     async fn before_delegation(
213///         &self,
214///         ctx: &mut A2aDelegationContext,
215///     ) -> Result<InterceptorDecision, A2aError> {
216///         match ctx.metadata.get("authorization") {
217///             Some(token) if token == &self.valid_token => Ok(InterceptorDecision::Continue),
218///             _ => Ok(InterceptorDecision::Reject {
219///                 code: -32001,
220///                 message: "unauthorized".to_string(),
221///             }),
222///         }
223///     }
224///
225///     async fn after_delegation(
226///         &self,
227///         _ctx: &A2aDelegationContext,
228///         _response: &mut serde_json::Value,
229///     ) -> Result<(), A2aError> {
230///         Ok(())
231///     }
232/// }
233/// ```
234#[async_trait]
235pub trait A2aInterceptor: Send + Sync {
236    /// Inspect or modify the request before delegation.
237    ///
238    /// Return [`InterceptorDecision::Continue`] to pass to the next interceptor,
239    /// [`InterceptorDecision::ShortCircuit`] to return a response immediately, or
240    /// [`InterceptorDecision::Reject`] to return a JSON-RPC error.
241    async fn before_delegation(
242        &self,
243        ctx: &mut A2aDelegationContext,
244    ) -> Result<InterceptorDecision, A2aError>;
245
246    /// Inspect or modify the response after delegation.
247    ///
248    /// Called in reverse registration order. Errors propagate immediately
249    /// without calling remaining interceptors.
250    async fn after_delegation(
251        &self,
252        ctx: &A2aDelegationContext,
253        response: &mut serde_json::Value,
254    ) -> Result<(), A2aError>;
255}
256
257/// An ordered chain of [`A2aInterceptor`] instances.
258///
259/// Executes `before_delegation` in registration order (first added runs first)
260/// and `after_delegation` in reverse order (last added runs first), following
261/// the standard middleware onion model.
262///
263/// # Example
264///
265/// ```rust
266/// use adk_server::a2a::interceptor::{
267///     A2aDelegationContext, A2aError, A2aInterceptor, InterceptorChain, InterceptorDecision,
268/// };
269/// use async_trait::async_trait;
270///
271/// struct PassthroughInterceptor;
272///
273/// #[async_trait]
274/// impl A2aInterceptor for PassthroughInterceptor {
275///     async fn before_delegation(
276///         &self,
277///         _ctx: &mut A2aDelegationContext,
278///     ) -> Result<InterceptorDecision, A2aError> {
279///         Ok(InterceptorDecision::Continue)
280///     }
281///
282///     async fn after_delegation(
283///         &self,
284///         _ctx: &A2aDelegationContext,
285///         _response: &mut serde_json::Value,
286///     ) -> Result<(), A2aError> {
287///         Ok(())
288///     }
289/// }
290///
291/// # tokio_test::block_on(async {
292/// let chain = InterceptorChain::new()
293///     .add(PassthroughInterceptor)
294///     .add(PassthroughInterceptor);
295///
296/// let mut ctx = A2aDelegationContext {
297///     method: "tasks/send".to_string(),
298///     params: serde_json::json!({}),
299///     caller_id: None,
300///     metadata: std::collections::HashMap::new(),
301/// };
302///
303/// let decision = chain.run_before(&mut ctx).await.unwrap();
304/// assert!(matches!(decision, InterceptorDecision::Continue));
305///
306/// let mut response = serde_json::json!({"result": "ok"});
307/// chain.run_after(&ctx, &mut response).await.unwrap();
308/// # });
309/// ```
310pub struct InterceptorChain {
311    interceptors: Vec<Box<dyn A2aInterceptor>>,
312}
313
314impl InterceptorChain {
315    /// Creates a new empty interceptor chain.
316    pub fn new() -> Self {
317        Self { interceptors: Vec::new() }
318    }
319
320    /// Adds an interceptor to the end of the chain.
321    ///
322    /// Interceptors are executed in the order they are added for `before_delegation`,
323    /// and in reverse order for `after_delegation`.
324    #[allow(clippy::should_implement_trait)]
325    pub fn add(mut self, interceptor: impl A2aInterceptor + 'static) -> Self {
326        self.interceptors.push(Box::new(interceptor));
327        self
328    }
329
330    /// Returns the number of interceptors in the chain.
331    pub fn len(&self) -> usize {
332        self.interceptors.len()
333    }
334
335    /// Returns `true` if the chain contains no interceptors.
336    pub fn is_empty(&self) -> bool {
337        self.interceptors.is_empty()
338    }
339
340    /// Runs all interceptors' `before_delegation` in registration order.
341    ///
342    /// Stops early if any interceptor returns [`InterceptorDecision::ShortCircuit`]
343    /// or [`InterceptorDecision::Reject`].
344    ///
345    /// # Errors
346    ///
347    /// Returns [`A2aError`] if any interceptor fails.
348    pub async fn run_before(
349        &self,
350        ctx: &mut A2aDelegationContext,
351    ) -> Result<InterceptorDecision, A2aError> {
352        for interceptor in &self.interceptors {
353            match interceptor.before_delegation(ctx).await? {
354                InterceptorDecision::Continue => continue,
355                decision => return Ok(decision),
356            }
357        }
358        Ok(InterceptorDecision::Continue)
359    }
360
361    /// Runs all interceptors' `after_delegation` in reverse registration order.
362    ///
363    /// Stops early if any interceptor returns an error.
364    ///
365    /// # Errors
366    ///
367    /// Returns [`A2aError`] if any interceptor fails.
368    pub async fn run_after(
369        &self,
370        ctx: &A2aDelegationContext,
371        response: &mut serde_json::Value,
372    ) -> Result<(), A2aError> {
373        for interceptor in self.interceptors.iter().rev() {
374            interceptor.after_delegation(ctx, response).await?;
375        }
376        Ok(())
377    }
378}
379
380impl Default for InterceptorChain {
381    fn default() -> Self {
382        Self::new()
383    }
384}
385
386impl fmt::Debug for InterceptorChain {
387    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388        f.debug_struct("InterceptorChain")
389            .field("interceptor_count", &self.interceptors.len())
390            .finish()
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    struct CountingInterceptor {
399        id: usize,
400        order: std::sync::Arc<std::sync::Mutex<Vec<(usize, &'static str)>>>,
401    }
402
403    #[async_trait]
404    impl A2aInterceptor for CountingInterceptor {
405        async fn before_delegation(
406            &self,
407            _ctx: &mut A2aDelegationContext,
408        ) -> Result<InterceptorDecision, A2aError> {
409            self.order.lock().unwrap().push((self.id, "before"));
410            Ok(InterceptorDecision::Continue)
411        }
412
413        async fn after_delegation(
414            &self,
415            _ctx: &A2aDelegationContext,
416            _response: &mut serde_json::Value,
417        ) -> Result<(), A2aError> {
418            self.order.lock().unwrap().push((self.id, "after"));
419            Ok(())
420        }
421    }
422
423    struct RejectingInterceptor;
424
425    #[async_trait]
426    impl A2aInterceptor for RejectingInterceptor {
427        async fn before_delegation(
428            &self,
429            _ctx: &mut A2aDelegationContext,
430        ) -> Result<InterceptorDecision, A2aError> {
431            Ok(InterceptorDecision::Reject { code: -32001, message: "denied".to_string() })
432        }
433
434        async fn after_delegation(
435            &self,
436            _ctx: &A2aDelegationContext,
437            _response: &mut serde_json::Value,
438        ) -> Result<(), A2aError> {
439            Ok(())
440        }
441    }
442
443    struct ShortCircuitInterceptor;
444
445    #[async_trait]
446    impl A2aInterceptor for ShortCircuitInterceptor {
447        async fn before_delegation(
448            &self,
449            _ctx: &mut A2aDelegationContext,
450        ) -> Result<InterceptorDecision, A2aError> {
451            Ok(InterceptorDecision::ShortCircuit(serde_json::json!({"cached": true})))
452        }
453
454        async fn after_delegation(
455            &self,
456            _ctx: &A2aDelegationContext,
457            _response: &mut serde_json::Value,
458        ) -> Result<(), A2aError> {
459            Ok(())
460        }
461    }
462
463    fn make_ctx() -> A2aDelegationContext {
464        A2aDelegationContext {
465            method: "tasks/send".to_string(),
466            params: serde_json::json!({}),
467            caller_id: None,
468            metadata: HashMap::new(),
469        }
470    }
471
472    #[tokio::test]
473    async fn test_empty_chain_returns_continue() {
474        let chain = InterceptorChain::new();
475        let mut ctx = make_ctx();
476        let decision = chain.run_before(&mut ctx).await.unwrap();
477        assert!(matches!(decision, InterceptorDecision::Continue));
478    }
479
480    #[tokio::test]
481    async fn test_before_executes_in_registration_order() {
482        let order = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
483        let chain = InterceptorChain::new()
484            .add(CountingInterceptor { id: 1, order: order.clone() })
485            .add(CountingInterceptor { id: 2, order: order.clone() })
486            .add(CountingInterceptor { id: 3, order: order.clone() });
487
488        let mut ctx = make_ctx();
489        chain.run_before(&mut ctx).await.unwrap();
490
491        let recorded = order.lock().unwrap();
492        assert_eq!(recorded.as_slice(), &[(1, "before"), (2, "before"), (3, "before")]);
493    }
494
495    #[tokio::test]
496    async fn test_after_executes_in_reverse_order() {
497        let order = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
498        let chain = InterceptorChain::new()
499            .add(CountingInterceptor { id: 1, order: order.clone() })
500            .add(CountingInterceptor { id: 2, order: order.clone() })
501            .add(CountingInterceptor { id: 3, order: order.clone() });
502
503        let ctx = make_ctx();
504        let mut response = serde_json::json!({"result": "ok"});
505        chain.run_after(&ctx, &mut response).await.unwrap();
506
507        let recorded = order.lock().unwrap();
508        assert_eq!(recorded.as_slice(), &[(3, "after"), (2, "after"), (1, "after")]);
509    }
510
511    #[tokio::test]
512    async fn test_reject_stops_chain() {
513        let order = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
514        let chain = InterceptorChain::new()
515            .add(CountingInterceptor { id: 1, order: order.clone() })
516            .add(RejectingInterceptor)
517            .add(CountingInterceptor { id: 3, order: order.clone() });
518
519        let mut ctx = make_ctx();
520        let decision = chain.run_before(&mut ctx).await.unwrap();
521
522        assert!(matches!(decision, InterceptorDecision::Reject { code: -32001, .. }));
523        let recorded = order.lock().unwrap();
524        // Only interceptor 1 ran before the rejection
525        assert_eq!(recorded.as_slice(), &[(1, "before")]);
526    }
527
528    #[tokio::test]
529    async fn test_short_circuit_stops_chain() {
530        let order = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
531        let chain = InterceptorChain::new()
532            .add(CountingInterceptor { id: 1, order: order.clone() })
533            .add(ShortCircuitInterceptor)
534            .add(CountingInterceptor { id: 3, order: order.clone() });
535
536        let mut ctx = make_ctx();
537        let decision = chain.run_before(&mut ctx).await.unwrap();
538
539        match decision {
540            InterceptorDecision::ShortCircuit(val) => {
541                assert_eq!(val, serde_json::json!({"cached": true}));
542            }
543            _ => panic!("expected ShortCircuit"),
544        }
545        let recorded = order.lock().unwrap();
546        assert_eq!(recorded.as_slice(), &[(1, "before")]);
547    }
548
549    #[tokio::test]
550    async fn test_chain_len_and_is_empty() {
551        let chain = InterceptorChain::new();
552        assert!(chain.is_empty());
553        assert_eq!(chain.len(), 0);
554
555        let chain = chain.add(ShortCircuitInterceptor);
556        assert!(!chain.is_empty());
557        assert_eq!(chain.len(), 1);
558    }
559
560    #[tokio::test]
561    async fn test_context_mutation_propagates() {
562        struct MutatingInterceptor;
563
564        #[async_trait]
565        impl A2aInterceptor for MutatingInterceptor {
566            async fn before_delegation(
567                &self,
568                ctx: &mut A2aDelegationContext,
569            ) -> Result<InterceptorDecision, A2aError> {
570                ctx.metadata.insert("enriched".to_string(), "true".to_string());
571                Ok(InterceptorDecision::Continue)
572            }
573
574            async fn after_delegation(
575                &self,
576                _ctx: &A2aDelegationContext,
577                _response: &mut serde_json::Value,
578            ) -> Result<(), A2aError> {
579                Ok(())
580            }
581        }
582
583        let chain = InterceptorChain::new().add(MutatingInterceptor);
584        let mut ctx = make_ctx();
585        chain.run_before(&mut ctx).await.unwrap();
586
587        assert_eq!(ctx.metadata.get("enriched"), Some(&"true".to_string()));
588    }
589
590    #[tokio::test]
591    async fn test_a2a_error_display() {
592        let err = A2aError::new("something failed");
593        assert_eq!(err.to_string(), "A2A interceptor error: something failed");
594
595        let err = A2aError::rejected(-32001, "rate limited");
596        assert_eq!(err.to_string(), "A2A interceptor error (code -32001): rate limited");
597        assert_eq!(err.code(), Some(-32001));
598    }
599}