返回 CodeWhale
claude.rs
根目录 / crates / plugins / src / marketplace / parsers / claude.rs
1 //! Claude `.claude-plugin/marketplace.json` parser.
2 //!
3 //! Schema source: <https://code.claude.com/docs/en/plugin-marketplaces>
4 //!
5 //! Top level: `name` (kebab-case, required), `owner` (`{name`, `email?`,
6 //! `url?}`, required), `plugins[]` (required); optional `$schema`,
7 //! `description`, `version`, `metadata.pluginRoot`, `renames`.
8 //!
9 //! Plugin entry: `name` (kebab-case) and `source` (required). `source`
10 //! is either a `./`-relative string or an object tagged with its
11 //! `source` discriminator: `github` (`repo`, `ref?`, `sha?`), `url`
12 //! (`url`, `ref?`, `sha?`), `git-subdir` (`url`, `path`, `ref?`, `sha?`),
13 //! `npm` (`package`, `version?`, `registry?`), `archive` (`url`,
14 //! `sha256?`), `command` (`command`, `timeout?`, `mode?`). Optional
15 //! entry fields: `displayName`, `description`, `version`, `author`,
16 //! `homepage`, `repository`, `license`, `keywords`, `category`, `tags`,
17 //! `strict`, and component config (`skills`, `commands`, `agents`,
18 //! `hooks`, `mcpServers`, `lspServers`) which this parser counts for
19 //! display only.
20 //!
21 //! No invented `entries`, `npm_package`, or `download_url` fields exist
22 //! in this format and none are parsed.
23
24 use serde_json::Value;
25
26 use crate::agent_plugin::{is_standard_plugin_name, slugify_plugin_name};
27 use crate::manifest::PluginInventory;
28
29 use super::super::types::{
30 CatalogProvenance, CatalogTier, MarketplaceCandidate, MarketplaceCandidateId,
31 MarketplaceCatalog, MarketplaceDiagnostic, MarketplaceEntryKind, MarketplaceFormat,
32 MarketplaceInstallPlan, MarketplaceSourceSpec,
33 };
34 use super::{MarketplaceDocument, str_array_field, str_field, unknown_fields_warning};
35
36 const TOP_LEVEL_FIELDS: &[&str] = &[
37 "$schema",
38 "name",
39 "owner",
40 "plugins",
41 "description",
42 "version",
43 "metadata",
44 "renames",
45 "allowCrossMarketplaceDependenciesOn",
46 ];
47 const ENTRY_FIELDS: &[&str] = &[
48 "name",
49 "source",
50 "displayName",
51 "description",
52 "version",
53 "author",
54 "homepage",
55 "repository",
56 "license",
57 "keywords",
58 "category",
59 "tags",
60 "strict",
61 "relevance",
62 "defaultEnabled",
63 "skills",
64 "commands",
65 "agents",
66 "hooks",
67 "mcpServers",
68 "lspServers",
69 "metadata",
70 ];
71
72 pub fn parse_claude_catalog(document: MarketplaceDocument) -> MarketplaceCatalog {
73 let MarketplaceDocument {
74 catalog_id,
75 root,
76 base,
77 ..
78 } = document;
79 let mut diagnostics = Vec::new();
80
81 let Some(obj) = root.as_object() else {
82 return empty_catalog(
83 catalog_id,
84 base,
85 MarketplaceDiagnostic::error(
86 "NOT_AN_OBJECT",
87 "Claude marketplace must be a JSON object",
88 None,
89 None,
90 ),
91 );
92 };
93
94 if let Some(diag) = unknown_fields_warning(obj, TOP_LEVEL_FIELDS) {
95 diagnostics.push(diag);
96 }
97
98 let (name, bad_name) = str_field(obj, "name");
99 if let Some(diag) = bad_name {
100 diagnostics.push(diag);
101 }
102 let name = name
103 .map(ToString::to_string)
104 .unwrap_or_else(|| catalog_id.as_str().to_string());
105
106 let (description, bad_desc) = str_field(obj, "description");
107 if let Some(diag) = bad_desc {
108 diagnostics.push(diag);
109 }
110 let (version, bad_version) = str_field(obj, "version");
111 if let Some(diag) = bad_version {
112 diagnostics.push(diag);
113 }
114
115 // `owner` is a documented required object with `name` required.
116 let publisher = obj
117 .get("owner")
118 .and_then(|o| o.get("name"))
119 .and_then(|n| n.as_str());
120 if obj
121 .get("owner")
122 .is_some_and(|o| o.get("name").and_then(Value::as_str).is_none())
123 {
124 diagnostics.push(MarketplaceDiagnostic::warning(
125 "FIELD_TYPE",
126 "Claude `owner.name` is missing or not a string",
127 None,
128 None,
129 ));
130 }
131
132 let Some(entries) = obj.get("plugins").and_then(Value::as_array) else {
133 diagnostics.push(MarketplaceDiagnostic::error(
134 "MISSING_PLUGINS",
135 "Claude marketplace must contain a `plugins` array",
136 None,
137 None,
138 ));
139 return MarketplaceCatalog {
140 id: catalog_id,
141 format: MarketplaceFormat::Claude,
142 name,
143 display_name: None,
144 description: description.map(ToString::to_string),
145 version: version.map(ToString::to_string),
146 base,
147 provenance: CatalogProvenance::default(),
148 candidates: Vec::new(),
149 diagnostics,
150 };
151 };
152
153 let copilot_paths = base.as_deref().is_some_and(|file| {
154 let file = std::path::Path::new(file);
155 file.ends_with(".github/plugin/marketplace.json")
156 || file.ends_with(".plugin/marketplace.json")
157 });
158 let mut candidates = Vec::new();
159 for (index, entry) in entries.iter().enumerate() {
160 if let Some(candidate) = parse_claude_entry(
161 &catalog_id,
162 index,
163 entry,
164 publisher,
165 copilot_paths,
166 &mut diagnostics,
167 ) {
168 candidates.push(candidate);
169 }
170 }
171
172 MarketplaceCatalog {
173 id: catalog_id,
174 format: MarketplaceFormat::Claude,
175 name,
176 display_name: None,
177 description: description.map(ToString::to_string),
178 version: version.map(ToString::to_string),
179 base,
180 provenance: CatalogProvenance {
181 tier: CatalogTier::Community,
182 publisher: publisher.map(ToString::to_string),
183 source_url: None,
184 },
185 candidates,
186 diagnostics,
187 }
188 }
189
190 fn empty_catalog(
191 catalog_id: super::super::types::MarketplaceCatalogId,
192 base: Option<String>,
193 diagnostic: MarketplaceDiagnostic,
194 ) -> MarketplaceCatalog {
195 MarketplaceCatalog {
196 id: catalog_id,
197 format: MarketplaceFormat::Claude,
198 name: String::new(),
199 display_name: None,
200 description: None,
201 version: None,
202 base,
203 provenance: CatalogProvenance::default(),
204 candidates: Vec::new(),
205 diagnostics: vec![diagnostic],
206 }
207 }
208
209 fn parse_claude_entry(
210 catalog_id: &super::super::types::MarketplaceCatalogId,
211 index: usize,
212 entry: &Value,
213 catalog_publisher: Option<&str>,
214 copilot_paths: bool,
215 diagnostics: &mut Vec<MarketplaceDiagnostic>,
216 ) -> Option<MarketplaceCandidate> {
217 let Some(obj) = entry.as_object() else {
218 diagnostics.push(MarketplaceDiagnostic::error(
219 "MALFORMED_ENTRY",
220 format!("Claude plugin at index {index} must be a JSON object"),
221 None,
222 Some(index),
223 ));
224 return None;
225 };
226
227 let mut entry_diags = Vec::new();
228 if let Some(diag) = unknown_fields_warning(obj, ENTRY_FIELDS) {
229 entry_diags.push(diag);
230 }
231
232 let (raw_name, bad_name) = str_field(obj, "name");
233 if let Some(diag) = bad_name {
234 entry_diags.push(diag);
235 }
236 let Some(raw_name) = raw_name else {
237 diagnostics.push(MarketplaceDiagnostic::error(
238 "MISSING_NAME",
239 format!("Claude plugin at index {index} is missing required `name`"),
240 None,
241 Some(index),
242 ));
243 return None;
244 };
245 let (name, display_name) = if is_standard_plugin_name(raw_name) {
246 (raw_name.to_string(), None)
247 } else {
248 match slugify_plugin_name(raw_name) {
249 Ok(slug) => {
250 entry_diags.push(MarketplaceDiagnostic::warning(
251 "NON_STANDARD_NAME",
252 format!("Claude name `{raw_name}` normalized to `{slug}`"),
253 Some(slug.clone()),
254 Some(index),
255 ));
256 (slug, Some(raw_name.to_string()))
257 }
258 Err(err) => {
259 diagnostics.push(MarketplaceDiagnostic::error(
260 "INVALID_NAME",
261 format!("Claude name `{raw_name}` cannot be normalized: {err}"),
262 Some(raw_name.to_string()),
263 Some(index),
264 ));
265 return None;
266 }
267 }
268 };
269 let (explicit_display, bad_display) = str_field(obj, "displayName");
270 if let Some(diag) = bad_display {
271 entry_diags.push(diag);
272 }
273 let display_name = explicit_display.map(ToString::to_string).or(display_name);
274
275 let Some(source_value) = obj.get("source") else {
276 diagnostics.push(MarketplaceDiagnostic::error(
277 "MISSING_SOURCE",
278 format!("Claude plugin `{name}` is missing required `source`"),
279 Some(name.clone()),
280 Some(index),
281 ));
282 return None;
283 };
284 let (source, install_plan, source_diags) = normalize_claude_source(source_value, copilot_paths);
285 entry_diags.extend(source_diags);
286
287 let (description, bad_desc) = str_field(obj, "description");
288 if let Some(diag) = bad_desc {
289 entry_diags.push(diag);
290 }
291 let (version, bad_version) = str_field(obj, "version");
292 if let Some(diag) = bad_version {
293 entry_diags.push(diag);
294 }
295 let (homepage, bad_home) = str_field(obj, "homepage");
296 if let Some(diag) = bad_home {
297 entry_diags.push(diag);
298 }
299 let (repository, bad_repo) = str_field(obj, "repository");
300 if let Some(diag) = bad_repo {
301 entry_diags.push(diag);
302 }
303 let (license, bad_license) = str_field(obj, "license");
304 if let Some(diag) = bad_license {
305 entry_diags.push(diag);
306 }
307 let (keywords, bad_keywords) = str_array_field(obj, "keywords");
308 if let Some(diag) = bad_keywords {
309 entry_diags.push(diag);
310 }
311 let (tags, bad_tags) = str_array_field(obj, "tags");
312 if let Some(diag) = bad_tags {
313 entry_diags.push(diag);
314 }
315 let (category, bad_category) = str_field(obj, "category");
316 if let Some(diag) = bad_category {
317 entry_diags.push(diag);
318 }
319 let author = obj
320 .get("author")
321 .and_then(|a| a.get("name"))
322 .and_then(|n| n.as_str());
323
324 let (declared, component_diags) = count_declared_components(obj);
325 entry_diags.extend(component_diags);
326 let compatibility = declared.as_ref().map(super::declared_catalog_compatibility);
327
328 if obj.get("strict") == Some(&Value::Bool(false)) {
329 entry_diags.push(MarketplaceDiagnostic::warning(
330 "NON_STRICT_ENTRY",
331 format!("Claude plugin `{name}` sets strict=false; Codewhale always reviews the installed manifest"),
332 Some(name.clone()),
333 Some(index),
334 ));
335 }
336
337 Some(MarketplaceCandidate {
338 id: MarketplaceCandidateId::new(catalog_id, &name),
339 catalog_id: catalog_id.clone(),
340 kind: MarketplaceEntryKind::Plugin,
341 icon: None,
342 name,
343 display_name,
344 description: description.map(ToString::to_string),
345 version: version.map(ToString::to_string),
346 author: author
347 .map(ToString::to_string)
348 .or_else(|| catalog_publisher.map(ToString::to_string)),
349 homepage: homepage.map(ToString::to_string),
350 repository: repository.map(ToString::to_string),
351 license: license.map(ToString::to_string),
352 keywords,
353 categories: category
354 .map(|c| vec![c.to_string()])
355 .into_iter()
356 .flatten()
357 .chain(tags)
358 .collect(),
359 source,
360 install_plan,
361 declared_components: declared,
362 compatibility,
363 provenance: CatalogProvenance {
364 tier: CatalogTier::Community,
365 publisher: author
366 .map(ToString::to_string)
367 .or_else(|| catalog_publisher.map(ToString::to_string)),
368 source_url: None,
369 },
370 when: None,
371 diagnostics: entry_diags,
372 })
373 }
374
375 /// Claude documents per-entry component config arrays (`skills`,
376 /// `commands`, `agents`, `hooks`, `lspServers`) and an `mcpServers` map.
377 /// These are catalog-side declarations; Codewhale counts them for
378 /// display and compatibility only — the reviewed installed manifest
379 /// remains the authority.
380 fn count_declared_components(
381 obj: &serde_json::Map<String, Value>,
382 ) -> (Option<PluginInventory>, Vec<MarketplaceDiagnostic>) {
383 let has_any = [
384 "skills",
385 "commands",
386 "agents",
387 "hooks",
388 "mcpServers",
389 "lspServers",
390 ]
391 .iter()
392 .any(|k| obj.contains_key(*k));
393 if !has_any {
394 return (None, Vec::new());
395 }
396 let mut diags = Vec::new();
397 let count = |key: &str, diags: &mut Vec<MarketplaceDiagnostic>| -> usize {
398 match obj.get(key) {
399 None | Some(Value::Null) => 0,
400 Some(Value::Array(items)) => items.len(),
401 Some(other) => {
402 diags.push(MarketplaceDiagnostic::warning(
403 "FIELD_TYPE",
404 format!("`{key}` must be an array, got {};", json_kind(other)),
405 None,
406 None,
407 ));
408 0
409 }
410 }
411 };
412 let mcp_servers = match obj.get("mcpServers") {
413 None | Some(Value::Null) => 0,
414 Some(Value::Object(map)) => map.len(),
415 Some(other) => {
416 diags.push(MarketplaceDiagnostic::warning(
417 "FIELD_TYPE",
418 format!("`mcpServers` must be an object, got {}", json_kind(other)),
419 None,
420 None,
421 ));
422 0
423 }
424 };
425 (
426 Some(PluginInventory {
427 skills: count("skills", &mut diags),
428 mcp_servers,
429 stdio_mcp_servers: 0,
430 remote_mcp_servers: 0,
431 commands: count("commands", &mut diags),
432 agents: count("agents", &mut diags),
433 hooks: count("hooks", &mut diags),
434 lsp: count("lspServers", &mut diags),
435 native: 0,
436 providers: 0,
437 filesystem_roots: Vec::new(),
438 network_hosts: Vec::new(),
439 lifecycle_mutation: false,
440 host_services: Vec::new(),
441 }),
442 diags,
443 )
444 }
445
446 /// Normalize a documented Claude `source`. Only the six documented
447 /// discriminators plus the `./`-relative string form are accepted.
448 fn normalize_claude_source(
449 value: &Value,
450 copilot_paths: bool,
451 ) -> (
452 MarketplaceSourceSpec,
453 MarketplaceInstallPlan,
454 Vec<MarketplaceDiagnostic>,
455 ) {
456 let mut diags = Vec::new();
457 if let Some(s) = value.as_str() {
458 let relative = copilot_paths
459 && !s.is_empty()
460 && !s.contains([':', '\\'])
461 && std::path::Path::new(s).components().all(|part| {
462 matches!(
463 part,
464 std::path::Component::Normal(_) | std::path::Component::CurDir
465 )
466 });
467 if s.starts_with("./") || s == "." || relative {
468 return (
469 MarketplaceSourceSpec::LocalPath { path: s.into() },
470 MarketplaceInstallPlan::Supported {
471 spec: format!("path:{s}"),
472 source_kind: "Marketplace-relative directory".to_string(),
473 },
474 diags,
475 );
476 }
477 return (
478 MarketplaceSourceSpec::Invalid {
479 reason: format!("Claude string sources must be `./`-relative (got `{s}`)"),
480 },
481 MarketplaceInstallPlan::Unsupported {
482 reason: "Claude string sources must be `./`-relative paths".to_string(),
483 raw: s.to_string(),
484 },
485 diags,
486 );
487 }
488 let Some(obj) = value.as_object() else {
489 return (
490 MarketplaceSourceSpec::Invalid {
491 reason: "source must be a string or a tagged object".to_string(),
492 },
493 MarketplaceInstallPlan::Unsupported {
494 reason: "Claude source must be a `./` string or a `{source: ...}` object"
495 .to_string(),
496 raw: value.to_string(),
497 },
498 diags,
499 );
500 };
501 let discriminator = obj
502 .get("source")
503 .and_then(Value::as_str)
504 .unwrap_or_default();
505 let field = |name: &str| obj.get(name).and_then(Value::as_str);
506 match discriminator {
507 "github" => {
508 let Some(repo) = field("repo") else {
509 return invalid("github source requires `repo` (\"owner/repo\")", value, &mut diags);
510 };
511 let (owner, repo) = match repo.split_once('/') {
512 Some((o, r)) if !o.is_empty() && !r.is_empty() => (o, r),
513 _ => return invalid("github `repo` must be \"owner/repo\"", value, &mut diags),
514 };
515 super::github_source(value, owner, repo)
516 }
517 "url" | "git-subdir" => super::git_url_source(value),
518 "npm" => {
519 let Some(package) = field("package") else {
520 return invalid("npm source requires `package`", value, &mut diags);
521 };
522 (
523 MarketplaceSourceSpec::Npm { package: package.to_string() },
524 MarketplaceInstallPlan::Unsupported {
525 reason: "Codewhale does not execute npm; install the plugin from a GitHub repo, tarball, or local path".to_string(),
526 raw: value.to_string(),
527 },
528 diags,
529 )
530 }
531 "archive" => {
532 let Some(url) = field("url") else {
533 return invalid("archive source requires `url`", value, &mut diags);
534 };
535 let (spec, sha256) = match obj.get("sha256").filter(|pin| !pin.is_null()) {
536 None => (url.to_string(), None),
537 Some(pin) => match pin
538 .as_str()
539 .ok_or_else(|| "archive `sha256` must be a string".to_string())
540 .and_then(|pin| {
541 crate::install::PluginInstallSource::pin_archive_spec(url, pin)
542 })
543 {
544 Ok((spec, digest)) => (spec, Some(digest)),
545 Err(reason) => return invalid(&reason, value, &mut diags),
546 },
547 };
548 (
549 MarketplaceSourceSpec::ArchiveUrl { url: url.to_string(), sha256 },
550 MarketplaceInstallPlan::Supported {
551 spec,
552 source_kind: "Tarball archive URL".to_string(),
553 },
554 diags,
555 )
556 }
557 "command" => (
558 MarketplaceSourceSpec::Refused {
559 reason: "Claude `command` sources execute arbitrary shell commands and are never run by Codewhale".to_string(),
560 },
561 MarketplaceInstallPlan::Unsupported {
562 reason: "command sources are never executed".to_string(),
563 raw: value.to_string(),
564 },
565 diags,
566 ),
567 other => invalid(
568 &format!("unknown Claude source discriminator `{other}`"),
569 value,
570 &mut diags,
571 ),
572 }
573 }
574
575 fn invalid(
576 reason: &str,
577 value: &Value,
578 diags: &mut Vec<MarketplaceDiagnostic>,
579 ) -> (
580 MarketplaceSourceSpec,
581 MarketplaceInstallPlan,
582 Vec<MarketplaceDiagnostic>,
583 ) {
584 diags.push(MarketplaceDiagnostic::error(
585 "INVALID_SOURCE",
586 reason.to_string(),
587 None,
588 None,
589 ));
590 (
591 MarketplaceSourceSpec::Invalid {
592 reason: reason.to_string(),
593 },
594 MarketplaceInstallPlan::Unsupported {
595 reason: reason.to_string(),
596 raw: value.to_string(),
597 },
598 std::mem::take(diags),
599 )
600 }
601
602 fn json_kind(value: &Value) -> &'static str {
603 match value {
604 Value::Null => "null",
605 Value::Bool(_) => "a boolean",
606 Value::Number(_) => "a number",
607 Value::String(_) => "a string",
608 Value::Array(_) => "an array",
609 Value::Object(_) => "an object",
610 }
611 }
612
612 lines RUST