-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathregistry.rs
More file actions
367 lines (329 loc) · 12.3 KB
/
Copy pathregistry.rs
File metadata and controls
367 lines (329 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//! Integration Registry — manages bundled + installed integration templates.
//!
//! Loads 25 bundled MCP server templates at compile time, merges with user's
//! installed state from `~/.openfang/integrations.toml`, and converts installed
//! integrations to `McpServerConfigEntry` for kernel consumption.
use crate::{
ExtensionError, ExtensionResult, InstalledIntegration, IntegrationCategory, IntegrationInfo,
IntegrationStatus, IntegrationTemplate, IntegrationsFile,
};
use openfang_types::config::{McpServerConfigEntry, McpTransportEntry};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};
/// The integration registry — holds all known templates and install state.
pub struct IntegrationRegistry {
/// All known templates (bundled + custom).
templates: HashMap<String, IntegrationTemplate>,
/// Current installed state.
installed: HashMap<String, InstalledIntegration>,
/// Path to integrations.toml.
integrations_path: PathBuf,
}
impl IntegrationRegistry {
/// Create a new registry with no templates.
pub fn new(home_dir: &Path) -> Self {
Self {
templates: HashMap::new(),
installed: HashMap::new(),
integrations_path: home_dir.join("integrations.toml"),
}
}
/// Load bundled templates (compile-time embedded). Returns count loaded.
pub fn load_bundled(&mut self) -> usize {
let bundled = crate::bundled::bundled_integrations();
let count = bundled.len();
for (id, toml_content) in bundled {
match toml::from_str::<IntegrationTemplate>(toml_content) {
Ok(template) => {
self.templates.insert(id.to_string(), template);
}
Err(e) => {
warn!("Failed to parse bundled integration '{}': {}", id, e);
}
}
}
debug!("Loaded {count} bundled integration template(s)");
count
}
/// Load installed state from integrations.toml.
pub fn load_installed(&mut self) -> ExtensionResult<usize> {
if !self.integrations_path.exists() {
return Ok(0);
}
let content = std::fs::read_to_string(&self.integrations_path)?;
let file: IntegrationsFile =
toml::from_str(&content).map_err(|e| ExtensionError::TomlParse(e.to_string()))?;
let count = file.installed.len();
for entry in file.installed {
self.installed.insert(entry.id.clone(), entry);
}
info!("Loaded {count} installed integration(s)");
Ok(count)
}
/// Save installed state to integrations.toml.
pub fn save_installed(&self) -> ExtensionResult<()> {
let file = IntegrationsFile {
installed: self.installed.values().cloned().collect(),
};
let content =
toml::to_string_pretty(&file).map_err(|e| ExtensionError::TomlParse(e.to_string()))?;
if let Some(parent) = self.integrations_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&self.integrations_path, content)?;
Ok(())
}
/// Get a template by ID.
pub fn get_template(&self, id: &str) -> Option<&IntegrationTemplate> {
self.templates.get(id)
}
/// Get an installed record by ID.
pub fn get_installed(&self, id: &str) -> Option<&InstalledIntegration> {
self.installed.get(id)
}
/// Check if an integration is installed.
pub fn is_installed(&self, id: &str) -> bool {
self.installed.contains_key(id)
}
/// Mark an integration as installed.
pub fn install(&mut self, entry: InstalledIntegration) -> ExtensionResult<()> {
if self.installed.contains_key(&entry.id) {
return Err(ExtensionError::AlreadyInstalled(entry.id.clone()));
}
self.installed.insert(entry.id.clone(), entry);
self.save_installed()
}
/// Remove an installed integration.
pub fn uninstall(&mut self, id: &str) -> ExtensionResult<()> {
if self.installed.remove(id).is_none() {
return Err(ExtensionError::NotInstalled(id.to_string()));
}
self.save_installed()
}
/// Enable/disable an installed integration.
pub fn set_enabled(&mut self, id: &str, enabled: bool) -> ExtensionResult<()> {
let entry = self
.installed
.get_mut(id)
.ok_or_else(|| ExtensionError::NotInstalled(id.to_string()))?;
entry.enabled = enabled;
self.save_installed()
}
/// List all templates.
pub fn list_templates(&self) -> Vec<&IntegrationTemplate> {
let mut templates: Vec<_> = self.templates.values().collect();
templates.sort_by(|a, b| a.id.cmp(&b.id));
templates
}
/// List templates by category.
pub fn list_by_category(&self, category: &IntegrationCategory) -> Vec<&IntegrationTemplate> {
self.templates
.values()
.filter(|t| &t.category == category)
.collect()
}
/// Search templates by query (matches id, name, description, tags).
pub fn search(&self, query: &str) -> Vec<&IntegrationTemplate> {
let q = query.to_lowercase();
self.templates
.values()
.filter(|t| {
t.id.to_lowercase().contains(&q)
|| t.name.to_lowercase().contains(&q)
|| t.description.to_lowercase().contains(&q)
|| t.tags.iter().any(|tag| tag.to_lowercase().contains(&q))
})
.collect()
}
/// Get combined info for all integrations (template + install state).
pub fn list_all_info(&self) -> Vec<IntegrationInfo> {
self.templates
.values()
.map(|t| {
let installed = self.installed.get(&t.id);
let status = match installed {
Some(inst) if !inst.enabled => IntegrationStatus::Disabled,
Some(_) => IntegrationStatus::Ready,
None => IntegrationStatus::Available,
};
IntegrationInfo {
template: t.clone(),
status,
installed: installed.cloned(),
tool_count: 0,
}
})
.collect()
}
/// Convert all enabled installed integrations to MCP server config entries.
/// These can be merged into the kernel's MCP server list.
pub fn to_mcp_configs(&self) -> Vec<McpServerConfigEntry> {
self.installed
.values()
.filter(|inst| inst.enabled)
.filter_map(|inst| {
let template = self.templates.get(&inst.id)?;
let transport = match &template.transport {
crate::McpTransportTemplate::Stdio { command, args } => {
McpTransportEntry::Stdio {
command: command.clone(),
args: args.clone(),
}
}
crate::McpTransportTemplate::Sse { url } => {
McpTransportEntry::Sse { url: url.clone() }
}
crate::McpTransportTemplate::Http { url } => {
McpTransportEntry::Http { url: url.clone() }
}
};
let env: Vec<String> = template
.required_env
.iter()
.map(|e| e.name.clone())
.collect();
Some(McpServerConfigEntry {
name: inst.id.clone(),
transport,
timeout_secs: 30,
env,
headers: Vec::new(),
allow_push_events: false,
push_queue_size: 256,
push_rate_limit_per_minute: 600,
})
})
.collect()
}
/// Get the path to integrations.toml.
pub fn integrations_path(&self) -> &Path {
&self.integrations_path
}
/// Total template count.
pub fn template_count(&self) -> usize {
self.templates.len()
}
/// Total installed count.
pub fn installed_count(&self) -> usize {
self.installed.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_load_bundled() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
let count = reg.load_bundled();
assert_eq!(count, 25);
assert_eq!(reg.template_count(), 25);
}
#[test]
fn registry_get_template() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
reg.load_bundled();
let gh = reg.get_template("github").unwrap();
assert_eq!(gh.name, "GitHub");
assert_eq!(gh.category, IntegrationCategory::DevTools);
}
#[test]
fn registry_search() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
reg.load_bundled();
let results = reg.search("search");
assert!(results.len() >= 2); // brave-search, exa-search
}
#[test]
fn registry_install_uninstall() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
reg.load_bundled();
let entry = InstalledIntegration {
id: "github".to_string(),
installed_at: chrono::Utc::now(),
enabled: true,
oauth_provider: None,
config: HashMap::new(),
};
reg.install(entry).unwrap();
assert!(reg.is_installed("github"));
assert_eq!(reg.installed_count(), 1);
// Double install should fail
let entry2 = InstalledIntegration {
id: "github".to_string(),
installed_at: chrono::Utc::now(),
enabled: true,
oauth_provider: None,
config: HashMap::new(),
};
assert!(reg.install(entry2).is_err());
reg.uninstall("github").unwrap();
assert!(!reg.is_installed("github"));
}
#[test]
fn registry_to_mcp_configs() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
reg.load_bundled();
let entry = InstalledIntegration {
id: "github".to_string(),
installed_at: chrono::Utc::now(),
enabled: true,
oauth_provider: None,
config: HashMap::new(),
};
reg.install(entry).unwrap();
let configs = reg.to_mcp_configs();
assert_eq!(configs.len(), 1);
assert_eq!(configs[0].name, "github");
}
#[test]
fn registry_save_load_roundtrip() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
reg.load_bundled();
let entry = InstalledIntegration {
id: "notion".to_string(),
installed_at: chrono::Utc::now(),
enabled: true,
oauth_provider: None,
config: HashMap::new(),
};
reg.install(entry).unwrap();
// Load from same path
let mut reg2 = IntegrationRegistry::new(dir.path());
reg2.load_bundled();
let count = reg2.load_installed().unwrap();
assert_eq!(count, 1);
assert!(reg2.is_installed("notion"));
}
#[test]
fn registry_list_by_category() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
reg.load_bundled();
let devtools = reg.list_by_category(&IntegrationCategory::DevTools);
assert_eq!(devtools.len(), 6);
}
#[test]
fn registry_set_enabled() {
let dir = tempfile::tempdir().unwrap();
let mut reg = IntegrationRegistry::new(dir.path());
reg.load_bundled();
let entry = InstalledIntegration {
id: "github".to_string(),
installed_at: chrono::Utc::now(),
enabled: true,
oauth_provider: None,
config: HashMap::new(),
};
reg.install(entry).unwrap();
reg.set_enabled("github", false).unwrap();
let configs = reg.to_mcp_configs();
assert!(configs.is_empty()); // disabled = not in MCP configs
}
}