Skip to main content

rap_client/
toolset_loader.rs

1/// Toolset discovery via `/.well-known/rap-toolset` endpoints.
2use rap_protocol::ToolsetManifest;
3use tracing;
4
5use crate::http::{HttpClient, ToolsetCache};
6
7/// A loaded toolset ready to be converted into Tool trait objects.
8pub struct LoadedToolset {
9    /// The deserialized toolset manifest.
10    pub manifest: ToolsetManifest,
11}
12
13impl LoadedToolset {
14    /// Wrap a manifest in a `LoadedToolset`.
15    pub fn from_manifest(manifest: ToolsetManifest) -> Self {
16        Self { manifest }
17    }
18}
19
20/// Loads RAP toolsets from `.well-known/rap-toolset` endpoints,
21/// caches them for the duration of the agent session,
22/// and converts them into Tool trait objects.
23pub struct ToolsetLoader<H: HttpClient, C: ToolsetCache> {
24    http_client: H,
25    cache: C,
26}
27
28impl<H: HttpClient, C: ToolsetCache> ToolsetLoader<H, C> {
29    /// Create a new loader with the given HTTP client and cache.
30    pub fn new(http_client: H, cache: C) -> Self {
31        Self { http_client, cache }
32    }
33
34    /// Load toolsets for the given server base URLs, scoped to a session.
35    pub async fn load_toolsets(
36        &self,
37        server_urls: &[String],
38        session_id: &rap_protocol::ThreadId<str>,
39    ) -> Result<Vec<LoadedToolset>, Box<dyn std::error::Error + Send + Sync>> {
40        let mut results = Vec::new();
41        for url in server_urls {
42            let toolset = self.load_single(url, session_id).await?;
43            results.push(toolset);
44        }
45        Ok(results)
46    }
47
48    async fn load_single(
49        &self,
50        server_url: &str,
51        session_id: &rap_protocol::ThreadId<str>,
52    ) -> Result<LoadedToolset, Box<dyn std::error::Error + Send + Sync>> {
53        let cache_key = format!("__toolset__{}_{}", session_id, server_url);
54
55        if let Some(cached_json) = self
56            .cache
57            .get_cached(&cache_key)
58            .await
59            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
60        {
61            let cached: ToolsetManifest = serde_json::from_str(&cached_json)?;
62            tracing::info!(
63                "Using cached toolset '{}' for session {}",
64                cached.name,
65                session_id
66            );
67            return Ok(LoadedToolset::from_manifest(cached));
68        }
69
70        let toolset = self.fetch_from_well_known(server_url).await?;
71
72        let json = serde_json::to_string(&toolset)?;
73        let _ = self.cache.put_cache(&cache_key, &json).await;
74
75        tracing::info!(
76            "Fetched toolset '{}' with {} tools",
77            toolset.name,
78            toolset.tools.len()
79        );
80        Ok(LoadedToolset::from_manifest(toolset))
81    }
82
83    async fn fetch_from_well_known(
84        &self,
85        server_url: &str,
86    ) -> Result<ToolsetManifest, Box<dyn std::error::Error + Send + Sync>> {
87        let well_known_url = format!(
88            "{}/.well-known/rap-toolset",
89            server_url.trim_end_matches('/')
90        );
91        tracing::info!("Fetching toolset from {}", well_known_url);
92
93        let (status, body) = self
94            .http_client
95            .get(&well_known_url)
96            .await
97            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
98
99        if !(200..300).contains(&status) {
100            let body_str = String::from_utf8_lossy(&body);
101            return Err(format!(
102                "Toolset fetch from {} returned status {}: {}",
103                well_known_url, status, body_str
104            )
105            .into());
106        }
107
108        let toolset: ToolsetManifest = serde_json::from_slice(&body)?;
109        Ok(toolset)
110    }
111}