Skip to main content

lean_ctx/core/gateway/
catalog.rs

1//! Aggregated downstream tool catalog (#210) with a TTL cache.
2//!
3//! Connects to every enabled downstream server, namespaces each tool as
4//! `server::tool`, and caches the union in-process for `cache_ttl_secs`. Fetch
5//! errors are *surfaced* (collected into [`Catalog::errors`]) rather than
6//! silently dropped, so a misconfigured server is visible to the agent.
7
8use std::sync::Mutex;
9use std::time::{Duration, Instant};
10
11use serde_json::{Map, Value};
12
13use super::client;
14use super::config::GatewayConfig;
15
16/// One downstream tool, namespaced by its server.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct CatalogEntry {
19    pub server: String,
20    pub tool: String,
21    /// `server::tool` — the stable, collision-free handle used by `ctx_tools`.
22    pub namespaced: String,
23    pub description: String,
24    /// Compact `param, required*` summary for ChoiceCards.
25    pub params: String,
26}
27
28/// The aggregated catalog plus any per-server fetch errors.
29#[derive(Debug, Clone, Default)]
30pub struct Catalog {
31    pub entries: Vec<CatalogEntry>,
32    pub errors: Vec<String>,
33}
34
35impl Catalog {
36    /// Look up an entry by its `server::tool` handle.
37    pub fn find(&self, namespaced: &str) -> Option<&CatalogEntry> {
38        self.entries.iter().find(|e| e.namespaced == namespaced)
39    }
40
41    /// Distinct server names present in the catalog, sorted.
42    pub fn server_names(&self) -> Vec<String> {
43        let mut names: Vec<String> = self.entries.iter().map(|e| e.server.clone()).collect();
44        names.sort();
45        names.dedup();
46        names
47    }
48}
49
50/// Split a `server::tool` handle back into its parts.
51pub fn split_namespaced(handle: &str) -> Option<(&str, &str)> {
52    handle
53        .split_once("::")
54        .filter(|(s, t)| !s.is_empty() && !t.is_empty())
55}
56
57static CACHE: Mutex<Option<(Instant, Catalog)>> = Mutex::new(None);
58
59/// Drop the cached catalog so the next [`get`] rebuilds it.
60pub fn invalidate() {
61    if let Ok(mut g) = CACHE.lock() {
62        *g = None;
63    }
64}
65
66/// Return the catalog, rebuilding it if the cache is empty or older than
67/// `cache_ttl_secs`.
68pub async fn get(cfg: &GatewayConfig) -> Catalog {
69    let ttl = Duration::from_secs(cfg.cache_ttl_secs);
70    if let Ok(guard) = CACHE.lock()
71        && let Some((at, cat)) = guard.as_ref()
72        && at.elapsed() < ttl
73    {
74        return cat.clone();
75    }
76    let fresh = build(cfg).await;
77    if let Ok(mut guard) = CACHE.lock() {
78        *guard = Some((Instant::now(), fresh.clone()));
79    }
80    fresh
81}
82
83/// Build the catalog from scratch (no cache). Connects to each enabled server.
84pub async fn build(cfg: &GatewayConfig) -> Catalog {
85    let timeout = Duration::from_secs(cfg.call_timeout_secs.max(1));
86    let mut entries: Vec<CatalogEntry> = Vec::new();
87    let mut errors: Vec<String> = Vec::new();
88
89    for server in cfg.active_servers() {
90        let resolved = match server.resolve() {
91            Ok(r) => r,
92            Err(e) => {
93                errors.push(e);
94                continue;
95            }
96        };
97        match client::fetch_tools(&resolved, timeout).await {
98            Ok(tools) => {
99                for t in tools {
100                    let tool = t.name.to_string();
101                    entries.push(CatalogEntry {
102                        namespaced: format!("{}::{}", server.name, tool),
103                        server: server.name.clone(),
104                        description: t.description.as_deref().unwrap_or("").trim().to_string(),
105                        params: summarize_schema(t.input_schema.as_ref()),
106                        tool,
107                    });
108                }
109            }
110            Err(e) => errors.push(format!("{}: {e}", server.name)),
111        }
112    }
113
114    // Stable order + collision-free dedup by handle.
115    entries.sort_by(|a, b| a.namespaced.cmp(&b.namespaced));
116    entries.dedup_by(|a, b| a.namespaced == b.namespaced);
117    errors.sort();
118    errors.dedup();
119
120    Catalog { entries, errors }
121}
122
123/// Render a JSON-Schema `properties`/`required` object into a compact
124/// `name, required*` parameter list (required params get a trailing `*`).
125fn summarize_schema(schema: &Map<String, Value>) -> String {
126    let Some(props) = schema.get("properties").and_then(Value::as_object) else {
127        return String::new();
128    };
129    let required: std::collections::HashSet<&str> = schema
130        .get("required")
131        .and_then(Value::as_array)
132        .map(|a| a.iter().filter_map(Value::as_str).collect())
133        .unwrap_or_default();
134    let mut names: Vec<String> = props
135        .keys()
136        .map(|k| {
137            if required.contains(k.as_str()) {
138                format!("{k}*")
139            } else {
140                k.clone()
141            }
142        })
143        .collect();
144    names.sort();
145    names.join(", ")
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use serde_json::json;
152
153    #[test]
154    fn split_namespaced_parses_handle() {
155        assert_eq!(split_namespaced("fs::read_file"), Some(("fs", "read_file")));
156        assert_eq!(split_namespaced("noseparator"), None);
157        assert_eq!(split_namespaced("::x"), None);
158        assert_eq!(split_namespaced("x::"), None);
159    }
160
161    #[test]
162    fn summarize_schema_marks_required() {
163        let schema = json!({
164            "type": "object",
165            "properties": { "path": {"type":"string"}, "depth": {"type":"integer"} },
166            "required": ["path"]
167        });
168        let s = summarize_schema(schema.as_object().unwrap());
169        assert_eq!(s, "depth, path*");
170    }
171
172    #[test]
173    fn summarize_schema_empty_when_no_props() {
174        let schema = json!({ "type": "object" });
175        assert_eq!(summarize_schema(schema.as_object().unwrap()), "");
176    }
177
178    #[test]
179    fn catalog_find_and_servers() {
180        let cat = Catalog {
181            entries: vec![
182                CatalogEntry {
183                    server: "fs".into(),
184                    tool: "read".into(),
185                    namespaced: "fs::read".into(),
186                    description: "Read a file".into(),
187                    params: "path*".into(),
188                },
189                CatalogEntry {
190                    server: "git".into(),
191                    tool: "log".into(),
192                    namespaced: "git::log".into(),
193                    description: "Show log".into(),
194                    params: String::new(),
195                },
196            ],
197            errors: vec![],
198        };
199        assert_eq!(cat.find("fs::read").unwrap().tool, "read");
200        assert!(cat.find("missing::x").is_none());
201        assert_eq!(cat.server_names(), vec!["fs", "git"]);
202    }
203}