返回 CodeWhale
agent_plugin.rs
根目录 / crates / plugins / src / agent_plugin.rs
1 //! Agent Plugins v1.0.0 (agent-plugins.org) format support.
2 //!
3 //! The standard is a vendor-neutral packaging format: a `plugin.json` manifest
4 //! with a closed root (`$schema`, `name`, and the optional well-known fields;
5 //! everything client-specific lives under `extensions`, keyed by reverse-domain
6 //! namespace), a sibling `mcp.json` for MCP servers (the manifest root is
7 //! closed, so servers cannot live in `plugin.json`), and a `skills/<name>/
8 //! SKILL.md` tree that already matches Codewhale's skill layout.
9 //!
10 //! This module owns the mapping between that format and Codewhale's internal
11 //! [`PluginManifest`]:
12 //!
13 //! * **Consume** — [`parse_plugin_json`] + [`standard_to_manifest`] and
14 //! [`parse_mcp_json`]. Unknown `extensions` namespaces are ignored, never
15 //! rejected: that is what lets a Cursor- or Copilot-authored plugin load
16 //! here. Codewhale-specific fields round-trip through
17 //! `extensions["net.codewhale"]`.
18 //! * **Publish** — [`manifest_to_standard`], emitting a spec-valid
19 //! `plugin.json` (+ `mcp.json` when servers exist). [`validate_plugin_json`]
20 //! and [`validate_mcp_json`] re-check every emission against the standard's
21 //! shape before it is written, so upstream drift fails here rather than
22 //! shipping.
23 //! * **Names** — the standard's name rule
24 //! (`^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$`, 1–64 chars) is
25 //! [`is_standard_plugin_name`]; [`slugify_plugin_name`] maps a legacy name
26 //! onto it. A slugified name that collides with an existing plugin is an
27 //! error, never a silent rename.
28 //!
29 //! Auto-migration of on-disk `plugin.toml` files is deliberately **not**
30 //! implemented here; this module only converts representations.
31
32 use std::collections::{BTreeMap, BTreeSet, HashMap};
33 use std::path::{Path, PathBuf};
34
35 use serde::{Deserialize, Serialize};
36
37 use super::manifest::{
38 CURRENT_SCHEMA_VERSION, MAX_PLUGIN_NAME_CHARS, PluginCapabilities, PluginManifest, PluginMeta,
39 PluginPathSpec, PluginWhen,
40 };
41 use codewhale_mcp::config::{McpServerConfig, McpServerOAuthConfig};
42
43 /// Manifest file names, in discovery preference order. `plugin.json` is the
44 /// native Agent Plugins format; `plugin.toml` is the legacy Codewhale format
45 /// and stays readable.
46 pub const PLUGIN_JSON_NAME: &str = "plugin.json";
47 pub const PLUGIN_TOML_NAME: &str = "plugin.toml";
48 /// Kimi Code's native plugin manifest. Codewhale consumes the compatible
49 /// Skills and MCP subset directly so official Kimi bundles do not need to be
50 /// rewritten or copied by hand before installation.
51 pub const KIMI_PLUGIN_JSON_NAME: &str = "kimi.plugin.json";
52 /// Sibling file carrying MCP server definitions for a `plugin.json` bundle.
53 pub const MCP_JSON_NAME: &str = "mcp.json";
54
55 /// `$schema` values emitted for the v1.0.0 documents.
56 pub const PLUGIN_SCHEMA_URL: &str = "https://agent-plugins.org/schemas/plugin.json";
57 pub const MCP_SCHEMA_URL: &str = "https://agent-plugins.org/schemas/mcp.json";
58
59 /// Codewhale's reverse-domain extension namespace.
60 pub const CODEWHALE_NAMESPACE: &str = "net.codewhale";
61
62 /// `env` keys a plugin may never define: the host runtime owns these.
63 const RESERVED_MCP_ENV_NAMES: [&str; 2] = ["PLUGIN_ROOT", "PLUGIN_DATA"];
64
65 /// The standard's name rule: lowercase ASCII letters/digits with internal
66 /// single hyphens or dots, starting and ending alphanumeric, never containing
67 /// `--` or `..`, 1–64 chars. Equivalent to
68 /// `^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$`.
69 #[must_use]
70 pub fn is_standard_plugin_name(name: &str) -> bool {
71 let count = name.chars().count();
72 if count == 0 || count > MAX_PLUGIN_NAME_CHARS {
73 return false;
74 }
75 if name.contains("--") || name.contains("..") {
76 return false;
77 }
78 let alphanumeric = |ch: char| ch.is_ascii_lowercase() || ch.is_ascii_digit();
79 name.chars().next().is_some_and(alphanumeric)
80 && name.chars().next_back().is_some_and(alphanumeric)
81 && name
82 .chars()
83 .all(|ch| alphanumeric(ch) || ch == '-' || ch == '.')
84 }
85
86 /// Map an arbitrary legacy plugin name onto the standard's name rule.
87 ///
88 /// Letters are ASCII-lowercased; every maximal run of non-conforming
89 /// characters collapses to one separator (`.` when the run is dots only, `-`
90 /// otherwise), leading/trailing separators are dropped, and the result is
91 /// truncated to 64 chars. Errors when nothing usable remains — slugification
92 /// never invents a name.
93 pub fn slugify_plugin_name(name: &str) -> Result<String, String> {
94 let mut slug = String::new();
95 let mut pending_separator: Option<char> = None;
96 for ch in name.chars() {
97 if ch.is_ascii_alphanumeric() {
98 if let Some(separator) = pending_separator.take()
99 && !slug.is_empty()
100 {
101 slug.push(separator);
102 }
103 slug.push(ch.to_ascii_lowercase());
104 } else {
105 let separator = if ch == '.' { '.' } else { '-' };
106 pending_separator = Some(match (pending_separator, separator) {
107 (Some('.'), '.') => '.',
108 (None, sep) => sep,
109 // Any run touching a hyphen (or mixing separators) is a hyphen.
110 _ => '-',
111 });
112 }
113 }
114 while slug.chars().count() > MAX_PLUGIN_NAME_CHARS {
115 slug.pop();
116 }
117 while slug.ends_with(['-', '.']) {
118 slug.pop();
119 }
120 if slug.is_empty() {
121 return Err(format!(
122 "plugin name `{name}` cannot be slugified: it contains no ASCII letters or digits"
123 ));
124 }
125 debug_assert!(is_standard_plugin_name(&slug));
126 Ok(slug)
127 }
128
129 const LEGACY_METADATA_MANIFESTS: [&str; 3] = [
130 ".claude-plugin/plugin.json",
131 ".plugin/plugin.json",
132 ".github/plugin/plugin.json",
133 ];
134
135 /// Locate the manifest of a bundle directory: `plugin.json` when present,
136 /// otherwise a legacy `plugin.toml`. A bundle shipping both (dual-publish for
137 /// older clients) is read through its `plugin.json`.
138 #[must_use]
139 pub fn resolve_manifest_path(root: &Path) -> Option<PathBuf> {
140 let json = root.join(PLUGIN_JSON_NAME);
141 if json.is_file() {
142 return Some(json);
143 }
144 let kimi_json = root.join(KIMI_PLUGIN_JSON_NAME);
145 if kimi_json.is_file() {
146 return Some(kimi_json);
147 }
148 let toml = root.join(PLUGIN_TOML_NAME);
149 if toml.is_file() {
150 return Some(toml);
151 }
152 LEGACY_METADATA_MANIFESTS
153 .iter()
154 .map(|suffix| root.join(suffix))
155 .find(|path| path.is_file())
156 }
157
158 pub fn plugin_root_for_manifest(path: &Path) -> Option<&Path> {
159 if let Some(suffix) = LEGACY_METADATA_MANIFESTS
160 .iter()
161 .find(|suffix| path.ends_with(suffix))
162 {
163 path.ancestors().nth(Path::new(suffix).components().count())
164 } else {
165 path.parent()
166 }
167 }
168
169 /// Claude's skills/commands/agents/MCP subset uses the existing declarative
170 /// adapters. Unsupported components fail validation; no hooks are silently lost.
171 pub fn parse_claude_plugin_json(
172 text: &str,
173 root: &Path,
174 mcp_bytes: Option<&[u8]>,
175 ) -> Result<PluginManifest, String> {
176 let mut value: serde_json::Value = serde_json::from_str(text)
177 .map_err(|error| format!("invalid Claude plugin.json: {error}"))?;
178 let object = value
179 .as_object_mut()
180 .ok_or("Claude plugin.json must be an object")?;
181 for component in [
182 "hooks/hooks.json",
183 "hooks.json",
184 ".lsp.json",
185 "lsp.json",
186 ".github/lsp.json",
187 "lsp-config/servers.json",
188 ".github/mcp.json",
189 ] {
190 if root.join(component).exists() {
191 return Err(format!(
192 "Claude component {component} is not supported by this importer; no partial plugin will be installed"
193 ));
194 }
195 }
196
197 // Reuse the compatible, closed metadata/component schema. Claude's
198 // default component directories are additive to explicit paths.
199 for component in ["skills", "commands", "agents"] {
200 if root.join(component).is_dir() {
201 let mut paths = match object.remove(component) {
202 Some(value) => {
203 let spec = serde_json::from_value::<KimiPathSpec>(value)
204 .map_err(|error| format!("invalid Claude {component} paths: {error}"))?
205 .into_plugin_path_spec()?;
206 spec.path.into_iter().chain(spec.paths).collect::<Vec<_>>()
207 }
208 None => Vec::new(),
209 };
210 if !paths.iter().any(|path| {
211 path.strip_prefix("./")
212 .unwrap_or(path)
213 .trim_end_matches('/')
214 == component
215 }) {
216 paths.push(component.to_string());
217 }
218 object.insert(component.to_string(), serde_json::json!(paths));
219 }
220 }
221 let mut servers = match object.remove("mcpServers") {
222 Some(serde_json::Value::Object(map)) => map,
223 Some(_) => return Err("Claude mcpServers must be an inline server object; custom MCP file paths are not supported".to_string()),
224 None => serde_json::Map::new(),
225 };
226 if let Some(bytes) = mcp_bytes {
227 let mut file: serde_json::Value =
228 serde_json::from_slice(bytes).map_err(|error| format!("invalid .mcp.json: {error}"))?;
229 let map = file.as_object_mut().ok_or(".mcp.json must be an object")?;
230 let entries = if let Some(wrapped) = map.remove("mcpServers") {
231 map.remove("$schema");
232 if !map.is_empty() {
233 return Err("unsupported .mcp.json wrapper fields".to_string());
234 }
235 wrapped
236 .as_object()
237 .cloned()
238 .ok_or(".mcp.json mcpServers must be an object")?
239 } else {
240 std::mem::take(map)
241 };
242 for (name, server) in entries {
243 if servers.insert(name.clone(), server).is_some() {
244 return Err(format!(
245 "MCP server {name} is declared in both plugin.json and .mcp.json"
246 ));
247 }
248 }
249 }
250 for (name, server) in &mut servers {
251 if server.get("type").and_then(serde_json::Value::as_str) == Some("http") {
252 server["type"] = serde_json::json!("streamable-http");
253 }
254 let definition = server.to_string();
255 if [
256 "${CLAUDE_PLUGIN_ROOT}",
257 "${COPILOT_PLUGIN_ROOT}",
258 "${PLUGIN_ROOT}",
259 "${COPILOT_PLUGIN_DATA}",
260 "${CLAUDE_PLUGIN_DATA}",
261 "${PLUGIN_DATA}",
262 ]
263 .iter()
264 .any(|token| definition.contains(token))
265 {
266 return Err(format!(
267 "MCP server {name} uses unsupported plugin root or data expansion; use bundle-relative command paths"
268 ));
269 }
270 }
271 object.insert("mcpServers".to_string(), serde_json::Value::Object(servers));
272 let mut manifest = parse_kimi_plugin_json(&value.to_string(), root)
273 .map_err(|error| error.replace("kimi.plugin.json", "Claude plugin.json"))?;
274 // Official Claude bundles express credential sources as header templates.
275 // Translate only exact environment references into the existing reviewed
276 // credential contract. Never expand credentials while importing a bundle.
277 if let Some(servers) = &mut manifest.mcp_servers {
278 for (name, server) in servers {
279 for (header, value) in std::mem::take(&mut server.headers) {
280 let authorization = header.eq_ignore_ascii_case("authorization");
281 if server
282 .env_headers
283 .keys()
284 .any(|key| key.eq_ignore_ascii_case(&header))
285 || (authorization && server.bearer_token_env_var.is_some())
286 {
287 return Err(format!(
288 "MCP server {name} has duplicate credential sources for header {header}"
289 ));
290 }
291 if authorization
292 && let Some(source) = value
293 .strip_prefix("Bearer ")
294 .and_then(super::manifest::exact_environment_placeholder)
295 {
296 server.bearer_token_env_var = Some(source.to_string());
297 } else if let Some(source) = super::manifest::exact_environment_placeholder(&value)
298 {
299 server.env_headers.insert(header, source.to_string());
300 } else {
301 return Err(format!(
302 "MCP server {name} header {header} must use an exact environment reference; literal or compound header values are not supported"
303 ));
304 }
305 }
306 }
307 }
308 Ok(manifest)
309 }
310
311 // ─────────────────────────────────────────────────────────────────────────────
312 // Kimi Code compatibility
313 // ─────────────────────────────────────────────────────────────────────────────
314
315 #[derive(Debug, Clone, Deserialize)]
316 #[serde(deny_unknown_fields)]
317 struct KimiPluginManifest {
318 #[serde(rename = "$schema", default)]
319 schema: Option<String>,
320 name: String,
321 #[serde(default)]
322 version: Option<String>,
323 #[serde(default)]
324 description: Option<String>,
325 #[serde(default)]
326 keywords: Vec<String>,
327 #[serde(default)]
328 author: Option<KimiAuthor>,
329 #[serde(default)]
330 homepage: Option<String>,
331 #[serde(default)]
332 repository: Option<String>,
333 #[serde(default)]
334 license: Option<String>,
335 #[serde(default)]
336 skills: Option<KimiPathSpec>,
337 #[serde(default)]
338 commands: Option<KimiPathSpec>,
339 #[serde(default)]
340 agents: Option<KimiPathSpec>,
341 #[serde(rename = "mcpServers", default)]
342 mcp_servers: BTreeMap<String, KimiMcpServer>,
343 #[serde(rename = "interface", default)]
344 interface_metadata: Option<KimiInterface>,
345 }
346
347 #[derive(Debug, Clone, Deserialize)]
348 #[serde(untagged)]
349 enum KimiAuthor {
350 Text(String),
351 Detailed(StandardAuthor),
352 }
353
354 #[derive(Debug, Clone, Deserialize)]
355 #[serde(untagged)]
356 enum KimiPathSpec {
357 One(String),
358 Many(Vec<String>),
359 }
360
361 impl KimiPathSpec {
362 fn into_plugin_path_spec(self) -> Result<PluginPathSpec, String> {
363 match self {
364 Self::One(path) => Ok(PluginPathSpec {
365 path: Some(path),
366 paths: Vec::new(),
367 }),
368 Self::Many(paths) if paths.is_empty() => {
369 Err("Kimi plugin component path list must not be empty".to_string())
370 }
371 Self::Many(paths) => Ok(PluginPathSpec { path: None, paths }),
372 }
373 }
374 }
375
376 #[derive(Debug, Clone, Default, Deserialize)]
377 #[serde(deny_unknown_fields)]
378 struct KimiInterface {
379 #[serde(rename = "displayName", default)]
380 display_name: Option<String>,
381 #[serde(rename = "shortDescription", default)]
382 _short_description: Option<String>,
383 #[serde(rename = "longDescription", default)]
384 _long_description: Option<String>,
385 #[serde(rename = "developerName", default)]
386 _developer_name: Option<String>,
387 #[serde(rename = "websiteURL", default)]
388 _website_url: Option<String>,
389 #[serde(rename = "iconUrl", default)]
390 _icon_url: Option<String>,
391 #[serde(rename = "category", default)]
392 _category: Option<String>,
393 #[serde(rename = "hostKind", default)]
394 host_kind: Option<String>,
395 #[serde(default)]
396 platforms: Vec<String>,
397 #[serde(rename = "mcpOverrides", default)]
398 mcp_overrides: BTreeMap<String, KimiMcpInterfaceOverride>,
399 }
400
401 #[derive(Debug, Clone, Default, Deserialize)]
402 #[serde(deny_unknown_fields)]
403 struct KimiMcpInterfaceOverride {
404 #[serde(rename = "displayName", default)]
405 _display_name: Option<String>,
406 #[serde(rename = "iconUrl", default)]
407 _icon_url: Option<String>,
408 }
409
410 /// Kimi's MCP shape is the standard MCP server entry plus a top-level
411 /// `enabledTools` allow-list. Keeping this as a separate closed type prevents
412 /// Kimi-only fields from weakening the Agent Plugins `mcp.json` parser.
413 #[derive(Debug, Clone, Default, Deserialize)]
414 #[serde(deny_unknown_fields)]
415 struct KimiMcpServer {
416 #[serde(rename = "type", default)]
417 transport: Option<String>,
418 #[serde(default)]
419 command: Option<String>,
420 #[serde(default)]
421 args: Vec<String>,
422 #[serde(default)]
423 env: BTreeMap<String, String>,
424 #[serde(default)]
425 cwd: Option<String>,
426 #[serde(default)]
427 url: Option<String>,
428 #[serde(default)]
429 headers: BTreeMap<String, String>,
430 #[serde(default)]
431 extensions: BTreeMap<String, serde_json::Value>,
432 #[serde(rename = "enabledTools", default)]
433 enabled_tools: Vec<String>,
434 }
435
436 impl KimiMcpServer {
437 fn into_config(self, id: &str) -> Result<McpServerConfig, String> {
438 let enabled_tools = self.enabled_tools;
439 let standard = StandardMcpServer {
440 transport: self.transport,
441 command: self.command,
442 args: self.args,
443 env: self.env,
444 cwd: self.cwd,
445 url: self.url,
446 headers: self.headers,
447 extensions: self.extensions,
448 };
449 let mut config = standard_server_to_config(id, standard)?;
450 if !enabled_tools.is_empty() {
451 if !config.enabled_tools.is_empty() && config.enabled_tools != enabled_tools {
452 return Err(format!(
453 "kimi.plugin.json MCP server `{id}` declares conflicting enabledTools filters"
454 ));
455 }
456 config.enabled_tools = enabled_tools;
457 }
458 Ok(config)
459 }
460 }
461
462 /// Parse the Skills/MCP-compatible subset of a Kimi Code plugin manifest.
463 ///
464 /// The input shape is deliberately closed. Kimi capabilities Codewhale does
465 /// not yet implement (for example lifecycle hooks or prompt injection) fail
466 /// validation instead of being silently dropped and then presented as fully
467 /// working. In addition to the Skills-only official bundles, this accepts the
468 /// known Kimi-managed CU shape: display/platform interface metadata and MCP
469 /// `enabledTools`. External applications, daemons, binaries, and permissions
470 /// are prerequisites outside this parser and are never implied to exist.
471 pub fn parse_kimi_plugin_json(text: &str, root: &Path) -> Result<PluginManifest, String> {
472 let kimi: KimiPluginManifest = serde_json::from_str(text)
473 .map_err(|error| format!("failed to parse kimi.plugin.json: {error}"))?;
474 if let Some(schema) = kimi.schema.as_deref()
475 && schema.trim().is_empty()
476 {
477 return Err("kimi.plugin.json `$schema` must be a non-empty string".to_string());
478 }
479 if !is_kimi_plugin_name(&kimi.name) {
480 return Err(format!(
481 "kimi.plugin.json name `{}` is invalid (1-{MAX_PLUGIN_NAME_CHARS} lowercase ASCII letters, digits, hyphens, or underscores; must start with a letter or digit)",
482 kimi.name
483 ));
484 }
485
486 let skills = match kimi.skills {
487 Some(paths) => Some(paths.into_plugin_path_spec()?),
488 None if root.join("SKILL.md").is_file() => Some(PluginPathSpec {
489 path: Some(".".to_string()),
490 paths: Vec::new(),
491 }),
492 None => None,
493 };
494 let commands = kimi
495 .commands
496 .map(KimiPathSpec::into_plugin_path_spec)
497 .transpose()?;
498 let agents = kimi
499 .agents
500 .map(KimiPathSpec::into_plugin_path_spec)
501 .transpose()?;
502
503 let mut mcp_servers = HashMap::with_capacity(kimi.mcp_servers.len());
504 for (id, server) in kimi.mcp_servers {
505 mcp_servers.insert(id.clone(), server.into_config(&id)?);
506 }
507 let mut network_hosts = mcp_servers
508 .values()
509 .filter_map(|server| server.url.as_deref())
510 .filter_map(|url| reqwest::Url::parse(url).ok())
511 .filter_map(|url| url.host_str().map(str::to_ascii_lowercase))
512 .collect::<Vec<_>>();
513 network_hosts.sort();
514 network_hosts.dedup();
515
516 let author = match kimi.author {
517 Some(KimiAuthor::Text(author)) => Some(author),
518 Some(KimiAuthor::Detailed(author)) => Some(compose_author(author)?),
519 None => None,
520 };
521 let (display_name, when) = match kimi.interface_metadata {
522 Some(interface) => {
523 if let Some(host_kind) = interface.host_kind.as_deref()
524 && !host_kind.eq_ignore_ascii_case("local")
525 {
526 return Err(format!(
527 "kimi.plugin.json interface hostKind `{host_kind}` is unsupported; only `local` is understood"
528 ));
529 }
530 if interface
531 .mcp_overrides
532 .keys()
533 .any(|key| key.trim().is_empty())
534 {
535 return Err(
536 "kimi.plugin.json interface mcpOverrides keys must not be empty".to_string(),
537 );
538 }
539 let mut platforms = Vec::with_capacity(interface.platforms.len());
540 let mut seen = BTreeSet::new();
541 const SUPPORTED_PLATFORMS: &[&str] = &[
542 "windows", "linux", "macos", "freebsd", "openbsd", "netbsd", "android", "ios",
543 ];
544 for platform in interface.platforms {
545 let platform = platform.trim().to_ascii_lowercase();
546 if !SUPPORTED_PLATFORMS.contains(&platform.as_str()) {
547 return Err(format!(
548 "kimi.plugin.json interface has unsupported platform `{platform}`"
549 ));
550 }
551 if !seen.insert(platform.clone()) {
552 return Err(format!(
553 "kimi.plugin.json interface repeats platform `{platform}`"
554 ));
555 }
556 platforms.push(platform);
557 }
558 let when = (!platforms.is_empty()).then_some(PluginWhen {
559 os: Some(platforms),
560 binaries: None,
561 });
562 (interface.display_name, when)
563 }
564 None => (None, None),
565 };
566
567 Ok(PluginManifest {
568 schema_version: CURRENT_SCHEMA_VERSION,
569 plugin: PluginMeta {
570 name: kimi.name,
571 description: kimi.description,
572 version: kimi.version.unwrap_or_else(|| "0.0.0".to_string()),
573 author,
574 homepage: kimi.homepage,
575 repository: kimi.repository,
576 license: kimi.license,
577 keywords: kimi.keywords,
578 display_name,
579 icon: None,
580 },
581 skills,
582 commands,
583 agents,
584 hooks: None,
585 lsp: None,
586 native: None,
587 providers: BTreeMap::new(),
588 mcp_servers: (!mcp_servers.is_empty()).then_some(mcp_servers),
589 capabilities: PluginCapabilities {
590 network_hosts,
591 ..PluginCapabilities::default()
592 },
593 when,
594 })
595 }
596
597 #[must_use]
598 pub fn is_kimi_plugin_name(name: &str) -> bool {
599 let count = name.chars().count();
600 count > 0
601 && count <= MAX_PLUGIN_NAME_CHARS
602 && name
603 .chars()
604 .next()
605 .is_some_and(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit())
606 && name
607 .chars()
608 .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '-' | '_'))
609 }
610
611 // ─────────────────────────────────────────────────────────────────────────────
612 // Standard document shapes
613 // ─────────────────────────────────────────────────────────────────────────────
614
615 /// `plugin.json` per Agent Plugins v1.0.0. The root is closed
616 /// (`additionalProperties: false`); client-specific data belongs under
617 /// `extensions`, keyed by reverse-domain namespace.
618 #[derive(Debug, Clone, Deserialize, Serialize)]
619 #[serde(deny_unknown_fields)]
620 pub struct StandardPluginManifest {
621 #[serde(rename = "$schema")]
622 pub schema: String,
623 pub name: String,
624 #[serde(default, skip_serializing_if = "Option::is_none")]
625 pub version: Option<String>,
626 #[serde(default, skip_serializing_if = "Option::is_none")]
627 pub description: Option<String>,
628 #[serde(default, skip_serializing_if = "Option::is_none")]
629 pub author: Option<StandardAuthor>,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
631 pub homepage: Option<String>,
632 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub repository: Option<String>,
634 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub license: Option<String>,
636 #[serde(default, skip_serializing_if = "Vec::is_empty")]
637 pub keywords: Vec<String>,
638 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
639 pub extensions: BTreeMap<String, serde_json::Value>,
640 }
641
642 #[derive(Debug, Clone, Deserialize, Serialize)]
643 #[serde(deny_unknown_fields)]
644 pub struct StandardAuthor {
645 pub name: String,
646 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub email: Option<String>,
648 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub url: Option<String>,
650 }
651
652 /// Codewhale's own `extensions["net.codewhale"]` payload: every manifest
653 /// concept the standard does not define. Unknown keys inside our own namespace
654 /// are rejected (`deny_unknown_fields`) — the ignore-unknowns rule applies to
655 /// *other* vendors' namespaces, not to a silently dropped Codewhale field.
656 #[derive(Debug, Clone, Default, Deserialize, Serialize)]
657 #[serde(deny_unknown_fields)]
658 pub struct CodewhalePluginExtension {
659 #[serde(default, skip_serializing_if = "Option::is_none")]
660 pub display_name: Option<String>,
661 #[serde(default, skip_serializing_if = "Option::is_none")]
662 pub icon: Option<String>,
663 #[serde(default, skip_serializing_if = "Option::is_none")]
664 pub skills: Option<PluginPathSpec>,
665 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub commands: Option<PluginPathSpec>,
667 #[serde(default, skip_serializing_if = "Option::is_none")]
668 pub agents: Option<PluginPathSpec>,
669 #[serde(default, skip_serializing_if = "Option::is_none")]
670 pub hooks: Option<PluginPathSpec>,
671 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub lsp: Option<PluginPathSpec>,
673 #[serde(default, skip_serializing_if = "Option::is_none")]
674 pub native: Option<PluginPathSpec>,
675 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
676 pub providers: BTreeMap<String, super::providers::PluginProviderDeclaration>,
677 #[serde(default, skip_serializing_if = "Option::is_none")]
678 pub capabilities: Option<PluginCapabilities>,
679 #[serde(default, skip_serializing_if = "Option::is_none")]
680 pub when: Option<PluginWhen>,
681 }
682
683 impl CodewhalePluginExtension {
684 #[must_use]
685 fn is_empty(&self) -> bool {
686 self.display_name.is_none()
687 && self.icon.is_none()
688 && self.skills.is_none()
689 && self.commands.is_none()
690 && self.agents.is_none()
691 && self.hooks.is_none()
692 && self.lsp.is_none()
693 && self.native.is_none()
694 && self.providers.is_empty()
695 && self.capabilities.is_none()
696 && self.when.is_none()
697 }
698 }
699
700 /// `mcp.json` per Agent Plugins v1.0.0: `$schema` plus `mcpServers` keyed by
701 /// server id.
702 #[derive(Debug, Clone, Deserialize, Serialize)]
703 #[serde(deny_unknown_fields)]
704 pub struct StandardMcpFile {
705 #[serde(rename = "$schema", default, skip_serializing_if = "Option::is_none")]
706 pub schema: Option<String>,
707 #[serde(rename = "mcpServers")]
708 pub servers: BTreeMap<String, StandardMcpServer>,
709 }
710
711 /// One `mcp.json` server entry. Transports: `stdio` (command/args/env/cwd),
712 /// `streamable-http` (url/headers), and `sse` (url/headers). `type` may be
713 /// omitted and is then inferred from `command` vs `url`. Codewhale-only
714 /// server options ride in `extensions["net.codewhale"]`.
715 #[derive(Debug, Clone, Default, Deserialize, Serialize)]
716 #[serde(deny_unknown_fields)]
717 pub struct StandardMcpServer {
718 #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
719 pub transport: Option<String>,
720 #[serde(default, skip_serializing_if = "Option::is_none")]
721 pub command: Option<String>,
722 #[serde(default, skip_serializing_if = "Vec::is_empty")]
723 pub args: Vec<String>,
724 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
725 pub env: BTreeMap<String, String>,
726 #[serde(default, skip_serializing_if = "Option::is_none")]
727 pub cwd: Option<String>,
728 #[serde(default, skip_serializing_if = "Option::is_none")]
729 pub url: Option<String>,
730 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
731 pub headers: BTreeMap<String, String>,
732 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
733 pub extensions: BTreeMap<String, serde_json::Value>,
734 }
735
736 /// Codewhale-only MCP server options, carried per-server under
737 /// `extensions["net.codewhale"]` in `mcp.json` so the standard fields round-
738 /// trip losslessly with Codewhale's richer review model (timeouts, tool
739 /// filters, env-backed credentials, enablement).
740 #[derive(Debug, Clone, Default, Deserialize, Serialize)]
741 #[serde(deny_unknown_fields)]
742 pub struct CodewhaleMcpExtension {
743 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
744 pub env_headers: BTreeMap<String, String>,
745 #[serde(default, skip_serializing_if = "Option::is_none")]
746 pub bearer_token_env_var: Option<String>,
747 #[serde(default, skip_serializing_if = "Option::is_none")]
748 pub connect_timeout: Option<u64>,
749 #[serde(default, skip_serializing_if = "Option::is_none")]
750 pub execute_timeout: Option<u64>,
751 #[serde(default, skip_serializing_if = "Option::is_none")]
752 pub read_timeout: Option<u64>,
753 #[serde(default, skip_serializing_if = "Option::is_none")]
754 pub enabled: Option<bool>,
755 #[serde(default, skip_serializing_if = "Option::is_none")]
756 pub disabled: Option<bool>,
757 #[serde(default, skip_serializing_if = "Option::is_none")]
758 pub required: Option<bool>,
759 #[serde(default, skip_serializing_if = "Vec::is_empty")]
760 pub enabled_tools: Vec<String>,
761 #[serde(default, skip_serializing_if = "Vec::is_empty")]
762 pub disabled_tools: Vec<String>,
763 #[serde(default, skip_serializing_if = "Vec::is_empty")]
764 pub scopes: Vec<String>,
765 #[serde(default, skip_serializing_if = "Option::is_none")]
766 pub oauth: Option<McpServerOAuthConfig>,
767 #[serde(default, skip_serializing_if = "Option::is_none")]
768 pub oauth_resource: Option<String>,
769 }
770
771 impl CodewhaleMcpExtension {
772 #[must_use]
773 fn is_empty(&self) -> bool {
774 self.env_headers.is_empty()
775 && self.bearer_token_env_var.is_none()
776 && self.connect_timeout.is_none()
777 && self.execute_timeout.is_none()
778 && self.read_timeout.is_none()
779 && self.enabled.is_none()
780 && self.disabled.is_none()
781 && self.required.is_none()
782 && self.enabled_tools.is_empty()
783 && self.disabled_tools.is_empty()
784 && self.scopes.is_empty()
785 && self.oauth.is_none()
786 && self.oauth_resource.is_none()
787 }
788 }
789
790 // ─────────────────────────────────────────────────────────────────────────────
791 // Consume: standard documents -> internal manifest
792 // ─────────────────────────────────────────────────────────────────────────────
793
794 /// Parse a `plugin.json` document. Unknown root keys are rejected (the
795 /// standard's root is closed); unknown `extensions` namespaces parse fine and
796 /// are dropped by [`standard_to_manifest`].
797 pub fn parse_plugin_json(text: &str) -> Result<StandardPluginManifest, String> {
798 let manifest: StandardPluginManifest = serde_json::from_str(text)
799 .map_err(|error| format!("failed to parse plugin.json: {error}"))?;
800 if manifest.schema.trim().is_empty() {
801 return Err("plugin.json `$schema` must be a non-empty string".to_string());
802 }
803 if !is_standard_plugin_name(&manifest.name) {
804 return Err(format!(
805 "plugin.json name `{}` is invalid under the Agent Plugins standard (1-{MAX_PLUGIN_NAME_CHARS} lowercase ASCII letters, digits, or internal single `-`/`.`; never `--` or `..`)",
806 manifest.name
807 ));
808 }
809 Ok(manifest)
810 }
811
812 /// Parse an `mcp.json` document into internal server configs, enforcing the
813 /// per-transport shapes and the reserved `env` names.
814 pub fn parse_mcp_json(text: &str) -> Result<HashMap<String, McpServerConfig>, String> {
815 let file: StandardMcpFile =
816 serde_json::from_str(text).map_err(|error| format!("failed to parse mcp.json: {error}"))?;
817 let mut servers = HashMap::with_capacity(file.servers.len());
818 for (id, server) in file.servers {
819 servers.insert(id.clone(), standard_server_to_config(&id, server)?);
820 }
821 Ok(servers)
822 }
823
824 fn standard_server_to_config(
825 id: &str,
826 server: StandardMcpServer,
827 ) -> Result<McpServerConfig, String> {
828 let extension = codewhale_mcp_extension(&server.extensions)?;
829 let transport = resolve_transport(id, &server)?;
830 let (command, url, sse) = match transport {
831 StandardTransport::Stdio => {
832 let command = server.command.clone().ok_or_else(|| {
833 format!("mcp.json server `{id}` declares stdio transport without a command")
834 })?;
835 if server.url.is_some() || !server.headers.is_empty() {
836 return Err(format!(
837 "mcp.json stdio server `{id}` may not declare url or headers"
838 ));
839 }
840 for key in server.env.keys() {
841 if RESERVED_MCP_ENV_NAMES.contains(&key.as_str()) {
842 return Err(format!(
843 "mcp.json server `{id}` env may not define reserved name `{key}`"
844 ));
845 }
846 }
847 (Some(command), None, false)
848 }
849 StandardTransport::StreamableHttp | StandardTransport::Sse => {
850 let url = server.url.clone().ok_or_else(|| {
851 format!("mcp.json server `{id}` declares an HTTP transport without a url")
852 })?;
853 if server.command.is_some()
854 || !server.args.is_empty()
855 || !server.env.is_empty()
856 || server.cwd.is_some()
857 {
858 return Err(format!(
859 "mcp.json HTTP server `{id}` may not declare command, args, env, or cwd"
860 ));
861 }
862 (None, Some(url), transport == StandardTransport::Sse)
863 }
864 };
865 Ok(McpServerConfig {
866 command,
867 args: server.args,
868 env: server.env.into_iter().collect(),
869 cwd: server.cwd.map(PathBuf::from),
870 url,
871 transport: sse.then(|| "sse".to_string()),
872 connect_timeout: extension.connect_timeout,
873 execute_timeout: extension.execute_timeout,
874 read_timeout: extension.read_timeout,
875 disabled: extension.disabled.unwrap_or(false),
876 enabled: extension.enabled.unwrap_or(true),
877 required: extension.required.unwrap_or(false),
878 lazy: false,
879 enabled_tools: extension.enabled_tools,
880 disabled_tools: extension.disabled_tools,
881 always_allow_tools: Vec::new(),
882 headers: server.headers.into_iter().collect(),
883 env_headers: extension.env_headers.into_iter().collect(),
884 bearer_token_env_var: extension.bearer_token_env_var,
885 scopes: extension.scopes,
886 oauth: extension.oauth,
887 oauth_resource: extension.oauth_resource,
888 reviewed_plugin: None,
889 runtime_added: false,
890 allow_private_network: false,
891 })
892 }
893
894 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
895 enum StandardTransport {
896 Stdio,
897 StreamableHttp,
898 Sse,
899 }
900
901 fn resolve_transport(id: &str, server: &StandardMcpServer) -> Result<StandardTransport, String> {
902 match server.transport.as_deref() {
903 Some(declared) => match declared.to_ascii_lowercase().as_str() {
904 "stdio" => Ok(StandardTransport::Stdio),
905 "streamable-http" => Ok(StandardTransport::StreamableHttp),
906 "sse" => Ok(StandardTransport::Sse),
907 _ => Err(format!(
908 "mcp.json server `{id}` has unknown type `{declared}`; expected `stdio`, `streamable-http`, or `sse`"
909 )),
910 },
911 None => match (server.command.is_some(), server.url.is_some()) {
912 (true, false) => Ok(StandardTransport::Stdio),
913 (false, true) => Ok(StandardTransport::StreamableHttp),
914 _ => Err(format!(
915 "mcp.json server `{id}` must declare exactly one of command or url, or set an explicit type"
916 )),
917 },
918 }
919 }
920
921 fn codewhale_mcp_extension(
922 extensions: &BTreeMap<String, serde_json::Value>,
923 ) -> Result<CodewhaleMcpExtension, String> {
924 match extensions.get(CODEWHALE_NAMESPACE) {
925 Some(value) => serde_json::from_value(value.clone()).map_err(|error| {
926 format!("mcp.json server extensions[\"{CODEWHALE_NAMESPACE}\"] is invalid: {error}")
927 }),
928 None => Ok(CodewhaleMcpExtension::default()),
929 }
930 }
931
932 /// Convert a parsed `plugin.json` (+ its sibling `mcp.json` servers, when the
933 /// file exists) into the internal manifest. `root` is the bundle directory:
934 /// the standard fixes the skills layout at `skills/`, so a bundle with no
935 /// Codewhale extension gets the default skills spec exactly when that
936 /// directory exists.
937 pub fn standard_to_manifest(
938 standard: StandardPluginManifest,
939 mcp_servers: Option<HashMap<String, McpServerConfig>>,
940 root: &Path,
941 ) -> Result<PluginManifest, String> {
942 let extension = match standard.extensions.get(CODEWHALE_NAMESPACE) {
943 Some(value) => {
944 serde_json::from_value::<CodewhalePluginExtension>(value.clone()).map_err(|error| {
945 format!("plugin.json extensions[\"{CODEWHALE_NAMESPACE}\"] is invalid: {error}")
946 })?
947 }
948 None => CodewhalePluginExtension::default(),
949 };
950 let skills = extension.skills.or_else(|| {
951 root.join("skills").is_dir().then(|| PluginPathSpec {
952 path: Some("skills".to_string()),
953 paths: Vec::new(),
954 })
955 });
956 Ok(PluginManifest {
957 schema_version: CURRENT_SCHEMA_VERSION,
958 plugin: PluginMeta {
959 name: standard.name,
960 description: standard.description,
961 version: standard.version.unwrap_or_else(|| "0.0.0".to_string()),
962 author: standard.author.map(compose_author).transpose()?,
963 homepage: standard.homepage,
964 repository: standard.repository,
965 license: standard.license,
966 keywords: standard.keywords,
967 display_name: extension.display_name,
968 icon: extension.icon,
969 },
970 skills,
971 commands: extension.commands,
972 agents: extension.agents,
973 hooks: extension.hooks,
974 lsp: extension.lsp,
975 native: extension.native,
976 providers: extension.providers,
977 mcp_servers,
978 capabilities: extension.capabilities.unwrap_or_default(),
979 when: extension.when,
980 })
981 }
982
983 /// `author: {name, email, url}` flattens onto the internal free-form author
984 /// string (`name <email> (url)`). The inverse mapping keeps the whole string
985 /// in `author.name`, so a Codewhale-origin author round-trips verbatim.
986 fn compose_author(author: StandardAuthor) -> Result<String, String> {
987 let name = author.name.trim();
988 if name.is_empty() {
989 return Err("plugin.json author.name must be a non-empty string".to_string());
990 }
991 let mut composed = name.to_string();
992 if let Some(email) = author
993 .email
994 .as_deref()
995 .filter(|email| !email.trim().is_empty())
996 {
997 composed.push_str(" <");
998 composed.push_str(email.trim());
999 composed.push('>');
1000 }
1001 if let Some(url) = author.url.as_deref().filter(|url| !url.trim().is_empty()) {
1002 composed.push_str(" (");
1003 composed.push_str(url.trim());
1004 composed.push(')');
1005 }
1006 Ok(composed)
1007 }
1008
1009 // ─────────────────────────────────────────────────────────────────────────────
1010 // Publish: internal manifest -> standard documents
1011 // ─────────────────────────────────────────────────────────────────────────────
1012
1013 /// The spec-valid documents for one plugin, ready to serialize and write.
1014 #[derive(Debug, Clone)]
1015 pub struct StandardEmission {
1016 pub plugin_json: StandardPluginManifest,
1017 /// Present exactly when the plugin declares MCP servers.
1018 pub mcp_json: Option<StandardMcpFile>,
1019 /// The conforming name the bundle is published under.
1020 pub exported_name: String,
1021 /// The original name, preserved when publishing required slugification (or
1022 /// when an imported bundle already carried one).
1023 pub display_name: Option<String>,
1024 }
1025
1026 /// Convert an internal manifest into spec-valid documents.
1027 ///
1028 /// A name that is invalid under the standard is slugified and the original is
1029 /// preserved as the display name. `existing_names` must hold every other
1030 /// plugin name in scope: a slugified name colliding with an existing plugin is
1031 /// an error, never a silent rename.
1032 pub fn manifest_to_standard(
1033 manifest: &PluginManifest,
1034 existing_names: &BTreeSet<String>,
1035 ) -> Result<StandardEmission, String> {
1036 let original = manifest.plugin.name.as_str();
1037 let (name, renamed) = if is_standard_plugin_name(original) {
1038 (original.to_string(), false)
1039 } else {
1040 (slugify_plugin_name(original)?, true)
1041 };
1042 if renamed && existing_names.contains(&name) {
1043 return Err(format!(
1044 "slugifying plugin `{original}` yields `{name}`, which collides with an existing plugin; rename one of them first"
1045 ));
1046 }
1047 let display_name = if renamed {
1048 Some(original.to_string())
1049 } else {
1050 manifest.plugin.display_name.clone()
1051 };
1052
1053 let extension = CodewhalePluginExtension {
1054 display_name: display_name.clone(),
1055 icon: manifest.plugin.icon.clone(),
1056 skills: manifest
1057 .skills
1058 .clone()
1059 .filter(|spec| !is_default_skills_spec(spec)),
1060 commands: manifest.commands.clone(),
1061 agents: manifest.agents.clone(),
1062 hooks: manifest.hooks.clone(),
1063 lsp: manifest.lsp.clone(),
1064 native: manifest.native.clone(),
1065 providers: manifest.providers.clone(),
1066 capabilities: (!capabilities_are_default(&manifest.capabilities))
1067 .then(|| manifest.capabilities.clone()),
1068 when: manifest.when.clone(),
1069 };
1070
1071 let plugin_json = StandardPluginManifest {
1072 schema: PLUGIN_SCHEMA_URL.to_string(),
1073 name: name.clone(),
1074 version: Some(manifest.plugin.version.clone()).filter(|version| !version.trim().is_empty()),
1075 description: manifest.plugin.description.clone(),
1076 author: manifest.plugin.author.clone().map(|author| StandardAuthor {
1077 name: author,
1078 email: None,
1079 url: None,
1080 }),
1081 homepage: manifest.plugin.homepage.clone(),
1082 repository: manifest.plugin.repository.clone(),
1083 license: manifest.plugin.license.clone(),
1084 keywords: manifest.plugin.keywords.clone(),
1085 extensions: if extension.is_empty() {
1086 BTreeMap::new()
1087 } else {
1088 let value = serde_json::to_value(&extension)
1089 .map_err(|error| format!("failed to encode Codewhale extension: {error}"))?;
1090 BTreeMap::from([(CODEWHALE_NAMESPACE.to_string(), value)])
1091 },
1092 };
1093
1094 let mcp_json = match &manifest.mcp_servers {
1095 Some(servers) if !servers.is_empty() => {
1096 let mut standard_servers = BTreeMap::new();
1097 for (id, config) in servers {
1098 standard_servers.insert(id.clone(), config_to_standard_server(id, config)?);
1099 }
1100 Some(StandardMcpFile {
1101 schema: Some(MCP_SCHEMA_URL.to_string()),
1102 servers: standard_servers,
1103 })
1104 }
1105 _ => None,
1106 };
1107
1108 Ok(StandardEmission {
1109 plugin_json,
1110 mcp_json,
1111 exported_name: name,
1112 display_name,
1113 })
1114 }
1115
1116 /// The standard fixes the skills tree at `skills/`; this spec (or its absence)
1117 /// needs no extension entry.
1118 #[must_use]
1119 pub fn is_default_skills_spec(spec: &PluginPathSpec) -> bool {
1120 let mut declared = spec.path.iter().chain(spec.paths.iter());
1121 declared.next().is_some_and(|path| path == "skills") && declared.next().is_none()
1122 }
1123
1124 fn capabilities_are_default(capabilities: &PluginCapabilities) -> bool {
1125 capabilities.filesystem_roots.is_empty()
1126 && capabilities.network_hosts.is_empty()
1127 && !capabilities.lifecycle_mutation
1128 && capabilities.host_services.is_empty()
1129 }
1130
1131 fn config_to_standard_server(
1132 id: &str,
1133 config: &McpServerConfig,
1134 ) -> Result<StandardMcpServer, String> {
1135 let extension = CodewhaleMcpExtension {
1136 env_headers: config
1137 .env_headers
1138 .iter()
1139 .map(|(k, v)| (k.clone(), v.clone()))
1140 .collect(),
1141 bearer_token_env_var: config.bearer_token_env_var.clone(),
1142 connect_timeout: config.connect_timeout,
1143 execute_timeout: config.execute_timeout,
1144 read_timeout: config.read_timeout,
1145 enabled: (!config.enabled).then_some(false),
1146 disabled: config.disabled.then_some(true),
1147 required: config.required.then_some(true),
1148 enabled_tools: config.enabled_tools.clone(),
1149 disabled_tools: config.disabled_tools.clone(),
1150 scopes: config.scopes.clone(),
1151 oauth: config.oauth.clone(),
1152 oauth_resource: config.oauth_resource.clone(),
1153 };
1154 let extensions = if extension.is_empty() {
1155 BTreeMap::new()
1156 } else {
1157 let value = serde_json::to_value(&extension)
1158 .map_err(|error| format!("failed to encode Codewhale MCP extension: {error}"))?;
1159 BTreeMap::from([(CODEWHALE_NAMESPACE.to_string(), value)])
1160 };
1161 match (config.command.as_deref(), config.url.as_deref()) {
1162 (Some(command), None) => {
1163 for key in config.env.keys() {
1164 if RESERVED_MCP_ENV_NAMES.contains(&key.as_str()) {
1165 return Err(format!(
1166 "MCP server `{id}` env may not define reserved name `{key}`"
1167 ));
1168 }
1169 }
1170 Ok(StandardMcpServer {
1171 transport: Some("stdio".to_string()),
1172 command: Some(command.to_string()),
1173 args: config.args.clone(),
1174 env: config
1175 .env
1176 .iter()
1177 .map(|(k, v)| (k.clone(), v.clone()))
1178 .collect(),
1179 cwd: config
1180 .cwd
1181 .as_ref()
1182 .map(|cwd| cwd.to_string_lossy().into_owned()),
1183 url: None,
1184 headers: BTreeMap::new(),
1185 extensions,
1186 })
1187 }
1188 (None, Some(url)) => {
1189 let sse = config
1190 .transport
1191 .as_deref()
1192 .is_some_and(|transport| transport.eq_ignore_ascii_case("sse"));
1193 Ok(StandardMcpServer {
1194 transport: Some(if sse { "sse" } else { "streamable-http" }.to_string()),
1195 command: None,
1196 args: Vec::new(),
1197 env: BTreeMap::new(),
1198 cwd: None,
1199 url: Some(url.to_string()),
1200 headers: config
1201 .headers
1202 .iter()
1203 .map(|(k, v)| (k.clone(), v.clone()))
1204 .collect(),
1205 extensions,
1206 })
1207 }
1208 _ => Err(format!(
1209 "MCP server `{id}` must declare exactly one of command or url to export"
1210 )),
1211 }
1212 }
1213
1214 // ─────────────────────────────────────────────────────────────────────────────
1215 // Emission conformance checks
1216 // ─────────────────────────────────────────────────────────────────────────────
1217 //
1218 // Every document Codewhale writes is re-validated against the standard's shape
1219 // before it hits disk; the same functions back the schema-conformance tests.
1220
1221 /// Validate a serialized `plugin.json` value against the standard's shape:
1222 /// closed root, required `$schema`/`name`, typed optional fields, and the name
1223 /// rule.
1224 pub fn validate_plugin_json(value: &serde_json::Value) -> Result<(), String> {
1225 const ROOT_KEYS: [&str; 10] = [
1226 "$schema",
1227 "name",
1228 "version",
1229 "description",
1230 "author",
1231 "homepage",
1232 "repository",
1233 "license",
1234 "keywords",
1235 "extensions",
1236 ];
1237 let object = value
1238 .as_object()
1239 .ok_or_else(|| "plugin.json must be a JSON object".to_string())?;
1240 for key in object.keys() {
1241 if !ROOT_KEYS.contains(&key.as_str()) {
1242 return Err(format!(
1243 "plugin.json root key `{key}` is not in the closed schema"
1244 ));
1245 }
1246 }
1247 let schema = required_string(object, "$schema")?;
1248 if schema.trim().is_empty() {
1249 return Err("plugin.json `$schema` must be a non-empty string".to_string());
1250 }
1251 let name = required_string(object, "name")?;
1252 if !is_standard_plugin_name(name) {
1253 return Err(format!(
1254 "plugin.json name `{name}` violates the standard's name rule"
1255 ));
1256 }
1257 for key in [
1258 "version",
1259 "description",
1260 "homepage",
1261 "repository",
1262 "license",
1263 ] {
1264 optional_string(object, key)?;
1265 }
1266 if let Some(author) = object.get("author") {
1267 let author = author
1268 .as_object()
1269 .ok_or_else(|| "plugin.json author must be an object".to_string())?;
1270 for key in author.keys() {
1271 if !["name", "email", "url"].contains(&key.as_str()) {
1272 return Err(format!(
1273 "plugin.json author key `{key}` is not in the schema"
1274 ));
1275 }
1276 }
1277 required_string(author, "name")?;
1278 optional_string(author, "email")?;
1279 optional_string(author, "url")?;
1280 }
1281 if let Some(keywords) = object.get("keywords") {
1282 let keywords = keywords
1283 .as_array()
1284 .ok_or_else(|| "plugin.json keywords must be an array of strings".to_string())?;
1285 if keywords.iter().any(|keyword| !keyword.is_string()) {
1286 return Err("plugin.json keywords must be an array of strings".to_string());
1287 }
1288 }
1289 if let Some(extensions) = object.get("extensions")
1290 && !extensions.is_object()
1291 {
1292 return Err("plugin.json extensions must be an object keyed by namespace".to_string());
1293 }
1294 Ok(())
1295 }
1296
1297 /// Validate a serialized `mcp.json` value against the standard's shape:
1298 /// `$schema` + `mcpServers`, the per-transport field sets, and the reserved
1299 /// `env` names.
1300 pub fn validate_mcp_json(value: &serde_json::Value) -> Result<(), String> {
1301 let object = value
1302 .as_object()
1303 .ok_or_else(|| "mcp.json must be a JSON object".to_string())?;
1304 for key in object.keys() {
1305 if !["$schema", "mcpServers"].contains(&key.as_str()) {
1306 return Err(format!(
1307 "mcp.json root key `{key}` is not in the closed schema"
1308 ));
1309 }
1310 }
1311 if let Some(schema) = object.get("$schema")
1312 && !schema.is_string()
1313 {
1314 return Err("mcp.json `$schema` must be a string".to_string());
1315 }
1316 let servers = object
1317 .get("mcpServers")
1318 .and_then(serde_json::Value::as_object)
1319 .ok_or_else(|| "mcp.json must carry an `mcpServers` object".to_string())?;
1320 for (id, server) in servers {
1321 validate_mcp_server_json(id, server)?;
1322 }
1323 Ok(())
1324 }
1325
1326 fn validate_mcp_server_json(id: &str, server: &serde_json::Value) -> Result<(), String> {
1327 const SERVER_KEYS: [&str; 8] = [
1328 "type",
1329 "command",
1330 "args",
1331 "env",
1332 "cwd",
1333 "url",
1334 "headers",
1335 "extensions",
1336 ];
1337 let object = server
1338 .as_object()
1339 .ok_or_else(|| format!("mcp.json server `{id}` must be an object"))?;
1340 for key in object.keys() {
1341 if !SERVER_KEYS.contains(&key.as_str()) {
1342 return Err(format!(
1343 "mcp.json server `{id}` key `{key}` is not in the closed schema"
1344 ));
1345 }
1346 }
1347 let transport = match object.get("type") {
1348 Some(value) => {
1349 let declared = value
1350 .as_str()
1351 .ok_or_else(|| format!("mcp.json server `{id}` type must be a string"))?;
1352 if !["stdio", "streamable-http", "sse"].contains(&declared) {
1353 return Err(format!(
1354 "mcp.json server `{id}` has unknown type `{declared}`"
1355 ));
1356 }
1357 Some(declared)
1358 }
1359 None => None,
1360 };
1361 for key in ["command", "cwd", "url"] {
1362 optional_string(object, key).map_err(|error| format!("mcp.json server `{id}`: {error}"))?;
1363 }
1364 if let Some(values) = object.get("args") {
1365 let values = values
1366 .as_array()
1367 .ok_or_else(|| format!("mcp.json server `{id}` args must be an array of strings"))?;
1368 if values.iter().any(|value| !value.is_string()) {
1369 return Err(format!(
1370 "mcp.json server `{id}` args must be an array of strings"
1371 ));
1372 }
1373 }
1374 for key in ["env", "headers"] {
1375 if let Some(values) = object.get(key) {
1376 let values = values
1377 .as_object()
1378 .ok_or_else(|| format!("mcp.json server `{id}` {key} must be a string map"))?;
1379 if values.values().any(|value| !value.is_string()) {
1380 return Err(format!("mcp.json server `{id}` {key} must be a string map"));
1381 }
1382 }
1383 }
1384 if let Some(env) = object.get("env").and_then(serde_json::Value::as_object) {
1385 for key in env.keys() {
1386 if RESERVED_MCP_ENV_NAMES.contains(&key.as_str()) {
1387 return Err(format!(
1388 "mcp.json server `{id}` env may not define reserved name `{key}`"
1389 ));
1390 }
1391 }
1392 }
1393 if let Some(extensions) = object.get("extensions")
1394 && !extensions.is_object()
1395 {
1396 return Err(format!(
1397 "mcp.json server `{id}` extensions must be an object"
1398 ));
1399 }
1400 let has_command = object.contains_key("command");
1401 let has_url = object.contains_key("url");
1402 let stdio_fields_empty = !has_command
1403 && !object.contains_key("args")
1404 && !object.contains_key("env")
1405 && !object.contains_key("cwd");
1406 let inferred = match transport {
1407 Some(declared) => declared,
1408 None if has_command && !has_url => "stdio",
1409 None if has_url && !has_command => "streamable-http",
1410 None => {
1411 return Err(format!(
1412 "mcp.json server `{id}` must declare exactly one of command or url, or set an explicit type"
1413 ));
1414 }
1415 };
1416 match inferred {
1417 "stdio" => {
1418 if !has_command {
1419 return Err(format!(
1420 "mcp.json stdio server `{id}` must declare a command"
1421 ));
1422 }
1423 if has_url || object.contains_key("headers") {
1424 return Err(format!(
1425 "mcp.json stdio server `{id}` may not declare url or headers"
1426 ));
1427 }
1428 }
1429 _ => {
1430 if !has_url {
1431 return Err(format!("mcp.json HTTP server `{id}` must declare a url"));
1432 }
1433 if !stdio_fields_empty {
1434 return Err(format!(
1435 "mcp.json HTTP server `{id}` may not declare command, args, env, or cwd"
1436 ));
1437 }
1438 }
1439 }
1440 Ok(())
1441 }
1442
1443 fn required_string<'a>(
1444 object: &'a serde_json::Map<String, serde_json::Value>,
1445 key: &str,
1446 ) -> Result<&'a str, String> {
1447 object
1448 .get(key)
1449 .and_then(serde_json::Value::as_str)
1450 .ok_or_else(|| format!("plugin.json requires a `{key}` string"))
1451 }
1452
1453 fn optional_string(
1454 object: &serde_json::Map<String, serde_json::Value>,
1455 key: &str,
1456 ) -> Result<(), String> {
1457 match object.get(key) {
1458 Some(value) if !value.is_string() => Err(format!("`{key}` must be a string")),
1459 _ => Ok(()),
1460 }
1461 }
1462
1463 #[cfg(test)]
1464 mod tests {
1465 use super::*;
1466
1467 /// A full-featured legacy manifest: every Codewhale-specific field the
1468 /// standard does not define, plus both MCP transports.
1469 const ROUND_TRIP_TOML: &str = r#"schema_version = 1
1470
1471 [plugin]
1472 name = "round-trip"
1473 version = "1.2.3"
1474 description = "Round-trip fixture"
1475 author = "Jane Doe"
1476 homepage = "https://example.com/round-trip"
1477 repository = "https://github.com/example/round-trip"
1478 license = "MIT"
1479 keywords = ["one", "two"]
1480
1481 [skills]
1482 path = "skills"
1483
1484 [commands]
1485 path = "commands"
1486
1487 [capabilities]
1488 filesystem_roots = ["src"]
1489 network_hosts = ["example.com"]
1490
1491 [when]
1492 os = ["macos", "linux"]
1493
1494 [mcp_servers.local]
1495 command = "run.sh"
1496 args = ["--port", "8080"]
1497 env = { API_KEY = "${ROUND_TRIP_API_KEY}" }
1498 cwd = "bin"
1499
1500 [mcp_servers.remote]
1501 url = "https://example.com/mcp"
1502 transport = "sse"
1503 connect_timeout = 30
1504 required = true
1505 enabled_tools = ["search"]
1506 env_headers = { Authorization = "ROUND_TRIP_REMOTE_TOKEN" }
1507 "#;
1508
1509 #[test]
1510 fn standard_name_rule_matches_the_spec_regex() {
1511 let long = "a".repeat(MAX_PLUGIN_NAME_CHARS);
1512 for valid in [
1513 "a",
1514 "0",
1515 "ab",
1516 "a-b",
1517 "a.b",
1518 "a-b.c-d",
1519 "a.-b",
1520 "acme.tools",
1521 long.as_str(),
1522 ] {
1523 assert!(is_standard_plugin_name(valid), "{valid}");
1524 }
1525 let too_long = "a".repeat(MAX_PLUGIN_NAME_CHARS + 1);
1526 for invalid in [
1527 "",
1528 "A",
1529 "a_b",
1530 "a b",
1531 "-a",
1532 "a-",
1533 ".a",
1534 "a.",
1535 "a--b",
1536 "a..b",
1537 "café",
1538 too_long.as_str(),
1539 ] {
1540 assert!(!is_standard_plugin_name(invalid), "{invalid}");
1541 }
1542 }
1543
1544 #[test]
1545 fn slugify_maps_legacy_names_onto_the_standard_rule() {
1546 let cases = [
1547 ("round-trip", "round-trip"),
1548 ("acme.tools", "acme.tools"),
1549 ("My_Plugin Name", "my-plugin-name"),
1550 ("Foo--Bar", "foo-bar"),
1551 ("a..b", "a.b"),
1552 ("--weird--", "weird"),
1553 ("UPPER_SNAKE Case.v2", "upper-snake-case.v2"),
1554 (" padded ", "padded"),
1555 ("dots...here", "dots.here"),
1556 ("mixed._-seps", "mixed-seps"),
1557 ];
1558 for (input, expected) in cases {
1559 let slug = slugify_plugin_name(input).unwrap();
1560 assert_eq!(slug, expected, "input: {input}");
1561 assert!(is_standard_plugin_name(&slug), "slug for {input}");
1562 }
1563
1564 let long = format!("{}-suffix", "a".repeat(70));
1565 let slug = slugify_plugin_name(&long).unwrap();
1566 assert!(slug.chars().count() <= MAX_PLUGIN_NAME_CHARS);
1567 assert!(is_standard_plugin_name(&slug));
1568 let boundary = format!("{}-{}", "a".repeat(63), "b".repeat(10));
1569 assert_eq!(slugify_plugin_name(&boundary).unwrap(), "a".repeat(63));
1570
1571 for unusable in ["___", "...", "", "插件"] {
1572 assert!(slugify_plugin_name(unusable).is_err(), "{unusable}");
1573 }
1574 }
1575
1576 #[test]
1577 fn toml_to_standard_to_internal_round_trip_is_stable() {
1578 let internal: PluginManifest = toml::from_str(ROUND_TRIP_TOML).unwrap();
1579 let emission = manifest_to_standard(&internal, &BTreeSet::new()).unwrap();
1580 assert_eq!(emission.exported_name, "round-trip");
1581 assert_eq!(emission.display_name, None);
1582
1583 // Every emitted document conforms to the standard's shape.
1584 let plugin_value = serde_json::to_value(&emission.plugin_json).unwrap();
1585 validate_plugin_json(&plugin_value).unwrap();
1586 let mcp_value = serde_json::to_value(emission.mcp_json.as_ref().unwrap()).unwrap();
1587 validate_mcp_json(&mcp_value).unwrap();
1588
1589 // The consume side derives the default skills spec from the standard
1590 // skills/ directory on disk.
1591 let tmp = tempfile::tempdir().unwrap();
1592 std::fs::create_dir(tmp.path().join("skills")).unwrap();
1593
1594 let plugin_text = serde_json::to_string_pretty(&plugin_value).unwrap();
1595 let standard = parse_plugin_json(&plugin_text).unwrap();
1596 let mcp_text = serde_json::to_string_pretty(&mcp_value).unwrap();
1597 let servers = parse_mcp_json(&mcp_text).unwrap();
1598 let restored = standard_to_manifest(standard, Some(servers), tmp.path()).unwrap();
1599
1600 assert_eq!(
1601 serde_json::to_value(&internal).unwrap(),
1602 serde_json::to_value(&restored).unwrap(),
1603 "plugin.toml -> internal -> plugin.json + mcp.json -> internal drifted"
1604 );
1605 }
1606
1607 #[test]
1608 fn emitted_documents_carry_only_standard_root_keys() {
1609 let internal: PluginManifest = toml::from_str(ROUND_TRIP_TOML).unwrap();
1610 let emission = manifest_to_standard(&internal, &BTreeSet::new()).unwrap();
1611 let plugin_value = serde_json::to_value(&emission.plugin_json).unwrap();
1612 // mcp_servers never leak into the closed plugin.json root; Codewhale
1613 // data is namespaced.
1614 assert!(plugin_value.get("mcp_servers").is_none());
1615 assert!(plugin_value.get("mcpServers").is_none());
1616 assert!(
1617 plugin_value["extensions"]
1618 .get(CODEWHALE_NAMESPACE)
1619 .is_some()
1620 );
1621 let mcp_value = serde_json::to_value(emission.mcp_json.as_ref().unwrap()).unwrap();
1622 assert_eq!(mcp_value["$schema"], serde_json::json!(MCP_SCHEMA_URL));
1623 assert_eq!(mcp_value["mcpServers"]["local"]["type"], "stdio");
1624 assert_eq!(mcp_value["mcpServers"]["remote"]["type"], "sse");
1625 assert_eq!(
1626 mcp_value["mcpServers"]["remote"]["extensions"][CODEWHALE_NAMESPACE]["connect_timeout"],
1627 serde_json::json!(30)
1628 );
1629 }
1630
1631 #[test]
1632 fn slugified_export_preserves_display_name_and_collision_is_an_error() {
1633 let toml = "schema_version = 1\n[plugin]\nname = \"Foo--Bar\"\nversion = \"1.0.0\"\n";
1634 let internal: PluginManifest = toml::from_str(toml).unwrap();
1635
1636 let emission = manifest_to_standard(&internal, &BTreeSet::new()).unwrap();
1637 assert_eq!(emission.exported_name, "foo-bar");
1638 assert_eq!(emission.display_name.as_deref(), Some("Foo--Bar"));
1639 let extension = emission.plugin_json.extensions[CODEWHALE_NAMESPACE].clone();
1640 assert_eq!(extension["display_name"], serde_json::json!("Foo--Bar"));
1641 validate_plugin_json(&serde_json::to_value(&emission.plugin_json).unwrap()).unwrap();
1642
1643 let colliding = BTreeSet::from(["foo-bar".to_string()]);
1644 let error = manifest_to_standard(&internal, &colliding).unwrap_err();
1645 assert!(error.contains("collides"), "{error}");
1646 }
1647
1648 #[test]
1649 fn unknown_extensions_namespaces_are_ignored_not_rejected() {
1650 let text = r#"{
1651 "$schema": "https://agent-plugins.org/schemas/plugin.json",
1652 "name": "acme.tools",
1653 "version": "2.0.0",
1654 "author": {"name": "Acme", "email": "plugins@acme.example", "url": "https://acme.example"},
1655 "extensions": {
1656 "com.example.client": {"anything": [1, 2, 3], "nested": {"x": true}},
1657 "net.codewhale": {"when": {"os": ["macos"]}}
1658 }
1659 }"#;
1660 let standard = parse_plugin_json(text).unwrap();
1661 let tmp = tempfile::tempdir().unwrap();
1662 let manifest = standard_to_manifest(standard, None, tmp.path()).unwrap();
1663 assert_eq!(manifest.plugin.name, "acme.tools");
1664 assert_eq!(
1665 manifest.plugin.author.as_deref(),
1666 Some("Acme <plugins@acme.example> (https://acme.example)")
1667 );
1668 assert_eq!(
1669 manifest.when.and_then(|when| when.os),
1670 Some(vec!["macos".to_string()])
1671 );
1672 assert!(
1673 manifest.skills.is_none(),
1674 "no skills/ directory means no skills spec"
1675 );
1676
1677 // Unknown keys inside our own namespace are rejected.
1678 let bad_extension = r#"{
1679 "$schema": "https://agent-plugins.org/schemas/plugin.json",
1680 "name": "acme.tools",
1681 "extensions": {"net.codewhale": {"surprise": true}}
1682 }"#;
1683 let standard = parse_plugin_json(bad_extension).unwrap();
1684 assert!(standard_to_manifest(standard, None, tmp.path()).is_err());
1685
1686 // Unknown root keys are rejected: the standard's root is closed.
1687 let bad_root = r#"{"$schema": "x", "name": "acme.tools", "mcpServers": {}}"#;
1688 assert!(parse_plugin_json(bad_root).is_err());
1689 }
1690
1691 #[test]
1692 fn plugin_json_requires_schema_and_a_standard_name() {
1693 let missing_schema = r#"{"name": "ok"}"#;
1694 assert!(parse_plugin_json(missing_schema).is_err());
1695 let bad_name = r#"{"$schema": "x", "name": "Not--Valid"}"#;
1696 assert!(parse_plugin_json(bad_name).is_err());
1697 }
1698
1699 #[test]
1700 fn mcp_json_transports_and_reserved_env_names() {
1701 let reserved =
1702 r#"{"mcpServers": {"x": {"command": "run", "env": {"PLUGIN_ROOT": "/tmp"}}}}"#;
1703 let error = parse_mcp_json(reserved).unwrap_err();
1704 assert!(error.contains("PLUGIN_ROOT"), "{error}");
1705
1706 let inferred = r#"{"mcpServers": {
1707 "local": {"command": "run.sh", "args": ["-y"]},
1708 "remote": {"url": "https://example.com/mcp"}
1709 }}"#;
1710 let servers = parse_mcp_json(inferred).unwrap();
1711 assert_eq!(servers["local"].command.as_deref(), Some("run.sh"));
1712 assert!(servers["local"].transport.is_none());
1713 assert!(servers["remote"].transport.is_none());
1714
1715 let sse = r#"{"mcpServers": {"r": {"type": "sse", "url": "https://example.com/sse"}}}"#;
1716 assert_eq!(
1717 parse_mcp_json(sse).unwrap()["r"].transport.as_deref(),
1718 Some("sse")
1719 );
1720 for bad in [
1721 r#"{"mcpServers": {"r": {"type": "websocket", "url": "https://example.com/ws"}}}"#,
1722 r#"{"mcpServers": {"r": {"command": "x", "url": "https://example.com"}}}"#,
1723 r#"{"mcpServers": {"r": {"type": "stdio", "command": "x", "url": "https://example.com"}}}"#,
1724 r#"{"mcpServers": {"r": {"url": "https://example.com", "args": ["x"]}}}"#,
1725 r#"{"mcpServers": {"r": {"type": "sse"}}}"#,
1726 ] {
1727 assert!(parse_mcp_json(bad).is_err(), "{bad}");
1728 }
1729
1730 let extended = r#"{"mcpServers": {"r": {"url": "https://example.com/mcp",
1731 "extensions": {"net.codewhale": {"connect_timeout": 30, "required": true,
1732 "env_headers": {"Authorization": "TOKEN_ENV"}}}}}}"#;
1733 let servers = parse_mcp_json(extended).unwrap();
1734 assert_eq!(servers["r"].connect_timeout, Some(30));
1735 assert!(servers["r"].required);
1736 assert_eq!(servers["r"].env_headers["Authorization"], "TOKEN_ENV");
1737 }
1738
1739 #[test]
1740 fn emission_validators_reject_nonconforming_documents() {
1741 let extra_root_key = serde_json::json!({"$schema": "x", "name": "ok", "surprise": 1});
1742 assert!(validate_plugin_json(&extra_root_key).is_err());
1743 let bad_name = serde_json::json!({"$schema": "x", "name": "Not--Valid"});
1744 assert!(validate_plugin_json(&bad_name).is_err());
1745 let nameless_author =
1746 serde_json::json!({"$schema": "x", "name": "ok", "author": {"email": "a@b.c"}});
1747 assert!(validate_plugin_json(&nameless_author).is_err());
1748
1749 let reserved_env = serde_json::json!({"mcpServers": {"x": {"command": "run", "env": {"PLUGIN_DATA": "y"}}}});
1750 assert!(validate_mcp_json(&reserved_env).is_err());
1751 let extra_root = serde_json::json!({"mcpServers": {}, "extra": true});
1752 assert!(validate_mcp_json(&extra_root).is_err());
1753 let cross_transport = serde_json::json!({"mcpServers": {"x": {"type": "sse", "url": "https://e.c", "cwd": "bin"}}});
1754 assert!(validate_mcp_json(&cross_transport).is_err());
1755
1756 let conforming = serde_json::json!({
1757 "$schema": MCP_SCHEMA_URL,
1758 "mcpServers": {"x": {"type": "stdio", "command": "run", "env": {"A": "${B}"}}}
1759 });
1760 validate_mcp_json(&conforming).unwrap();
1761 }
1762 }
1763
1763 lines RUST