Skip to main content

adk_tool/mcp/
resource_notifications.rs

1//! MCP resource update notification handling.
2
3use std::sync::Arc;
4
5/// Receives resource update notifications from an MCP server.
6///
7/// Register one handler on an [`McpToolset`](super::McpToolset),
8/// [`McpHttpClientBuilder`](super::McpHttpClientBuilder), or
9/// [`McpServerManager`](super::McpServerManager). The same handler is retained
10/// when ADK-Rust reconnects the underlying transport.
11#[async_trait::async_trait]
12pub trait ResourceNotificationHandler: Send + Sync {
13    /// Handle `notifications/resources/updated` for one concrete resource URI.
14    async fn handle_resource_updated(
15        &self,
16        uri: &str,
17    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
18
19    /// Handle `notifications/resources/list_changed`.
20    async fn handle_resource_list_changed(
21        &self,
22    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
23}
24
25pub(crate) async fn dispatch_resource_updated(
26    handler: &Option<Arc<dyn ResourceNotificationHandler>>,
27    uri: &str,
28) {
29    let Some(handler) = handler else {
30        return;
31    };
32    let result = std::panic::AssertUnwindSafe(handler.handle_resource_updated(uri));
33    match futures::FutureExt::catch_unwind(result).await {
34        Ok(Ok(())) => {}
35        Ok(Err(error)) => {
36            tracing::warn!(%error, %uri, "resource notification handler returned error");
37        }
38        Err(_) => {
39            tracing::warn!(%uri, "resource notification handler panicked");
40        }
41    }
42}
43
44pub(crate) async fn dispatch_resource_list_changed(
45    handler: &Option<Arc<dyn ResourceNotificationHandler>>,
46) {
47    let Some(handler) = handler else {
48        return;
49    };
50    let result = std::panic::AssertUnwindSafe(handler.handle_resource_list_changed());
51    match futures::FutureExt::catch_unwind(result).await {
52        Ok(Ok(())) => {}
53        Ok(Err(error)) => {
54            tracing::warn!(%error, "resource list notification handler returned error");
55        }
56        Err(_) => {
57            tracing::warn!("resource list notification handler panicked");
58        }
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use std::sync::atomic::{AtomicUsize, Ordering};
65
66    use super::*;
67
68    #[derive(Default)]
69    struct RecordingHandler {
70        updated: AtomicUsize,
71        list_changed: AtomicUsize,
72    }
73
74    #[async_trait::async_trait]
75    impl ResourceNotificationHandler for RecordingHandler {
76        async fn handle_resource_updated(
77            &self,
78            _uri: &str,
79        ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
80            self.updated.fetch_add(1, Ordering::Relaxed);
81            Ok(())
82        }
83
84        async fn handle_resource_list_changed(
85            &self,
86        ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
87            self.list_changed.fetch_add(1, Ordering::Relaxed);
88            Ok(())
89        }
90    }
91
92    #[tokio::test]
93    async fn dispatches_resource_notifications() {
94        let concrete = Arc::new(RecordingHandler::default());
95        let handler: Arc<dyn ResourceNotificationHandler> = concrete.clone();
96        let handler = Some(handler);
97
98        dispatch_resource_updated(&handler, "file:///workspace/Cargo.toml").await;
99        dispatch_resource_list_changed(&handler).await;
100
101        assert_eq!(concrete.updated.load(Ordering::Relaxed), 1);
102        assert_eq!(concrete.list_changed.load(Ordering::Relaxed), 1);
103    }
104}