//! Publisher for Claude Code plugin directories.
//!
//! Claude Code reads its own plugin layout: a manifest and marketplace entry
//! under `.claude-plugin/`, skills under `skills/`, MCP servers in `.mcp.json`,
//! and executables under `bin/`, which Claude Code adds to its shell's PATH while
//! the plugin is enabled. This target is client-specific; the portable Agent
//! Plugins layout written by [`super::publish`] stays the portable format.
//!
//! Both targets compile the same typed inputs. Portable plugin-root variables
//! are mapped to Claude Code's: `./` and `${PLUGIN_ROOT}` become
//! `${CLAUDE_PLUGIN_ROOT}`, and `${PLUGIN_DATA}` becomes `${CLAUDE_PLUGIN_DATA}`.
//! Manifest extensions belong to the portable manifest and are not written,
//! because Claude Code strips unknown manifest fields.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use super::{
AgentPluginMcpServerConfig, AgentPluginPublisherError, AgentPluginPublisherOptions,
AgentPluginRemoteMcpServer, AgentPluginStdioMcpServer, PublishedAgentPlugin, canonicalize,
invalid_mcp_server, prepare_output, prepare_plugin, write_json, write_skills_and_runtime,
};
use crate::skill::CommandInfo;
/// Words Claude Code reserves for official plugins and marketplaces.
const RESERVED_WORDS: [&str; 3] = ["claude", "anthropic", "anthropics"];
/// Publishes a Claude Code plugin directory that is also a one-plugin marketplace.
///
/// The directory installs with `claude plugin marketplace add <dir>` followed by
/// `claude plugin install <name>@<name>`.
pub fn publish(
root: &Path,
commands: &[CommandInfo],
groups: &BTreeMap<String, String>,
options: &AgentPluginPublisherOptions,
) -> Result<PublishedAgentPlugin, AgentPluginPublisherError> {
validate_claude_plugin_name(&options.manifest.name)?;
let prepared = prepare_plugin(commands, groups, options)?;
let mcp_servers = prepared
.mcp_servers
.iter()
.map(|(name, server)| Ok((name.clone(), claude_mcp_server_json(name, server)?)))
.collect::<Result<serde_json::Map<_, _>, AgentPluginPublisherError>>()?;
prepare_output(
root,
options.policy.overwrite,
&[".claude-plugin", "skills", "bin"],
&[".mcp.json"],
)?;
let mut files = Vec::new();
write_json(
&root.join(".claude-plugin/plugin.json"),
&claude_plugin_manifest(options),
"Claude Code plugin manifest",
)?;
files.push(PathBuf::from(".claude-plugin/plugin.json"));
write_json(
&root.join(".claude-plugin/marketplace.json"),
&claude_marketplace(options),
"Claude Code marketplace",
)?;
files.push(PathBuf::from(".claude-plugin/marketplace.json"));
write_skills_and_runtime(root, prepared, &mut files)?;
if !mcp_servers.is_empty() {
write_json(
&root.join(".mcp.json"),
&canonicalize(json!({ "mcpServers": mcp_servers })),
"Claude Code MCP server map",
)?;
files.push(PathBuf::from(".mcp.json"));
}
Ok(PublishedAgentPlugin {
root: root.to_path_buf(),
files,
})
}
/// Rejects names Claude Code refuses or warns about.
///
/// Claude Code compares names case-insensitively with runs of separators folded
/// together. It refuses a `cc-plugin-` prefix and names built on the reserved
/// words, and warns about a reserved word anywhere else; both are rejected here
/// so a strict validation passes.
fn validate_claude_plugin_name(name: &str) -> Result<(), AgentPluginPublisherError> {
let lower = name.to_ascii_lowercase();
let words = lower
.split(|c: char| !c.is_ascii_alphanumeric())
.filter(|word| !word.is_empty())
.collect::<Vec<_>>();
let reserved = words.iter().any(|word| RESERVED_WORDS.contains(word))
|| words.starts_with(&["cc", "plugin"]);
if reserved {
Err(AgentPluginPublisherError::InvalidPluginName {
name: name.to_string(),
})
} else {
Ok(())
}
}
fn claude_plugin_manifest(options: &AgentPluginPublisherOptions) -> Value {
let manifest = &options.manifest;
let mut value = serde_json::Map::new();
value.insert("name".to_string(), Value::String(manifest.name.clone()));
let optional = [
("version", &manifest.version),
("description", &manifest.description),
("homepage", &manifest.homepage),
("repository", &manifest.repository),
("license", &manifest.license),
];
for (key, field) in optional {
if let Some(field) = field {
value.insert(key.to_string(), Value::String(field.clone()));
}
}
if let Some(author) = &manifest.author {
let mut entry = serde_json::Map::new();
for (key, field) in [
("name", &author.name),
("email", &author.email),
("url", &author.url),
] {
if let Some(field) = field {
entry.insert(key.to_string(), Value::String(field.clone()));
}
}
value.insert("author".to_string(), Value::Object(entry));
}
if !manifest.keywords.is_empty() {
value.insert(
"keywords".to_string(),
Value::Array(
manifest
.keywords
.iter()
.cloned()
.map(Value::String)
.collect(),
),
);
}
canonicalize(Value::Object(value))
}
fn claude_marketplace(options: &AgentPluginPublisherOptions) -> Value {
let manifest = &options.manifest;
let owner = manifest
.author
.as_ref()
.and_then(|author| author.name.clone())
.unwrap_or_else(|| manifest.name.clone());
let mut entry = serde_json::Map::from_iter([
("name".to_string(), Value::String(manifest.name.clone())),
("source".to_string(), Value::String("./".to_string())),
]);
if let Some(description) = &manifest.description {
entry.insert(
"description".to_string(),
Value::String(description.clone()),
);
}
if let Some(version) = &manifest.version {
entry.insert("version".to_string(), Value::String(version.clone()));
}
let mut marketplace = json!({
"name": manifest.name,
"owner": { "name": owner },
"plugins": [Value::Object(entry)],
});
if let Some(description) = &manifest.description {
marketplace["description"] = Value::String(description.clone());
}
canonicalize(marketplace)
}
fn claude_mcp_server_json(
name: &str,
server: &AgentPluginMcpServerConfig,
) -> Result<Value, AgentPluginPublisherError> {
match server {
AgentPluginMcpServerConfig::Stdio(server) => claude_stdio_json(name, server),
AgentPluginMcpServerConfig::StreamableHttp(server) => {
Ok(claude_remote_json("http", server))
}
AgentPluginMcpServerConfig::Sse(server) => Ok(claude_remote_json("sse", server)),
}
}
fn claude_stdio_json(
name: &str,
server: &AgentPluginStdioMcpServer,
) -> Result<Value, AgentPluginPublisherError> {
if server.cwd.is_some() {
return invalid_mcp_server(
name,
"Claude Code plugin servers do not declare a working directory",
);
}
for key in server.env.keys() {
if key.eq_ignore_ascii_case("CLAUDE_PLUGIN_ROOT")
|| key.eq_ignore_ascii_case("CLAUDE_PLUGIN_DATA")
{
return invalid_mcp_server(
name,
"env must not set CLAUDE_PLUGIN_ROOT or CLAUDE_PLUGIN_DATA",
);
}
}
let command = match server.command.strip_prefix("./") {
Some(relative) => format!("${{CLAUDE_PLUGIN_ROOT}}/{relative}"),
None => server.command.clone(),
};
let mut value = serde_json::Map::from_iter([
("type".to_string(), Value::String("stdio".to_string())),
("command".to_string(), Value::String(command)),
]);
if !server.args.is_empty() {
value.insert(
"args".to_string(),
Value::Array(
server
.args
.iter()
.map(|arg| Value::String(claude_variables(arg)))
.collect(),
),
);
}
if !server.env.is_empty() {
value.insert(
"env".to_string(),
Value::Object(
server
.env
.iter()
.map(|(key, value)| (key.clone(), Value::String(claude_variables(value))))
.collect(),
),
);
}
Ok(Value::Object(value))
}
fn claude_remote_json(kind: &str, server: &AgentPluginRemoteMcpServer) -> Value {
let mut value = serde_json::Map::from_iter([
("type".to_string(), Value::String(kind.to_string())),
(
"url".to_string(),
Value::String(claude_variables(&server.url)),
),
]);
if !server.headers.is_empty() {
value.insert(
"headers".to_string(),
Value::Object(
server
.headers
.iter()
.map(|(key, value)| (key.clone(), Value::String(claude_variables(value))))
.collect(),
),
);
}
Value::Object(value)
}
/// Maps portable plugin variables to the names Claude Code substitutes.
fn claude_variables(value: &str) -> String {
value
.replace("${PLUGIN_ROOT}", "${CLAUDE_PLUGIN_ROOT}")
.replace("${PLUGIN_DATA}", "${CLAUDE_PLUGIN_DATA}")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agent_plugin::{
AgentPluginAuthor, AgentPluginManifestMetadata, AgentPluginMcpServer,
AgentPluginPublicationPolicy, AgentPluginSkillOptions, AgentPluginToolBindingOptions,
};
use std::fs;
fn command(name: &str) -> CommandInfo {
CommandInfo {
name: name.to_string(),
description: Some(format!("Run {name}")),
args_fields: Vec::new(),
options_fields: Vec::new(),
env_fields: Vec::new(),
hint: None,
examples: Vec::new(),
output_schema: None,
}
}
fn temp_root(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"multicast-claude-plugin-test-{}-{name}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
root
}
fn options(name: &str, overwrite: bool) -> AgentPluginPublisherOptions {
AgentPluginPublisherOptions {
manifest: AgentPluginManifestMetadata {
name: name.to_string(),
version: Some("1.2.3".to_string()),
description: Some("Demo tools for repeatable work.".to_string()),
author: None,
homepage: None,
repository: None,
license: None,
keywords: Vec::new(),
extensions: BTreeMap::new(),
},
skills: AgentPluginSkillOptions {
cli_name: "demo-tools".to_string(),
depth: 0,
additional_skills: Vec::new(),
},
tools: AgentPluginToolBindingOptions {
mcp_server: Some(AgentPluginMcpServer {
command: "./bin/demo-tools".to_string(),
args: vec!["--mcp".to_string()],
}),
mcp_servers: BTreeMap::new(),
},
tool_runtime: None,
policy: AgentPluginPublicationPolicy { overwrite },
}
}
fn read(root: &Path, path: &str) -> String {
fs::read_to_string(root.join(path)).unwrap()
}
#[test]
fn publish_writes_claude_code_layout_with_mapped_plugin_root() {
let root = temp_root("layout");
let mut options = options("demo-tools", false);
options.manifest.author = Some(AgentPluginAuthor {
name: Some("Demo Org".to_string()),
email: None,
url: None,
});
options.manifest.license = Some("MIT".to_string());
options.manifest.extensions.insert(
"com.example.client".to_string(),
serde_json::json!({ "enabled": true }),
);
let result = publish(&root, &[command("run")], &BTreeMap::new(), &options).unwrap();
assert_eq!(
result.files,
vec![
PathBuf::from(".claude-plugin/plugin.json"),
PathBuf::from(".claude-plugin/marketplace.json"),
PathBuf::from("skills/demo-tools/SKILL.md"),
PathBuf::from(".mcp.json"),
]
);
assert_eq!(
read(&root, ".claude-plugin/plugin.json"),
"{\n \"author\": {\n \"name\": \"Demo Org\"\n },\n \"description\": \"Demo tools for repeatable work.\",\n \"license\": \"MIT\",\n \"name\": \"demo-tools\",\n \"version\": \"1.2.3\"\n}\n"
);
assert_eq!(
read(&root, ".claude-plugin/marketplace.json"),
"{\n \"description\": \"Demo tools for repeatable work.\",\n \"name\": \"demo-tools\",\n \"owner\": {\n \"name\": \"Demo Org\"\n },\n \"plugins\": [\n {\n \"description\": \"Demo tools for repeatable work.\",\n \"name\": \"demo-tools\",\n \"source\": \"./\",\n \"version\": \"1.2.3\"\n }\n ]\n}\n"
);
assert_eq!(
read(&root, ".mcp.json"),
"{\n \"mcpServers\": {\n \"demo-tools\": {\n \"args\": [\n \"--mcp\"\n ],\n \"command\": \"${CLAUDE_PLUGIN_ROOT}/bin/demo-tools\",\n \"type\": \"stdio\"\n }\n }\n}\n"
);
assert!(!root.join("plugin.json").exists());
assert!(!root.join("mcp.json").exists());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn publish_maps_portable_variables_and_remote_transports() {
let root = temp_root("variables");
let mut options = options("demo-tools", false);
options.tools.mcp_server = None;
options.tools.mcp_servers.insert(
"local".to_string(),
AgentPluginMcpServerConfig::Stdio(AgentPluginStdioMcpServer {
command: "demo".to_string(),
args: vec!["${PLUGIN_ROOT}/config.json".to_string()],
env: BTreeMap::from([("DATA_DIR".to_string(), "${PLUGIN_DATA}/demo".to_string())]),
cwd: None,
}),
);
options.tools.mcp_servers.insert(
"remote".to_string(),
AgentPluginMcpServerConfig::StreamableHttp(AgentPluginRemoteMcpServer {
url: "https://api.example.com/mcp".to_string(),
headers: BTreeMap::from([(
"X-Config".to_string(),
"${PLUGIN_ROOT}/headers".to_string(),
)]),
}),
);
options.tools.mcp_servers.insert(
"legacy".to_string(),
AgentPluginMcpServerConfig::Sse(AgentPluginRemoteMcpServer {
url: "http://localhost:8080/sse".to_string(),
headers: BTreeMap::new(),
}),
);
publish(&root, &[command("run")], &BTreeMap::new(), &options).unwrap();
assert_eq!(
read(&root, ".mcp.json"),
"{\n \"mcpServers\": {\n \"legacy\": {\n \"type\": \"sse\",\n \"url\": \"http://localhost:8080/sse\"\n },\n \"local\": {\n \"args\": [\n \"${CLAUDE_PLUGIN_ROOT}/config.json\"\n ],\n \"command\": \"demo\",\n \"env\": {\n \"DATA_DIR\": \"${CLAUDE_PLUGIN_DATA}/demo\"\n },\n \"type\": \"stdio\"\n },\n \"remote\": {\n \"headers\": {\n \"X-Config\": \"${CLAUDE_PLUGIN_ROOT}/headers\"\n },\n \"type\": \"http\",\n \"url\": \"https://api.example.com/mcp\"\n }\n }\n}\n"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn publish_rejects_reserved_names_before_writing() {
for name in [
"claude-tools",
"my-anthropic",
"Anthropics",
"cc-plugin-demo",
"CC_Plugin",
] {
let root = temp_root("reserved");
let error = publish(
&root,
&[command("run")],
&BTreeMap::new(),
&options(name, false),
)
.unwrap_err();
assert!(
matches!(error, AgentPluginPublisherError::InvalidPluginName { .. }),
"{name}: {error:?}"
);
assert!(!root.exists(), "{name} wrote output");
}
for name in ["claudette", "cc-demo", "plugin-cc"] {
let root = temp_root("allowed");
publish(
&root,
&[command("run")],
&BTreeMap::new(),
&options(name, false),
)
.unwrap_or_else(|error| panic!("{name}: {error:?}"));
let _ = fs::remove_dir_all(&root);
}
}
#[test]
fn publish_rejects_working_directory_and_claude_variables_in_env() {
for (cwd, key) in [
(Some("${PLUGIN_ROOT}"), "DATA_DIR"),
(None, "claude_plugin_root"),
] {
let root = temp_root("server");
let mut options = options("demo-tools", false);
options.tools.mcp_servers.insert(
"local".to_string(),
AgentPluginMcpServerConfig::Stdio(AgentPluginStdioMcpServer {
command: "demo".to_string(),
args: Vec::new(),
env: BTreeMap::from([(key.to_string(), "value".to_string())]),
cwd: cwd.map(str::to_string),
}),
);
let error = publish(&root, &[command("run")], &BTreeMap::new(), &options).unwrap_err();
assert!(
matches!(error, AgentPluginPublisherError::InvalidMcpServer { .. }),
"{key}: {error:?}"
);
assert!(!root.exists());
}
}
#[test]
fn publish_guards_and_replaces_only_claude_owned_artifacts() {
let root = temp_root("owned");
fs::create_dir_all(root.join(".claude-plugin")).unwrap();
fs::write(root.join(".claude-plugin/plugin.json"), "stale").unwrap();
fs::write(root.join("keep.txt"), "keep").unwrap();
let error = publish(
&root,
&[command("run")],
&BTreeMap::new(),
&options("demo-tools", false),
)
.unwrap_err();
assert!(matches!(
error,
AgentPluginPublisherError::OutputExists { .. }
));
assert_eq!(read(&root, ".claude-plugin/plugin.json"), "stale");
fs::write(root.join(".claude-plugin/stale.json"), "stale").unwrap();
fs::write(root.join(".mcp.json"), "stale").unwrap();
let mut replace = options("demo-tools", true);
replace.tools.mcp_server = None;
publish(&root, &[command("run")], &BTreeMap::new(), &replace).unwrap();
assert!(!root.join(".claude-plugin/stale.json").exists());
assert!(!root.join(".mcp.json").exists());
assert!(read(&root, ".claude-plugin/plugin.json").contains("demo-tools"));
assert_eq!(read(&root, "keep.txt"), "keep");
let _ = fs::remove_dir_all(&root);
}
}