1use std::collections::BTreeMap;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use crate::error::ErrorCode;
12use crate::model::validate::{Diagnostics, join};
13use crate::model::{SCHEMA_VERSION, StoreModel};
14
15pub const BUILTIN_IDS: [&str; 3] = ["mcp-registry", "anthropic-skills", "skills-sh"];
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
20#[serde(rename_all = "snake_case")]
21pub enum CatalogSourceKind {
22 McpRegistry,
24 GitTap,
27}
28
29impl CatalogSourceKind {
30 pub const fn as_str(self) -> &'static str {
31 match self {
32 CatalogSourceKind::McpRegistry => "mcp_registry",
33 CatalogSourceKind::GitTap => "git_tap",
34 }
35 }
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
41pub struct CatalogRecord {
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub kind: Option<CatalogSourceKind>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub url: Option<String>,
49 #[serde(rename = "ref", default, skip_serializing_if = "Option::is_none")]
51 pub git_ref: Option<String>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub title: Option<String>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub enabled: Option<bool>,
58 #[serde(flatten)]
59 #[schemars(skip)]
60 pub extra: toml::Table,
61}
62
63impl CatalogRecord {
64 pub fn switch(enabled: bool) -> Self {
66 Self {
67 kind: None,
68 url: None,
69 git_ref: None,
70 title: None,
71 enabled: Some(enabled),
72 extra: toml::Table::new(),
73 }
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
78#[schemars(title = "Surjection catalogs (store/catalogs.toml)")]
79pub struct CatalogsFile {
80 #[schemars(extend("const" = 1))]
82 pub schema: i64,
83 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
85 pub catalogs: BTreeMap<String, CatalogRecord>,
86 #[serde(flatten)]
87 #[schemars(skip)]
88 pub extra: toml::Table,
89}
90
91impl StoreModel for CatalogsFile {
92 const SCHEMA_NAME: &'static str = "catalogs";
93}
94
95impl Default for CatalogsFile {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101pub fn is_catalog_id(id: &str) -> bool {
104 (1..=64).contains(&id.len())
105 && id.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit())
106 && id
107 .bytes()
108 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
109}
110
111pub fn registry_url_problem(url: &str) -> Option<String> {
114 let Ok(parsed) = url::Url::parse(url) else {
115 return Some(format!("{url:?} is not a URL"));
116 };
117 let loopback = matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
118 match parsed.scheme() {
119 "https" => {}
120 "http" if loopback => {}
121 "http" => {
122 return Some("a registry URL must use https (http only for localhost)".to_owned());
123 }
124 _ => return Some(format!("{url:?} is not an https URL")),
125 }
126 if parsed.host_str().is_none_or(str::is_empty) {
127 return Some(format!("{url:?} has no host"));
128 }
129 if !parsed.username().is_empty() || parsed.password().is_some() {
130 return Some("a registry URL must not hold a user name or password".to_owned());
131 }
132 if parsed.query().is_some() || parsed.fragment().is_some() {
133 return Some("a registry URL must not hold a query or fragment".to_owned());
134 }
135 None
136}
137
138pub fn tap_url_problem(url: &str) -> Option<String> {
142 let parsed = url::Url::parse(url.trim()).ok()?;
143 let web = matches!(parsed.scheme(), "http" | "https");
144 if parsed.password().is_some() || (web && !parsed.username().is_empty()) {
145 return Some(
146 "a tap URL must not hold a user name, password or token (it would be saved in your \
147 store): use your git credential helper instead"
148 .to_owned(),
149 );
150 }
151 None
152}
153
154impl CatalogsFile {
155 pub fn new() -> Self {
156 Self {
157 schema: SCHEMA_VERSION,
158 catalogs: BTreeMap::new(),
159 extra: toml::Table::new(),
160 }
161 }
162
163 pub fn validate(&self) -> Diagnostics {
167 let mut d = Diagnostics::new();
168 for (id, record) in &self.catalogs {
169 let path = join("catalogs", id);
170 if !is_catalog_id(id) {
171 d.error(
172 ErrorCode::InvalidValue,
173 &path,
174 format!(
175 "{id:?} is not a catalog id (1 to 64 characters of a-z, 0-9, '.', '_', '-', \
176 starting with a letter or digit)"
177 ),
178 );
179 continue;
180 }
181 if BUILTIN_IDS.contains(&id.as_str()) {
182 let extra = [
183 ("kind", record.kind.is_some()),
184 ("url", record.url.is_some()),
185 ("ref", record.git_ref.is_some()),
186 ("title", record.title.is_some()),
187 ];
188 for (key, set) in extra {
189 if set {
190 d.error(
191 ErrorCode::FieldNotAllowed,
192 join(&path, key),
193 format!("{id:?} is a built-in catalog: only `enabled` can be set"),
194 );
195 }
196 }
197 continue;
198 }
199 let Some(kind) = record.kind else {
200 d.error(
201 ErrorCode::MissingField,
202 join(&path, "kind"),
203 "a catalog needs its kind (mcp_registry or git_tap)",
204 );
205 continue;
206 };
207 let Some(url) = record.url.as_deref().filter(|url| !url.is_empty()) else {
208 d.error(
209 ErrorCode::MissingField,
210 join(&path, "url"),
211 "a catalog needs its url",
212 );
213 continue;
214 };
215 match kind {
216 CatalogSourceKind::McpRegistry => {
217 if let Some(problem) = registry_url_problem(url) {
218 d.error(ErrorCode::InvalidValue, join(&path, "url"), problem);
219 }
220 if record.git_ref.is_some() {
221 d.error(
222 ErrorCode::FieldNotAllowed,
223 join(&path, "ref"),
224 "only a git tap has a ref",
225 );
226 }
227 }
228 CatalogSourceKind::GitTap => {
229 if let Some(problem) = tap_url_problem(url) {
230 d.error(ErrorCode::InvalidValue, join(&path, "url"), problem);
231 } else if let Err(err) = crate::sources::SourceRef::from_git_url(url) {
232 d.error(ErrorCode::InvalidValue, join(&path, "url"), err.message());
233 }
234 if let Some(git_ref) = &record.git_ref
235 && let Err(err) = crate::skills::install::check_ref(git_ref)
236 {
237 d.error(ErrorCode::InvalidValue, join(&path, "ref"), err.message());
238 }
239 }
240 }
241 }
242 d
243 }
244}