1mod cache;
23pub mod http;
24pub mod registry;
25pub mod skills_sh;
26mod tap;
27#[cfg(test)]
28mod tests;
29
30use std::path::Path;
31use std::time::{Duration, SystemTime};
32
33use serde::{Deserialize, Serialize};
34
35use crate::adapters::detect::NoRegistry;
36use crate::env::Env;
37use crate::error::{CoreError, ErrorCode};
38use crate::fs::Fs;
39use crate::local_settings::LocalSettings;
40use crate::mcp_source::{self, RegistryRequest, ResolveRequest, Resolved};
41use crate::model::TomlDocument;
42pub use crate::model::catalogs::{
43 BUILTIN_IDS, CatalogRecord, CatalogSourceKind, CatalogsFile, is_catalog_id,
44 registry_url_problem,
45};
46use crate::model::server::ServerSource;
47use crate::paths::SurjectionHome;
48use crate::remote::git::Runner;
49use crate::skills::install::{InstallRequest, Source};
50use crate::skills::{LinkKind, SkillsEnv};
51use crate::sources::SourceRef;
52use crate::store::{CommitId, Operation, Store, StoreRead};
53pub use http::{Http, HttpLimits, HttpResponse, UreqHttp};
54
55pub const CATALOGS_FILE: &str = "catalogs.toml";
57pub const ENTITY: &str = "catalogs";
59pub const CACHE_DIR: &str = "catalogs";
61pub const TTL: Duration = Duration::from_secs(24 * 60 * 60);
63pub const MIN_QUERY: usize = 3;
66pub const REF_PREFIX: &str = "catalog:";
68pub const REGISTRY_ATTRIBUTION: &str = "Data from the Official MCP Registry";
70pub const BUILTIN_REGISTRY: &str = "mcp-registry";
71pub const BUILTIN_SKILLS: &str = "anthropic-skills";
72pub const BUILTIN_SKILLS_SH: &str = "skills-sh";
73pub const REGISTRY_URL: &str = "https://registry.modelcontextprotocol.io";
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
78#[serde(rename_all = "snake_case")]
79pub enum CatalogKind {
80 McpRegistry,
81 GitTap,
82 SkillsSh,
84}
85
86impl CatalogKind {
87 pub const fn as_str(self) -> &'static str {
88 match self {
89 CatalogKind::McpRegistry => "mcp_registry",
90 CatalogKind::GitTap => "git_tap",
91 CatalogKind::SkillsSh => "skills_sh",
92 }
93 }
94}
95
96impl From<CatalogSourceKind> for CatalogKind {
97 fn from(kind: CatalogSourceKind) -> Self {
98 match kind {
99 CatalogSourceKind::McpRegistry => CatalogKind::McpRegistry,
100 CatalogSourceKind::GitTap => CatalogKind::GitTap,
101 }
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Catalog {
108 pub id: String,
109 pub kind: CatalogKind,
110 pub title: String,
111 pub url: String,
112 pub git_ref: Option<String>,
114 pub enabled: bool,
115 pub builtin: bool,
116 pub official: bool,
118 pub attribution: Option<String>,
120}
121
122impl Catalog {
123 fn exclude(&self) -> &'static [&'static str] {
125 if self.builtin && self.id == BUILTIN_SKILLS {
126 &["template", "spec"]
127 } else {
128 &[]
129 }
130 }
131}
132
133fn builtins() -> [Catalog; 3] {
134 [
135 Catalog {
136 id: BUILTIN_REGISTRY.to_owned(),
137 kind: CatalogKind::McpRegistry,
138 title: "Official MCP Registry".to_owned(),
139 url: REGISTRY_URL.to_owned(),
140 git_ref: None,
141 enabled: true,
142 builtin: true,
143 official: false,
144 attribution: Some(REGISTRY_ATTRIBUTION.to_owned()),
145 },
146 Catalog {
147 id: BUILTIN_SKILLS.to_owned(),
148 kind: CatalogKind::GitTap,
149 title: "Anthropic skills".to_owned(),
150 url: "https://github.com/anthropics/skills".to_owned(),
151 git_ref: None,
152 enabled: true,
153 builtin: true,
154 official: true,
155 attribution: None,
156 },
157 Catalog {
158 id: BUILTIN_SKILLS_SH.to_owned(),
159 kind: CatalogKind::SkillsSh,
160 title: "skills.sh".to_owned(),
161 url: "https://skills.sh".to_owned(),
162 git_ref: None,
163 enabled: true,
164 builtin: true,
165 official: false,
166 attribution: None,
167 },
168 ]
169}
170
171fn load_doc(read: &dyn StoreRead) -> Result<TomlDocument<CatalogsFile>, CoreError> {
174 let Some(text) = read.read_file(CATALOGS_FILE)? else {
175 return Ok(TomlDocument::new(CatalogsFile::new()));
176 };
177 let path = Path::new(CATALOGS_FILE);
178 let doc = TomlDocument::<CatalogsFile>::parse(&text)
179 .map_err(|diagnostic| diagnostic.to_core_error(Some(path)))?;
180 if let Some(err) = doc.value().validate().first_error(Some(path)) {
181 return Err(err);
182 }
183 Ok(doc)
184}
185
186pub fn list(read: Option<&dyn StoreRead>) -> Result<Vec<Catalog>, CoreError> {
189 let file = match read {
190 Some(read) => load_doc(read)?.into_value(),
191 None => CatalogsFile::new(),
192 };
193 let mut catalogs: Vec<Catalog> = builtins().into_iter().collect();
194 for catalog in &mut catalogs {
195 if let Some(record) = file.catalogs.get(&catalog.id) {
196 catalog.enabled = record.enabled.unwrap_or(true);
197 }
198 }
199 for (id, record) in &file.catalogs {
200 if BUILTIN_IDS.contains(&id.as_str()) {
201 continue;
202 }
203 let (Some(kind), Some(url)) = (record.kind, record.url.clone()) else {
204 continue;
205 };
206 let official = kind == CatalogSourceKind::GitTap && tap::is_anthropic(&url);
207 catalogs.push(Catalog {
208 id: id.clone(),
209 kind: kind.into(),
210 title: record.title.clone().unwrap_or_else(|| id.clone()),
211 url: url.trim_end_matches('/').to_owned(),
212 git_ref: record.git_ref.clone(),
213 enabled: record.enabled.unwrap_or(true),
214 builtin: false,
215 official,
216 attribution: None,
217 });
218 }
219 Ok(catalogs)
220}
221
222fn find(read: Option<&dyn StoreRead>, id: &str) -> Result<Catalog, CoreError> {
224 list(read)?
225 .into_iter()
226 .find(|catalog| catalog.id == id)
227 .ok_or_else(|| CoreError::new(ErrorCode::NotFound, format!("there is no catalog {id:?}")))
228}
229
230fn change(
232 store: &Store<'_>,
233 op: &str,
234 summary: String,
235 edit: impl FnOnce(&mut CatalogsFile) -> Result<bool, CoreError>,
236) -> Result<Option<CommitId>, CoreError> {
237 let operation = Operation::new(op, summary).entity(ENTITY);
238 let committed = store.transaction(operation, |tx| {
239 let mut doc = load_doc(tx)?;
240 if !edit(doc.value_mut())? {
241 return Ok(());
242 }
243 let path = Path::new(CATALOGS_FILE);
244 if let Some(err) = doc.value().validate().first_error(Some(path)) {
245 return Err(err);
246 }
247 let text = doc.to_text()?;
248 tx.write(CATALOGS_FILE, text)
249 })?;
250 Ok(committed.commit)
251}
252
253#[derive(Debug, Clone)]
255pub struct NewCatalog {
256 pub kind: CatalogSourceKind,
257 pub url: String,
258 pub id: Option<String>,
261 pub git_ref: Option<String>,
263 pub title: Option<String>,
264}
265
266fn id_from(text: &str) -> String {
268 let id: String = text
269 .to_lowercase()
270 .chars()
271 .map(|c| {
272 if c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-') {
273 c
274 } else {
275 '-'
276 }
277 })
278 .collect();
279 let id = id.trim_matches(|c: char| !c.is_ascii_alphanumeric());
280 let id: String = id.chars().take(64).collect();
281 if id.is_empty() {
282 "catalog".to_owned()
283 } else {
284 id
285 }
286}
287
288fn default_id(new: &NewCatalog) -> String {
290 match new.kind {
291 CatalogSourceKind::McpRegistry => url::Url::parse(&new.url)
292 .ok()
293 .and_then(|url| url.host_str().map(id_from))
294 .unwrap_or_else(|| "registry".to_owned()),
295 CatalogSourceKind::GitTap => id_from(
296 new.url
297 .trim_end_matches(['/', '\\'])
298 .rsplit(['/', '\\', ':'])
299 .next()
300 .unwrap_or("tap")
301 .trim_end_matches(".git"),
302 ),
303 }
304}
305
306pub fn add(store: &Store<'_>, new: &NewCatalog) -> Result<(String, Option<CommitId>), CoreError> {
309 let url = new.url.trim().trim_end_matches('/').to_owned();
310 let existing = list(Some(store))?;
311 if let Some(same) = existing
312 .iter()
313 .find(|catalog| catalog.url.eq_ignore_ascii_case(&url))
314 {
315 return Err(CoreError::new(
316 ErrorCode::AlreadyExists,
317 format!("this catalog is already there as {:?}", same.id),
318 ));
319 }
320 let taken = |id: &str| existing.iter().any(|catalog| catalog.id == id);
321 let id = match &new.id {
322 Some(id) => {
323 if !is_catalog_id(id) {
324 return Err(CoreError::new(
325 ErrorCode::InvalidId,
326 format!(
327 "{id:?} is not a catalog id (1 to 64 characters of a-z, 0-9, '.', '_', \
328 '-', starting with a letter or digit)"
329 ),
330 ));
331 }
332 if taken(id) {
333 return Err(CoreError::new(
334 ErrorCode::AlreadyExists,
335 format!("there is already a catalog {id:?}"),
336 ));
337 }
338 id.clone()
339 }
340 None => {
341 let base = default_id(new);
342 let mut id = base.clone();
343 let mut n = 2;
344 while taken(&id) {
345 id = format!("{base}-{n}");
346 n += 1;
347 }
348 id
349 }
350 };
351 let record = CatalogRecord {
352 kind: Some(new.kind),
353 url: Some(url),
354 git_ref: new
355 .git_ref
356 .as_deref()
357 .map(str::trim)
358 .filter(|r| !r.is_empty())
359 .map(str::to_owned),
360 title: new
361 .title
362 .as_deref()
363 .map(str::trim)
364 .filter(|t| !t.is_empty())
365 .map(str::to_owned),
366 enabled: None,
367 extra: toml::Table::new(),
368 };
369 let commit = change(store, "catalog.add", format!("catalog: add {id}"), |file| {
370 file.catalogs.insert(id.clone(), record);
371 Ok(true)
372 })?;
373 Ok((id, commit))
374}
375
376pub fn remove(
379 store: &Store<'_>,
380 sx: &SkillsEnv<'_>,
381 id: &str,
382) -> Result<Option<CommitId>, CoreError> {
383 if BUILTIN_IDS.contains(&id) {
384 return Err(CoreError::new(
385 ErrorCode::InvalidValue,
386 format!("{id:?} is a built-in catalog: turn it off instead"),
387 ));
388 }
389 find(Some(store), id)?;
390 let commit = change(
391 store,
392 "catalog.remove",
393 format!("catalog: remove {id}"),
394 |file| Ok(file.catalogs.remove(id).is_some()),
395 )?;
396 cache::clear(sx, id)?;
397 Ok(commit)
398}
399
400pub fn set_enabled(
402 store: &Store<'_>,
403 id: &str,
404 enabled: bool,
405) -> Result<Option<CommitId>, CoreError> {
406 find(Some(store), id)?;
407 let verb = if enabled { "enable" } else { "disable" };
408 change(
409 store,
410 &format!("catalog.{verb}"),
411 format!("catalog: {verb} {id}"),
412 |file| {
413 let builtin = BUILTIN_IDS.contains(&id);
414 let current = file
415 .catalogs
416 .get(id)
417 .and_then(|record| record.enabled)
418 .unwrap_or(true);
419 if current == enabled {
420 return Ok(false);
421 }
422 if builtin {
423 if enabled {
424 file.catalogs.remove(id);
425 } else {
426 file.catalogs
427 .insert(id.to_owned(), CatalogRecord::switch(false));
428 }
429 } else if let Some(record) = file.catalogs.get_mut(id) {
430 record.enabled = (!enabled).then_some(false);
431 }
432 Ok(true)
433 },
434 )
435}
436
437pub fn host(catalog: &Catalog) -> Option<String> {
440 match catalog.kind {
441 CatalogKind::GitTap => match SourceRef::from_git_url(&catalog.url) {
442 Ok(source) if source.key().starts_with("file:") => None,
443 Ok(source) => Some(
444 crate::sources::without_insecure_prefix(source.key())
445 .split('/')
446 .next()
447 .unwrap_or_default()
448 .to_owned(),
449 ),
450 Err(_) => None,
451 },
452 _ => Some(http::host_of(&catalog.url)),
453 }
454}
455
456pub fn contacts(catalogs: &[Catalog]) -> Vec<String> {
460 let mut hosts: Vec<String> = Vec::new();
461 for host in catalogs
462 .iter()
463 .filter(|catalog| catalog.enabled)
464 .filter_map(host)
465 {
466 if !hosts.contains(&host) {
467 hosts.push(host);
468 }
469 }
470 hosts
471}
472
473pub const LEGACY_HOSTS: [&str; 2] = ["registry.modelcontextprotocol.io", "github.com"];
479
480#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct OnlineSetting {
483 pub on: bool,
484 pub answered: bool,
486 pub hosts: Vec<String>,
490 pub not_now: Vec<String>,
493}
494
495impl OnlineSetting {
496 fn of(settings: &LocalSettings) -> Self {
497 let on = settings.online_catalogs == Some(true);
498 let hosts = match &settings.online_catalog_hosts {
499 Some(hosts) => hosts.clone(),
500 None if on => LEGACY_HOSTS.map(str::to_owned).to_vec(),
501 None => Vec::new(),
502 };
503 Self {
504 on,
505 answered: settings.online_catalogs.is_some(),
506 hosts,
507 not_now: settings
508 .online_catalog_hosts_not_now
509 .clone()
510 .unwrap_or_default(),
511 }
512 }
513
514 pub fn allows(&self, host: &str) -> bool {
516 self.on && self.hosts.iter().any(|approved| approved == host)
517 }
518
519 pub fn unapproved(&self, contacts: &[String]) -> Vec<String> {
522 contacts
523 .iter()
524 .filter(|host| !self.hosts.contains(host))
525 .cloned()
526 .collect()
527 }
528
529 pub fn to_ask(&self, contacts: &[String]) -> Vec<String> {
533 if !self.on {
534 return Vec::new();
535 }
536 self.unapproved(contacts)
537 .into_iter()
538 .filter(|host| !self.not_now.contains(host))
539 .collect()
540 }
541
542 pub fn decided(&self, contacts: &[String]) -> bool {
545 self.answered && self.to_ask(contacts).is_empty()
546 }
547
548 pub fn gate(&self, catalog: &Catalog) -> Result<(), CoreError> {
551 if !self.on {
552 return Err(off_error());
553 }
554 match host(catalog) {
555 Some(host) if !self.allows(&host) => Err(not_approved_error(&host)),
556 _ => Ok(()),
557 }
558 }
559}
560
561pub fn online(fs: &dyn Fs, home: &SurjectionHome) -> Result<OnlineSetting, CoreError> {
562 let settings = LocalSettings::load(fs, &home.state_dir())?;
563 Ok(OnlineSetting::of(&settings))
564}
565
566fn with_hosts(mut list: Vec<String>, hosts: &[String]) -> Vec<String> {
568 for host in hosts {
569 if !list.contains(host) {
570 list.push(host.clone());
571 }
572 }
573 list
574}
575
576pub fn set_online(
580 fs: &dyn Fs,
581 home: &SurjectionHome,
582 on: bool,
583 contacts: &[String],
584) -> Result<(), CoreError> {
585 let state = home.state_dir();
586 let mut settings = LocalSettings::load(fs, &state)?;
587 let before = OnlineSetting::of(&settings);
588 settings.online_catalogs = Some(on);
589 if on {
590 settings.online_catalog_hosts = Some(with_hosts(before.hosts, contacts));
591 let not_now: Vec<String> = before
592 .not_now
593 .into_iter()
594 .filter(|host| !contacts.contains(host))
595 .collect();
596 settings.online_catalog_hosts_not_now = (!not_now.is_empty()).then_some(not_now);
597 }
598 settings.save(fs, &state)
599}
600
601pub fn answer_hosts(
606 fs: &dyn Fs,
607 home: &SurjectionHome,
608 hosts: &[String],
609 allow: bool,
610) -> Result<(), CoreError> {
611 let state = home.state_dir();
612 let mut settings = LocalSettings::load(fs, &state)?;
613 let before = OnlineSetting::of(&settings);
614 let not_now = if allow {
615 settings.online_catalog_hosts = Some(with_hosts(before.hosts, hosts));
616 before
617 .not_now
618 .into_iter()
619 .filter(|host| !hosts.contains(host))
620 .collect()
621 } else {
622 let declined: Vec<String> = hosts
623 .iter()
624 .filter(|host| !before.hosts.contains(host))
625 .cloned()
626 .collect();
627 with_hosts(before.not_now, &declined)
628 };
629 settings.online_catalog_hosts_not_now = (!not_now.is_empty()).then_some(not_now);
630 settings.save(fs, &state)
631}
632
633fn off_error() -> CoreError {
634 CoreError::new(
635 ErrorCode::CatalogsOff,
636 "online catalogs are off on this machine, so no catalog was contacted; turn them on in \
637 Install > Browse or with `surject catalog online on`",
638 )
639}
640
641fn not_approved_error(host: &str) -> CoreError {
642 CoreError::new(
643 ErrorCode::CatalogHostWaiting,
644 format!(
645 "Surjection has not contacted {host}: it waits for your OK; allow it in Settings > \
646 Catalogs or with `surject catalog online on`"
647 ),
648 )
649}
650
651fn require_online(fs: &dyn Fs, home: &SurjectionHome) -> Result<(), CoreError> {
652 if online(fs, home)?.on {
653 Ok(())
654 } else {
655 Err(off_error())
656 }
657}
658
659#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
662#[serde(rename_all = "snake_case")]
663pub enum EntryKind {
664 Server,
665 Skill,
666 Plugin,
667}
668
669impl EntryKind {
670 pub const fn as_str(self) -> &'static str {
671 match self {
672 EntryKind::Server => "server",
673 EntryKind::Skill => "skill",
674 EntryKind::Plugin => "plugin",
675 }
676 }
677}
678
679#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
681pub struct Publisher {
682 pub name: String,
683 pub checked: Option<String>,
685}
686
687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
688pub struct EntryPackage {
689 pub registry_type: String,
690 pub identifier: String,
691 pub version: Option<String>,
692 pub transport: Option<String>,
693 pub pinned: bool,
695}
696
697#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
698pub struct EntryRemote {
699 pub transport: String,
700 pub url: String,
702}
703
704#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
705#[serde(rename_all = "snake_case")]
706pub enum PluginSourceKind {
707 Relative,
708 Github,
709 Url,
710 GitSubdir,
711 Npm,
712 Archive,
713 Command,
714 Unknown,
715}
716
717impl PluginSourceKind {
718 pub const fn as_str(self) -> &'static str {
719 match self {
720 PluginSourceKind::Relative => "relative",
721 PluginSourceKind::Github => "github",
722 PluginSourceKind::Url => "url",
723 PluginSourceKind::GitSubdir => "git_subdir",
724 PluginSourceKind::Npm => "npm",
725 PluginSourceKind::Archive => "archive",
726 PluginSourceKind::Command => "command",
727 PluginSourceKind::Unknown => "unknown",
728 }
729 }
730}
731
732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
734pub struct PluginSource {
735 pub kind: PluginSourceKind,
736 pub url: Option<String>,
738 pub path: Option<String>,
740 pub git_ref: Option<String>,
741 pub sha: Option<String>,
742}
743
744#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
747pub struct CatalogEntry {
748 pub catalog: String,
749 pub id: String,
751 pub kind: EntryKind,
752 pub name: String,
753 pub description: Option<String>,
754 pub version: Option<String>,
755 pub updated_at: Option<String>,
756 pub deprecated: bool,
757 pub status_message: Option<String>,
758 pub publisher: Option<Publisher>,
759 pub official: bool,
760 pub warning: Option<String>,
761 pub repository: Option<String>,
762 pub website: Option<String>,
763 pub license: Option<String>,
764 pub transports: Vec<String>,
765 pub packages: Vec<EntryPackage>,
766 pub remotes: Vec<EntryRemote>,
767 pub required_secrets: Vec<String>,
768 pub pinned: bool,
769 pub git_ref: Option<String>,
770 pub commit: Option<String>,
771 pub path: Option<String>,
772 pub skills: Vec<String>,
773 pub servers: Vec<String>,
774 pub not_imported: Vec<String>,
775 pub source: Option<PluginSource>,
776 pub install_mcp: bool,
777 pub install_skill: bool,
778 pub problem: Option<String>,
779 pub server_json: Option<String>,
781 #[serde(default)]
784 pub mcp_servers: Option<String>,
785 #[serde(default)]
787 pub installs: Option<u64>,
788}
789
790impl CatalogEntry {
791 pub fn reference(&self) -> String {
793 format!("{REF_PREFIX}{}/{}", self.catalog, self.id)
794 }
795}
796
797pub(crate) fn is_plugin_name(name: &str) -> bool {
800 !name.is_empty()
801 && name.len() <= 128
802 && name.starts_with(|c: char| c.is_ascii_alphanumeric())
803 && name
804 .chars()
805 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
806 && !name.contains("..")
807}
808
809#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
813pub enum ResultStatus {
814 Fresh,
816 Cached,
818 Stale,
820 Off,
822 Disabled,
824 QueryTooShort,
826 Error,
828}
829
830impl ResultStatus {
831 pub const fn as_str(self) -> &'static str {
832 match self {
833 ResultStatus::Fresh => "fresh",
834 ResultStatus::Cached => "cached",
835 ResultStatus::Stale => "stale",
836 ResultStatus::Off => "off",
837 ResultStatus::Disabled => "disabled",
838 ResultStatus::QueryTooShort => "query_too_short",
839 ResultStatus::Error => "error",
840 }
841 }
842}
843
844#[derive(Debug, Clone)]
846pub struct Results {
847 pub catalog: String,
848 pub status: ResultStatus,
849 pub fetched_at: Option<SystemTime>,
850 pub age: Option<Duration>,
851 pub error: Option<CoreError>,
852 pub entries: Vec<CatalogEntry>,
853 pub next_cursor: Option<String>,
854 pub attribution: Option<String>,
855}
856
857impl Results {
858 fn new(catalog: &Catalog, status: ResultStatus) -> Self {
859 Self {
860 catalog: catalog.id.clone(),
861 status,
862 fetched_at: None,
863 age: None,
864 error: None,
865 entries: Vec::new(),
866 next_cursor: None,
867 attribution: catalog.attribution.clone(),
868 }
869 }
870}
871
872pub struct CatalogEnv<'a> {
874 pub sx: &'a SkillsEnv<'a>,
875 pub http: &'a dyn Http,
876}
877
878static NO_REGISTRY: NoRegistry = NoRegistry;
879
880#[derive(Clone, Copy)]
883struct Parts<'a> {
884 env: &'a Env,
885 fs: &'a dyn Fs,
886 home: &'a SurjectionHome,
887 runner: &'a dyn Runner,
888 link_kind: LinkKind,
889 http: &'a dyn Http,
890}
891
892impl<'a> Parts<'a> {
893 fn of(cx: &CatalogEnv<'a>) -> Self {
894 Self {
895 env: cx.sx.env,
896 fs: cx.sx.fs,
897 home: cx.sx.home,
898 runner: cx.sx.runner,
899 link_kind: cx.sx.link_kind,
900 http: cx.http,
901 }
902 }
903
904 fn sx(&self) -> SkillsEnv<'a> {
905 SkillsEnv {
906 env: self.env,
907 fs: self.fs,
908 home: self.home,
909 registry: &NO_REGISTRY,
910 runner: self.runner,
911 link_kind: self.link_kind,
912 }
913 }
914}
915
916struct Got<T> {
918 data: Option<T>,
919 status: ResultStatus,
920 fetched_at: Option<SystemTime>,
921 age: Option<Duration>,
922 error: Option<CoreError>,
923}
924
925fn cached_or<T: Serialize + serde::de::DeserializeOwned>(
931 parts: &Parts<'_>,
932 gate: &Result<(), CoreError>,
933 refetch: bool,
934 catalog: &str,
935 name: &str,
936 key: &str,
937 fetch: impl FnOnce() -> Result<T, CoreError>,
938) -> Got<T> {
939 let sx = parts.sx();
940 let now = parts.env.now();
941 let hit = (!refetch)
942 .then(|| cache::read::<T>(&sx, catalog, name, key))
943 .flatten();
944 let from_hit = |hit: cache::Hit<T>, status: ResultStatus, error: Option<CoreError>| Got {
945 age: Some(hit.age(now)),
946 fetched_at: Some(hit.fetched_at),
947 data: Some(hit.data),
948 status,
949 error,
950 };
951 if let Err(closed) = gate {
952 return match hit {
953 Some(hit) => {
956 let waiting =
957 (closed.code() == ErrorCode::CatalogHostWaiting).then(|| closed.clone());
958 from_hit(hit, ResultStatus::Off, waiting)
959 }
960 None => Got {
961 data: None,
962 status: ResultStatus::Off,
963 fetched_at: None,
964 age: None,
965 error: Some(closed.clone()),
966 },
967 };
968 }
969 let hit = match hit {
970 Some(hit) if hit.age(now) < TTL => return from_hit(hit, ResultStatus::Cached, None),
971 hit => hit,
972 };
973 match fetch() {
974 Ok(data) => {
975 let fetched_at = cache::write(&sx, catalog, name, key, &data).ok();
976 Got {
977 data: Some(data),
978 status: ResultStatus::Fresh,
979 fetched_at: fetched_at.or(Some(now)),
980 age: Some(Duration::ZERO),
981 error: None,
982 }
983 }
984 Err(err) => {
985 let stale = hit.or_else(|| cache::read::<T>(&sx, catalog, name, key));
986 match stale {
987 Some(hit) => from_hit(hit, ResultStatus::Stale, Some(err)),
988 None => Got {
989 data: None,
990 status: ResultStatus::Error,
991 fetched_at: None,
992 age: None,
993 error: Some(err),
994 },
995 }
996 }
997 }
998}
999
1000fn search_prefix(catalog: &Catalog) -> String {
1003 format!("search\n{}\n", catalog.url)
1004}
1005
1006fn search_key(catalog: &Catalog, needle: &str, cursor: Option<&str>) -> String {
1008 format!(
1009 "{}{needle}\n{}",
1010 search_prefix(catalog),
1011 cursor.unwrap_or_default()
1012 )
1013}
1014
1015fn tap_key(catalog: &Catalog) -> String {
1017 format!(
1018 "tap\n{}\n{}",
1019 catalog.url,
1020 catalog.git_ref.as_deref().unwrap_or_default()
1021 )
1022}
1023
1024fn tap_index(
1026 parts: &Parts<'_>,
1027 gate: &Result<(), CoreError>,
1028 refetch: bool,
1029 catalog: &Catalog,
1030) -> Got<tap::TapIndex> {
1031 cached_or(
1032 parts,
1033 gate,
1034 refetch,
1035 &catalog.id,
1036 "index",
1037 &tap_key(catalog),
1038 || tap::index(&parts.sx(), catalog, catalog.exclude()),
1039 )
1040}
1041
1042fn with<T>(
1043 mut results: Results,
1044 got: Got<T>,
1045 entries: impl FnOnce(T) -> (Vec<CatalogEntry>, Option<String>),
1046) -> Results {
1047 results.status = got.status;
1048 results.fetched_at = got.fetched_at;
1049 results.age = got.age;
1050 results.error = got.error;
1051 if let Some(data) = got.data {
1052 (results.entries, results.next_cursor) = entries(data);
1053 }
1054 results
1055}
1056
1057fn search_catalog(
1058 parts: &Parts<'_>,
1059 gate: &Result<(), CoreError>,
1060 catalog: &Catalog,
1061 query: &str,
1062 cursor: Option<&str>,
1063) -> Results {
1064 if !catalog.enabled {
1065 return Results::new(catalog, ResultStatus::Disabled);
1066 }
1067 crate::diagnostics::log::event(
1069 "catalog.search",
1070 &[
1071 ("catalog", &catalog.id),
1072 ("query_len", &query.trim().chars().count()),
1073 ],
1074 );
1075 let needle = query.trim().to_lowercase();
1076 match catalog.kind {
1077 CatalogKind::SkillsSh => {
1078 if query.trim().chars().count() < skills_sh::MIN_QUERY {
1079 let mut results = Results::new(catalog, ResultStatus::QueryTooShort);
1080 results.error = Some(CoreError::new(
1081 ErrorCode::InvalidValue,
1082 format!(
1083 "search {} with at least {} characters",
1084 catalog.title,
1085 skills_sh::MIN_QUERY
1086 ),
1087 ));
1088 return results;
1089 }
1090 let key = search_key(catalog, &needle, None);
1091 let name = format!("search-{}", cache::digest(&key));
1092 let got = cached_or(parts, gate, false, &catalog.id, &name, &key, || {
1093 skills_sh::search(parts.http, catalog, query).map(|entries| (entries, None))
1094 });
1095 with(Results::new(catalog, ResultStatus::Fresh), got, |data| data)
1096 }
1097 CatalogKind::McpRegistry => {
1098 if query.trim().chars().count() < MIN_QUERY {
1099 let mut results = Results::new(catalog, ResultStatus::QueryTooShort);
1100 results.error = Some(CoreError::new(
1101 ErrorCode::InvalidValue,
1102 format!(
1103 "search {} with at least {MIN_QUERY} characters",
1104 catalog.title
1105 ),
1106 ));
1107 return results;
1108 }
1109 let key = search_key(catalog, &needle, cursor);
1110 let name = format!("search-{}", cache::digest(&key));
1111 let got = cached_or(parts, gate, false, &catalog.id, &name, &key, || {
1112 registry::search(parts.http, catalog, query, cursor)
1113 .map(|page| (page.entries, page.next_cursor))
1114 });
1115 with(Results::new(catalog, ResultStatus::Fresh), got, |data| data)
1116 }
1117 CatalogKind::GitTap => {
1118 let got = tap_index(parts, gate, false, catalog);
1119 with(Results::new(catalog, ResultStatus::Fresh), got, |index| {
1120 let entries = index
1121 .entries
1122 .into_iter()
1123 .filter(|entry| registry::matches(entry, &needle))
1124 .collect();
1125 (entries, None)
1126 })
1127 }
1128 }
1129}
1130
1131pub fn search(
1135 cx: &CatalogEnv<'_>,
1136 read: Option<&dyn StoreRead>,
1137 query: &str,
1138 only: Option<&str>,
1139) -> Result<Vec<Results>, CoreError> {
1140 let catalogs: Vec<Catalog> = match only {
1141 Some(id) => vec![find(read, id)?],
1142 None => list(read)?
1143 .into_iter()
1144 .filter(|catalog| catalog.enabled)
1145 .collect(),
1146 };
1147 let parts = Parts::of(cx);
1148 let setting = online(parts.fs, parts.home)?;
1149 let setting = &setting;
1150 Ok(std::thread::scope(|scope| {
1151 let handles: Vec<_> = catalogs
1152 .iter()
1153 .map(|catalog| {
1154 scope.spawn(move || {
1155 search_catalog(&parts, &setting.gate(catalog), catalog, query, None)
1156 })
1157 })
1158 .collect();
1159 handles
1160 .into_iter()
1161 .zip(&catalogs)
1162 .map(|(handle, catalog)| {
1163 handle.join().unwrap_or_else(|_| {
1164 let mut results = Results::new(catalog, ResultStatus::Error);
1165 results.error = Some(CoreError::new(
1166 ErrorCode::CatalogUnreachable,
1167 "the search of this catalog stopped unexpectedly",
1168 ));
1169 results
1170 })
1171 })
1172 .collect()
1173 }))
1174}
1175
1176pub fn search_one(
1178 cx: &CatalogEnv<'_>,
1179 read: Option<&dyn StoreRead>,
1180 catalog: &str,
1181 query: &str,
1182 cursor: Option<&str>,
1183) -> Result<Results, CoreError> {
1184 let catalog = find(read, catalog)?;
1185 let parts = Parts::of(cx);
1186 let gate = online(parts.fs, parts.home)?.gate(&catalog);
1187 Ok(search_catalog(&parts, &gate, &catalog, query, cursor))
1188}
1189
1190#[derive(Debug, Clone)]
1192pub struct Shown {
1193 pub entry: CatalogEntry,
1194 pub status: ResultStatus,
1195 pub age: Option<Duration>,
1196 pub error: Option<CoreError>,
1197}
1198
1199fn shown(got: Got<CatalogEntry>) -> Result<Shown, CoreError> {
1201 match got.data {
1202 Some(entry) => Ok(Shown {
1203 entry,
1204 status: got.status,
1205 age: got.age,
1206 error: got.error,
1207 }),
1208 None => Err(got.error.unwrap_or_else(off_error)),
1209 }
1210}
1211
1212fn not_in(catalog: &Catalog, id: &str) -> CoreError {
1213 CoreError::new(
1214 ErrorCode::NotFound,
1215 format!("{} lists no entry {id:?}", catalog.title),
1216 )
1217}
1218
1219pub fn show(
1222 cx: &CatalogEnv<'_>,
1223 read: Option<&dyn StoreRead>,
1224 catalog: &str,
1225 entry: &str,
1226) -> Result<Shown, CoreError> {
1227 let catalog = find(read, catalog)?;
1228 let parts = Parts::of(cx);
1229 let gate = online(parts.fs, parts.home)?.gate(&catalog);
1230 match catalog.kind {
1231 CatalogKind::SkillsSh => {
1232 let hit =
1233 cache::entry_in_pages(&parts.sx(), &catalog.id, &search_prefix(&catalog), entry)
1234 .ok_or_else(|| {
1235 CoreError::new(
1236 ErrorCode::NotFound,
1237 format!(
1238 "{} has no saved result {entry:?}: search for it first",
1239 catalog.title
1240 ),
1241 )
1242 })?;
1243 let age = hit.age(parts.env.now());
1244 Ok(Shown {
1245 status: if gate.is_err() {
1246 ResultStatus::Off
1247 } else if age >= TTL {
1248 ResultStatus::Stale
1249 } else {
1250 ResultStatus::Cached
1251 },
1252 age: Some(age),
1253 entry: hit.data,
1254 error: gate
1255 .err()
1256 .filter(|closed| closed.code() == ErrorCode::CatalogHostWaiting),
1257 })
1258 }
1259 CatalogKind::McpRegistry => {
1260 let key = format!("entry\n{}\n{entry}", catalog.url);
1261 let name = format!("entry-{}", cache::digest(&key));
1262 shown(cached_or(
1263 &parts,
1264 &gate,
1265 false,
1266 &catalog.id,
1267 &name,
1268 &key,
1269 || registry::entry(parts.http, &catalog, entry, None),
1270 ))
1271 }
1272 CatalogKind::GitTap => {
1273 let got = tap_index(&parts, &gate, false, &catalog);
1274 let found = got
1275 .data
1276 .as_ref()
1277 .map(|index| index.entries.iter().find(|e| e.id == entry).cloned());
1278 match found {
1279 Some(Some(found)) => Ok(Shown {
1280 entry: found,
1281 status: got.status,
1282 age: got.age,
1283 error: got.error,
1284 }),
1285 Some(None) => Err(not_in(&catalog, entry)),
1286 None => Err(got.error.unwrap_or_else(off_error)),
1287 }
1288 }
1289 }
1290}
1291
1292pub fn cached_entry(
1295 sx: &SkillsEnv<'_>,
1296 read: Option<&dyn StoreRead>,
1297 catalog: &str,
1298 entry: &str,
1299) -> Result<CatalogEntry, CoreError> {
1300 let catalog = find(read, catalog)?;
1301 match catalog.kind {
1302 CatalogKind::SkillsSh => {
1303 cache::entry_in_pages(sx, &catalog.id, &search_prefix(&catalog), entry)
1304 .map(|hit| hit.data)
1305 .ok_or_else(|| not_in(&catalog, entry))
1306 }
1307 CatalogKind::GitTap => {
1308 cache::read::<tap::TapIndex>(sx, &catalog.id, "index", &tap_key(&catalog))
1309 .and_then(|hit| hit.data.entries.into_iter().find(|e| e.id == entry))
1310 .ok_or_else(|| not_in(&catalog, entry))
1311 }
1312 CatalogKind::McpRegistry => {
1313 let key = format!("entry\n{}\n{entry}", catalog.url);
1314 if let Some(hit) = cache::read::<CatalogEntry>(
1315 sx,
1316 &catalog.id,
1317 &format!("entry-{}", cache::digest(&key)),
1318 &key,
1319 ) {
1320 return Ok(hit.data);
1321 }
1322 cache::entry_in_pages(sx, &catalog.id, &search_prefix(&catalog), entry)
1326 .map(|hit| hit.data)
1327 .ok_or_else(|| not_in(&catalog, entry))
1328 }
1329 }
1330}
1331
1332pub fn refresh(
1339 cx: &CatalogEnv<'_>,
1340 read: Option<&dyn StoreRead>,
1341 only: Option<&str>,
1342) -> Result<Vec<Results>, CoreError> {
1343 let catalogs: Vec<Catalog> = match only {
1344 Some(id) => vec![find(read, id)?],
1345 None => list(read)?
1346 .into_iter()
1347 .filter(|catalog| catalog.enabled)
1348 .collect(),
1349 };
1350 let parts = Parts::of(cx);
1351 let setting = online(parts.fs, parts.home)?;
1352 if !setting.on {
1353 return Err(off_error());
1354 }
1355 let setting = &setting;
1356 Ok(std::thread::scope(|scope| {
1357 let handles: Vec<_> = catalogs
1358 .iter()
1359 .map(|catalog| {
1360 scope.spawn(move || {
1361 let sx = parts.sx();
1362 let base = Results::new(catalog, ResultStatus::Fresh);
1363 if let Err(closed) = setting.gate(catalog) {
1364 return Results {
1365 status: ResultStatus::Off,
1366 error: Some(closed),
1367 ..base
1368 };
1369 }
1370 let answered = match catalog.kind {
1371 CatalogKind::SkillsSh => {
1372 skills_sh::search(parts.http, catalog, skills_sh::PING_QUERY)
1373 .map(|_| ())
1374 }
1375 CatalogKind::McpRegistry => registry::ping(parts.http, catalog),
1376 CatalogKind::GitTap => {
1377 let got = tap_index(&parts, &Ok(()), true, catalog);
1378 return with(base, got, |index| (index.entries, None));
1379 }
1380 };
1381 match answered {
1382 Ok(()) => {
1383 let _ = cache::clear(&sx, &catalog.id);
1384 Results {
1385 fetched_at: Some(parts.env.now()),
1386 age: Some(Duration::ZERO),
1387 ..base
1388 }
1389 }
1390 Err(err) => Results {
1391 status: ResultStatus::Error,
1392 error: Some(err),
1393 ..base
1394 },
1395 }
1396 })
1397 })
1398 .collect();
1399 handles
1400 .into_iter()
1401 .zip(&catalogs)
1402 .map(|(handle, catalog)| {
1403 handle.join().unwrap_or_else(|_| {
1404 let mut results = Results::new(catalog, ResultStatus::Error);
1405 results.error = Some(CoreError::new(
1406 ErrorCode::CatalogUnreachable,
1407 "the refresh of this catalog stopped unexpectedly",
1408 ));
1409 results
1410 })
1411 })
1412 .collect()
1413 }))
1414}
1415
1416pub fn parse_ref(text: &str) -> Result<(String, String), CoreError> {
1420 let bad = || {
1421 CoreError::new(
1422 ErrorCode::InvalidValue,
1423 format!("{text:?} is not a catalog entry (catalog:<source>/<id>)"),
1424 )
1425 };
1426 let rest = text.trim().strip_prefix(REF_PREFIX).ok_or_else(bad)?;
1427 let (catalog, id) = rest.split_once('/').ok_or_else(bad)?;
1428 if !is_catalog_id(catalog) || id.is_empty() || id.chars().any(char::is_control) {
1429 return Err(bad());
1430 }
1431 Ok((catalog.to_owned(), id.to_owned()))
1432}
1433
1434fn install_entry(
1437 parts: &Parts<'_>,
1438 read: Option<&dyn StoreRead>,
1439 text: &str,
1440) -> Result<(Catalog, CatalogEntry, Option<tap::TapIndex>), CoreError> {
1441 let (catalog_id, entry_id) = parse_ref(text)?;
1442 let catalog = find(read, &catalog_id)?;
1443 if !catalog.enabled {
1444 return Err(CoreError::new(
1445 ErrorCode::InvalidValue,
1446 format!("the catalog {catalog_id:?} is turned off"),
1447 ));
1448 }
1449 online(parts.fs, parts.home)?.gate(&catalog)?;
1450 match catalog.kind {
1451 CatalogKind::SkillsSh => {
1452 let entry = cache::entry_in_pages(
1454 &parts.sx(),
1455 &catalog.id,
1456 &search_prefix(&catalog),
1457 &entry_id,
1458 )
1459 .map(|hit| hit.data)
1460 .or_else(|| skills_sh::entry_for(&catalog, &entry_id, None, None, None))
1461 .ok_or_else(|| not_in(&catalog, &entry_id))?;
1462 Ok((catalog, entry, None))
1463 }
1464 CatalogKind::McpRegistry => {
1465 let entry = registry::entry(parts.http, &catalog, &entry_id, None);
1467 entry.map(|entry| (catalog, entry, None))
1468 }
1469 CatalogKind::GitTap => {
1470 let got = tap_index(parts, &Ok(()), false, &catalog);
1471 let index = got
1472 .data
1473 .ok_or_else(|| got.error.unwrap_or_else(off_error))?;
1474 let entry = index
1475 .entries
1476 .iter()
1477 .find(|e| e.id == entry_id)
1478 .cloned()
1479 .ok_or_else(|| not_in(&catalog, &entry_id))?;
1480 Ok((catalog, entry, Some(index)))
1481 }
1482 }
1483}
1484
1485#[derive(Debug, Clone)]
1487pub enum McpRequest {
1488 Registry(RegistryRequest),
1490 Git(ResolveRequest),
1492}
1493
1494#[derive(Debug, Clone)]
1497pub struct McpHandoff {
1498 pub entry: CatalogEntry,
1499 pub request: McpRequest,
1500}
1501
1502impl McpHandoff {
1503 pub fn trust_source(&self) -> Result<Option<SourceRef>, CoreError> {
1508 match &self.request {
1509 McpRequest::Registry(_) => Ok(None),
1510 McpRequest::Git(request) => match &request.source {
1511 Source::Git { url, .. } => SourceRef::from_git_url(url).map(Some),
1512 Source::Local(folder) => SourceRef::from_local_path(folder).map(Some),
1513 },
1514 }
1515 }
1516
1517 pub fn resolve(
1519 &self,
1520 store: Option<&Store<'_>>,
1521 sx: &SkillsEnv<'_>,
1522 ) -> Result<Resolved, CoreError> {
1523 match &self.request {
1524 McpRequest::Registry(request) => mcp_source::resolve_registry(store, sx, request),
1525 McpRequest::Git(request) => mcp_source::resolve(store, sx, request),
1526 }
1527 }
1528}
1529
1530fn plugin_url(catalog: &Catalog, source: &PluginSource) -> Result<String, CoreError> {
1533 match source.kind {
1534 PluginSourceKind::Relative => Ok(catalog.url.clone()),
1535 _ => source.url.clone().ok_or_else(|| {
1536 CoreError::new(ErrorCode::InvalidValue, "this plugin names no repository")
1537 }),
1538 }
1539}
1540
1541pub fn mcp_handoff(
1545 cx: &CatalogEnv<'_>,
1546 read: Option<&dyn StoreRead>,
1547 text: &str,
1548 version: Option<&str>,
1549) -> Result<McpHandoff, CoreError> {
1550 let parts = Parts::of(cx);
1551 let (catalog_id, entry_id) = parse_ref(text)?;
1552 let catalog = find(read, &catalog_id)?;
1553 if catalog.kind == CatalogKind::McpRegistry && version.is_some() {
1554 if !catalog.enabled {
1556 return Err(CoreError::new(
1557 ErrorCode::InvalidValue,
1558 format!("the catalog {catalog_id:?} is turned off"),
1559 ));
1560 }
1561 online(parts.fs, parts.home)?.gate(&catalog)?;
1562 let entry = registry::entry(parts.http, &catalog, &entry_id, version)?;
1563 return registry_handoff(&catalog, entry, true);
1564 }
1565 let (catalog, entry, _) = install_entry(&parts, read, text)?;
1566 match catalog.kind {
1567 CatalogKind::McpRegistry => registry_handoff(&catalog, entry, false),
1568 _ => {
1569 let source = match (&entry.kind, &entry.source) {
1570 (EntryKind::Plugin, Some(source)) if entry.install_mcp => source.clone(),
1571 (EntryKind::Skill, _) => {
1572 return Err(CoreError::new(
1573 ErrorCode::InvalidValue,
1574 format!(
1575 "{} is a skill: install it with `surject skills add {}`",
1576 entry.id,
1577 entry.reference()
1578 ),
1579 ));
1580 }
1581 _ => {
1582 return Err(CoreError::new(
1583 ErrorCode::InvalidValue,
1584 entry.problem.clone().unwrap_or_else(|| {
1585 format!("{} holds no MCP server Surjection imports", entry.id)
1586 }),
1587 ));
1588 }
1589 };
1590 let mut request = ResolveRequest::new(Source::Git {
1591 url: plugin_url(&catalog, &source)?,
1592 git_ref: None,
1593 path: None,
1594 });
1595 request.git_ref = version
1596 .map(str::to_owned)
1597 .or_else(|| source.sha.clone())
1598 .or_else(|| source.git_ref.clone());
1599 request.path.clone_from(&source.path);
1600 request.catalog = Some(format!("{}/{}", catalog.id, entry.id));
1601 request.mcp_servers.clone_from(&entry.mcp_servers);
1602 Ok(McpHandoff {
1603 entry,
1604 request: McpRequest::Git(request),
1605 })
1606 }
1607 }
1608}
1609
1610fn registry_handoff(
1611 catalog: &Catalog,
1612 entry: CatalogEntry,
1613 pinned: bool,
1614) -> Result<McpHandoff, CoreError> {
1615 if !entry.install_mcp {
1616 return Err(CoreError::new(
1617 ErrorCode::InvalidValue,
1618 entry
1619 .problem
1620 .clone()
1621 .unwrap_or_else(|| "this entry cannot be installed".to_owned()),
1622 ));
1623 }
1624 let server_json = entry.server_json.clone().ok_or_else(|| {
1625 CoreError::new(ErrorCode::InvalidValue, "the entry carries no server.json")
1626 })?;
1627 let version = entry
1628 .version
1629 .clone()
1630 .ok_or_else(|| CoreError::new(ErrorCode::InvalidValue, "the entry names no version"))?;
1631 Ok(McpHandoff {
1632 request: McpRequest::Registry(RegistryRequest {
1633 catalog: format!("{}/{}", catalog.id, entry.id),
1634 registry: catalog.url.clone(),
1635 name: entry.id.clone(),
1636 version,
1637 pinned,
1638 server_json,
1639 }),
1640 entry,
1641 })
1642}
1643
1644pub fn skill_request(
1648 cx: &CatalogEnv<'_>,
1649 read: Option<&dyn StoreRead>,
1650 text: &str,
1651 git_ref: Option<&str>,
1652 path: Option<&str>,
1653) -> Result<(InstallRequest, CatalogEntry), CoreError> {
1654 let parts = Parts::of(cx);
1655 let (catalog, entry, index) = install_entry(&parts, read, text)?;
1656 let catalog_ref = Some(format!("{}/{}", catalog.id, entry.id));
1657 if catalog.kind == CatalogKind::SkillsSh {
1658 if !entry.install_skill {
1659 return Err(CoreError::new(
1660 ErrorCode::InvalidValue,
1661 entry
1662 .problem
1663 .clone()
1664 .unwrap_or_else(|| skills_sh::WEBSITE_PROBLEM.to_owned()),
1665 ));
1666 }
1667 let mut request = skills_sh_request(&skills_sh::page_url(&catalog, &entry.id))
1668 .ok_or_else(|| not_in(&catalog, &entry.id))??;
1669 request.git_ref = git_ref.map(str::to_owned);
1670 request.path = path.map(str::to_owned);
1671 request.catalog = catalog_ref;
1672 return Ok((request, entry));
1673 }
1674 let pin = |entry: &CatalogEntry| -> Option<String> {
1675 if entry.pinned {
1676 entry.commit.clone()
1677 } else {
1678 entry.git_ref.clone()
1679 }
1680 };
1681 let (url, entry_ref, entry_path) = match entry.kind {
1682 EntryKind::Server => {
1683 return Err(CoreError::new(
1684 ErrorCode::InvalidValue,
1685 format!(
1686 "{} is an MCP server: add it with `surject server add --from {}`",
1687 entry.id,
1688 entry.reference()
1689 ),
1690 ));
1691 }
1692 EntryKind::Skill => (catalog.url.clone(), pin(&entry), entry.path.clone()),
1693 EntryKind::Plugin => {
1694 let source = entry
1695 .source
1696 .clone()
1697 .filter(|_| entry.install_skill)
1698 .ok_or_else(|| {
1699 CoreError::new(
1700 ErrorCode::InvalidValue,
1701 entry.problem.clone().unwrap_or_else(|| {
1702 format!("{} holds no skill Surjection installs", entry.id)
1703 }),
1704 )
1705 })?;
1706 let folder = match (source.kind, entry.skills.as_slice()) {
1707 (PluginSourceKind::Relative, _) if path.is_some() => None,
1708 (PluginSourceKind::Relative, [one]) => index
1709 .as_ref()
1710 .and_then(|index| index.entries.iter().find(|e| &e.id == one))
1711 .and_then(|skill| skill.path.clone()),
1712 (PluginSourceKind::Relative, many) => {
1713 return Err(CoreError::new(
1714 ErrorCode::InvalidValue,
1715 format!(
1716 "{} holds {} skills; install one of them: {}",
1717 entry.id,
1718 many.len(),
1719 many.iter()
1720 .map(|id| format!("{REF_PREFIX}{}/{id}", catalog.id))
1721 .collect::<Vec<_>>()
1722 .join(", ")
1723 ),
1724 ));
1725 }
1726 _ => source.path.clone(),
1727 };
1728 (
1729 plugin_url(&catalog, &source)?,
1730 source.sha.clone().or_else(|| source.git_ref.clone()),
1731 folder,
1732 )
1733 }
1734 };
1735 let mut request = InstallRequest::new(Source::Git {
1736 url,
1737 git_ref: None,
1738 path: None,
1739 });
1740 request.git_ref = git_ref.map(str::to_owned).or(entry_ref);
1741 request.path = path.map(str::to_owned).or(entry_path);
1742 request.catalog = catalog_ref;
1743 Ok((request, entry))
1744}
1745
1746pub fn skills_sh_request(text: &str) -> Option<Result<InstallRequest, CoreError>> {
1752 let url = url::Url::parse(text.trim()).ok()?;
1753 if !matches!(url.host_str(), Some("skills.sh" | "www.skills.sh")) {
1754 return None;
1755 }
1756 let parts: Vec<&str> = url
1757 .path_segments()
1758 .map(|segments| segments.filter(|s| !s.is_empty()).collect())
1759 .unwrap_or_default();
1760 let valid = |part: &str| {
1761 !part.is_empty()
1762 && part != "."
1763 && part != ".."
1764 && part
1765 .chars()
1766 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1767 };
1768 Some(match parts.as_slice() {
1769 ["site", domain, ..] => Err(CoreError::new(
1770 ErrorCode::InvalidValue,
1771 format!(
1772 "skills.sh lists this skill from {domain}, not from a GitHub repository; Surjection \
1773 installs skills.sh entries from GitHub repositories only"
1774 ),
1775 )),
1776 [owner, repo, rest @ ..]
1777 if valid(owner) && valid(repo) && rest.iter().all(|p| valid(p)) =>
1778 {
1779 let mut request = InstallRequest::new(Source::Git {
1780 url: format!("https://github.com/{owner}/{repo}"),
1781 git_ref: None,
1782 path: None,
1783 });
1784 request.skill = rest.first().map(|skill| (*skill).to_owned());
1785 Ok(request)
1786 }
1787 _ => Err(CoreError::new(
1788 ErrorCode::InvalidValue,
1789 "this skills.sh address names no skill (https://skills.sh/<owner>/<repo>/<skill>)",
1790 )),
1791 })
1792}
1793
1794pub(crate) fn registry_latest(
1799 read: &dyn StoreRead,
1800 sx: &SkillsEnv<'_>,
1801 source: &ServerSource,
1802) -> Result<RegistryRequest, CoreError> {
1803 require_online(sx.fs, sx.home)?;
1804 let missing = |what: &str| {
1805 CoreError::new(
1806 ErrorCode::MissingField,
1807 format!("the registry source has no {what}"),
1808 )
1809 };
1810 let reference = source
1811 .catalog
1812 .as_deref()
1813 .ok_or_else(|| missing("catalog"))?;
1814 let (catalog_id, name) = reference
1815 .split_once('/')
1816 .ok_or_else(|| missing("catalog entry"))?;
1817 let url = source.url.clone().ok_or_else(|| missing("url"))?;
1818 if let Some(problem) = registry_url_problem(&url) {
1819 return Err(CoreError::new(ErrorCode::InvalidValue, problem));
1820 }
1821 let catalog = find(Some(read), catalog_id)
1822 .ok()
1823 .filter(|catalog| catalog.kind == CatalogKind::McpRegistry && catalog.url == url)
1824 .ok_or_else(|| {
1825 CoreError::new(
1826 ErrorCode::NotFound,
1827 format!(
1828 "the catalog {catalog_id:?} is no longer in your catalogs at this address: \
1829 add it again to check for updates"
1830 ),
1831 )
1832 })?;
1833 if !catalog.enabled {
1834 return Err(CoreError::new(
1835 ErrorCode::InvalidValue,
1836 format!("the catalog {catalog_id:?} is turned off: turn it on to check for updates"),
1837 ));
1838 }
1839 online(sx.fs, sx.home)?.gate(&catalog)?;
1840 let http = UreqHttp::new(sx.env, HttpLimits::default());
1841 let entry = registry::entry(&http, &catalog, name, None)?;
1842 match registry_handoff(&catalog, entry, false)?.request {
1843 McpRequest::Registry(request) => Ok(request),
1844 McpRequest::Git(_) => unreachable!("a registry entry"),
1845 }
1846}