//! Client-local catalog revisions and synchronization for MCP calls. //! //! Only active readers, calls, and frozen model bindings pin earlier snapshots. //! Servers coalesce list-change notifications and publish only a stable listing. //! Notifications update discovery without waiting for admitted calls to finish. //! Failed refreshes retain the last catalog and share a short retry cooldown. use std::future::Future; use std::sync::Arc; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::time::Duration; use anyhow::Context; use anyhow::Result; use anyhow::bail; use akode_rmcp_client::ToolListRevision; use tokio::sync::Mutex; use tokio::sync::RwLock; use tokio::time::Instant; use crate::tools::ToolInfo; const NOTIFICATION_REFRESH_COOLDOWN: Duration = Duration::from_secs(5); pub(crate) struct ClientToolCatalog { current: RwLock, /// Serialize fetches and retain the next retry time after failure or cancellation. refresh_lock: Mutex>, /// Starts at zero so notifications during the initial listing stay pending. listed_notification_revision: AtomicU64, } struct CatalogState { revision: u64, tools: Arc<[ToolInfo]>, meta: Option>, } #[derive(Clone)] pub(crate) struct ToolCatalogSnapshot { pub(crate) revision: u64, pub(crate) tools: Arc<[ToolInfo]>, pub(crate) meta: Option>, } impl ClientToolCatalog { pub(crate) fn new( tools: impl Into>, meta: Option>, ) -> Self { Self { current: RwLock::new(CatalogState { revision: 0, tools: tools.into(), meta, }), refresh_lock: Mutex::new(None), listed_notification_revision: AtomicU64::new(0), } } pub(crate) async fn read(&self, read: impl FnOnce(ToolCatalogSnapshot) -> R) -> R { let current = self.current.read().await; let snapshot = ToolCatalogSnapshot { revision: current.revision, tools: Arc::clone(¤t.tools), meta: current.meta.clone(), }; drop(current); read(snapshot) } pub(crate) fn notifications_current(&self, notifications: &ToolListRevision) -> bool { self.listed_notification_revision.load(Ordering::Acquire) == notifications.current() } /// Refresh ordinary server catalogs, coalescing concurrent readers. Never mark a /// listing current if another notification arrived while fetching its pages. /// Retry once; persistent churn stays pending until the retry cooldown expires. #[expect( clippy::await_holding_invalid_type, reason = "refreshes must remain serialized through fetching and catalog publication" )] pub(crate) async fn refresh_after_notifications( &self, notifications: &ToolListRevision, timeout: Duration, mut fetch: F, ) -> Result<()> where F: FnMut() -> Fut, Fut: Future, Option>)>>, { if self.notifications_current(notifications) { return Ok(()); } let deadline = Instant::now() + timeout; let mut retry_after = tokio::time::timeout_at(deadline, self.refresh_lock.lock()) .await .context("MCP tool catalog refresh timed out")?; if self.notifications_current(notifications) || retry_after.is_some_and(|deadline| Instant::now() < deadline) { return Ok(()); } // Also bound retries if the caller cancels this future during the fetch. *retry_after = Some(deadline + NOTIFICATION_REFRESH_COOLDOWN); let result = tokio::time::timeout_at(deadline, async { for _ in 0..2 { let revision = notifications.current(); let tools = fetch().await; let mut current = self.current.write().await; if notifications.current() != revision { continue; } let (tools, meta) = tools?; current.tools = tools.into(); current.meta = meta; current.revision += 1; self.listed_notification_revision .store(revision, Ordering::Release); return Ok(()); } bail!("MCP tool list changed during catalog refresh") }) .await .context("MCP tool catalog refresh timed out") .and_then(std::convert::identity); *retry_after = result .is_err() .then(|| Instant::now() + NOTIFICATION_REFRESH_COOLDOWN); result } /// Installs a new catalog as a list-change refresh would. #[cfg(test)] pub(crate) async fn replace_for_test(&self, tools: Vec) { let mut current = self.current.write().await; current.tools = tools.into(); current.revision += 1; } /// Reject stale calls before preparation. List-change notifications may publish while an /// admitted call runs. pub(crate) async fn run_with_snapshot( &self, expected: &ToolCatalogSnapshot, run: F, ) -> Option where F: FnOnce() -> Fut, Fut: Future, { let current = self.read(|snapshot| snapshot).await; if current.revision != expected.revision && !catalogs_match(¤t.tools, &expected.tools) { return None; } Some(run().await) } } /// Compares complete definitions independently of tool-list order. Stable sorting keeps /// conflicting duplicate identities in their original order, since deduplication can pick the /// first definition. This slow path runs only after the client's revision has changed. fn catalogs_match(left: &[ToolInfo], right: &[ToolInfo]) -> bool { if left == right { return true; } if left.len() != right.len() { return false; } let mut left = left.iter().collect::>(); let mut right = right.iter().collect::>(); for tools in [&mut left, &mut right] { tools.sort_by_key(|tool| { ( tool.server_name.as_str(), tool.tool.name.as_ref(), tool.callable_namespace.as_str(), tool.callable_name.as_str(), ) }); } left == right } /// A binding cache key includes client identity, since new clients start at zero. #[derive(Clone)] pub(crate) struct ClientToolCatalogRevision { pub(crate) catalog: Arc, pub(crate) revision: u64, } impl PartialEq for ClientToolCatalogRevision { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.catalog, &other.catalog) && self.revision == other.revision } } impl Eq for ClientToolCatalogRevision {}