use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::script_tool::{
ExposureSpec, ParamSpec, ScriptLawError, pin_from_plugin_root, resolve_under_root,
};
use crate::tool_provider::{IdentityError, ToolIdentity};
pub const WASM_DEFAULT_TIMEOUT_SECS: u64 = 30;
pub const MANIFEST_SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ManifestError {
Json(String),
BadSchemaVersion(u32),
BadName { name: String, source: IdentityError },
EmptyTools,
DuplicateTool { name: String },
BadTimeout { tool: String },
BadExposure { tool: String },
BadCapability { tool: String, reason: String },
BadServer { tool: String, reason: String },
PathLaw {
tool: String,
source: ScriptLawError,
},
EmptyVersion,
BadSkills { reason: String },
}
impl std::fmt::Display for ManifestError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Json(e) => write!(f, "plugin.json parse error: {e}"),
Self::BadSchemaVersion(v) => write!(
f,
"plugin.json schemaVersion {v} is not supported (this build understands {MANIFEST_SCHEMA_VERSION})"
),
Self::BadName { name, source } => write!(f, "invalid name `{name}`: {source}"),
Self::EmptyTools => write!(f, "plugin.json must declare at least one tool"),
Self::DuplicateTool { name } => {
write!(f, "duplicate tool name `{name}` in plugin.json")
}
Self::BadTimeout { tool } => {
write!(f, "tool `{tool}`: timeout_secs must be >= 1")
}
Self::BadExposure { tool } => {
write!(f, "tool `{tool}`: exposure must be `direct` or `deferred`")
}
Self::BadCapability { tool, reason } => {
write!(f, "tool `{tool}`: invalid capability ({reason})")
}
Self::BadServer { tool, reason } => {
write!(f, "tool `{tool}`: invalid mcp server spec ({reason})")
}
Self::PathLaw { tool, source } => write!(f, "tool `{tool}`: {source}"),
Self::EmptyVersion => write!(f, "plugin.json `version` must not be empty"),
Self::BadSkills { reason } => write!(f, "plugin.json `skills`: {reason}"),
}
}
}
impl std::error::Error for ManifestError {}
pub use phi_cap::{
CapabilitySpec, DeviceCaptureSpec, DeviceInputSpec, FsReadSpec, NetHttpSpec, ProcessSpawnSpec,
ResolvedCapability,
};
pub fn resolve_capabilities(
caps: &[CapabilitySpec],
plugin_root: &Path,
) -> Result<Vec<ResolvedCapability>, ScriptLawError> {
caps.iter()
.map(|c| match c {
CapabilitySpec::FsRead(spec) => {
let mut resolved = Vec::with_capacity(spec.paths.len());
for p in &spec.paths {
resolved.push(resolve_under_root(plugin_root, p)?);
}
Ok(ResolvedCapability::FsRead { paths: resolved })
}
CapabilitySpec::NetHttp(spec) => Ok(ResolvedCapability::NetHttp {
hosts: spec
.hosts
.iter()
.map(|h| h.trim().to_ascii_lowercase())
.collect(),
}),
CapabilitySpec::ProcessSpawn(spec) => Ok(ResolvedCapability::ProcessSpawn {
programs: spec.programs.clone(),
}),
CapabilitySpec::DeviceInput(spec) => Ok(ResolvedCapability::DeviceInput {
targets: spec.targets.clone(),
}),
CapabilitySpec::DeviceCapture(spec) => Ok(ResolvedCapability::DeviceCapture {
targets: spec.targets.clone(),
}),
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct McpServerSpec {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub command: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub headers: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WasmToolSpec {
pub name: String,
pub description: String,
pub module: String,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub parameters: BTreeMap<String, ParamSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capabilities: Vec<CapabilitySpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub exposure: ExposureSpec,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScriptToolSpec {
pub name: String,
pub description: String,
pub run: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub parameters: BTreeMap<String, ParamSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub exposure: ExposureSpec,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct McpToolSpec {
pub name: String,
pub server: McpServerSpec,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub exposure: ExposureSpec,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "form", rename_all = "lowercase")]
pub enum PluginToolSpec {
Wasm(WasmToolSpec),
Script(ScriptToolSpec),
Mcp(McpToolSpec),
}
impl PluginToolSpec {
pub fn name(&self) -> &str {
match self {
Self::Wasm(t) => &t.name,
Self::Script(t) => &t.name,
Self::Mcp(t) => &t.name,
}
}
pub fn form(&self) -> &'static str {
match self {
Self::Wasm(_) => "wasm",
Self::Script(_) => "script",
Self::Mcp(_) => "mcp",
}
}
pub fn timeout_secs(&self) -> Option<u64> {
match self {
Self::Wasm(t) => t.timeout_secs,
Self::Script(t) => t.timeout_secs,
Self::Mcp(t) => t.timeout_secs,
}
}
pub fn identity(&self, plugin_name: &str) -> Result<String, IdentityError> {
ToolIdentity::plugin(plugin_name, self.name()).map(|id| id.to_key())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginManifest {
#[serde(rename = "schemaVersion")]
pub schema_version: u32,
pub name: String,
pub version: String,
pub tools: Vec<PluginToolSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skills: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewTool {
pub identity: String,
pub form: &'static str,
pub summary: String,
pub timeout_secs: Option<u64>,
pub capabilities: Vec<ResolvedCapability>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewDigest {
pub name: String,
pub version: String,
pub tools: Vec<ReviewTool>,
pub skills: Vec<String>,
}
impl PluginManifest {
pub fn from_json(raw: &str) -> Result<Self, ManifestError> {
let manifest: Self =
serde_json::from_str(raw).map_err(|e| ManifestError::Json(e.to_string()))?;
manifest.validate()?;
Ok(manifest)
}
pub fn validate(&self) -> Result<(), ManifestError> {
if self.schema_version != MANIFEST_SCHEMA_VERSION {
return Err(ManifestError::BadSchemaVersion(self.schema_version));
}
check_name(&self.name, &self.name)?;
if self.version.trim().is_empty() {
return Err(ManifestError::EmptyVersion);
}
if self.tools.is_empty() {
return Err(ManifestError::EmptyTools);
}
let mut seen = BTreeSet::new();
for tool in &self.tools {
check_name(&self.name, tool.name())?;
if !seen.insert(tool.name().to_string()) {
return Err(ManifestError::DuplicateTool {
name: tool.name().to_string(),
});
}
self.validate_tool(tool)?;
}
let mut skills_seen = BTreeSet::new();
for skill in &self.skills {
if skill.trim().is_empty() {
return Err(ManifestError::BadSkills {
reason: "empty skill directory".into(),
});
}
if !skills_seen.insert(skill.clone()) {
return Err(ManifestError::BadSkills {
reason: format!("duplicate skill directory `{skill}`"),
});
}
}
Ok(())
}
fn validate_tool(&self, tool: &PluginToolSpec) -> Result<(), ManifestError> {
let name = tool.name();
if matches!(tool.timeout_secs(), Some(0)) {
return Err(ManifestError::BadTimeout {
tool: name.to_string(),
});
}
match tool {
PluginToolSpec::Wasm(t) => {
if t.module.trim().is_empty() {
return Err(ManifestError::PathLaw {
tool: name.to_string(),
source: ScriptLawError::EmptyRun,
});
}
if t.exposure == ExposureSpec::Hidden {
return Err(ManifestError::BadExposure {
tool: name.to_string(),
});
}
for cap in &t.capabilities {
match cap {
CapabilitySpec::FsRead(spec) if spec.paths.is_empty() => {
return Err(ManifestError::BadCapability {
tool: name.to_string(),
reason: "fs:read needs at least one path".into(),
});
}
CapabilitySpec::NetHttp(spec) if spec.hosts.is_empty() => {
return Err(ManifestError::BadCapability {
tool: name.to_string(),
reason: "net:http needs at least one host".into(),
});
}
CapabilitySpec::NetHttp(spec)
if spec.hosts.iter().any(|h| h.trim().is_empty()) =>
{
return Err(ManifestError::BadCapability {
tool: name.to_string(),
reason: "net:http host must not be empty".into(),
});
}
CapabilitySpec::FsRead(_) | CapabilitySpec::NetHttp(_) => {}
CapabilitySpec::ProcessSpawn(_)
| CapabilitySpec::DeviceInput(_)
| CapabilitySpec::DeviceCapture(_) => {
return Err(ManifestError::BadCapability {
tool: name.to_string(),
reason: "wasm tools may only declare fs:read / net:http \
(the faces the wasm host enforces)"
.into(),
});
}
}
}
}
PluginToolSpec::Script(t) => {
if t.exposure == ExposureSpec::Hidden {
return Err(ManifestError::BadExposure {
tool: name.to_string(),
});
}
if t.run.is_empty() {
return Err(ManifestError::PathLaw {
tool: name.to_string(),
source: ScriptLawError::EmptyRun,
});
}
if t.run.iter().any(|c| c.trim().is_empty()) {
return Err(ManifestError::PathLaw {
tool: name.to_string(),
source: ScriptLawError::EmptyRun,
});
}
}
PluginToolSpec::Mcp(t) => {
if t.exposure == ExposureSpec::Hidden {
return Err(ManifestError::BadExposure {
tool: name.to_string(),
});
}
validate_server(name, &t.server)?;
}
}
Ok(())
}
pub fn review(&self, plugin_root: &Path) -> Result<ReviewDigest, ManifestError> {
let mut tools = Vec::with_capacity(self.tools.len());
for tool in &self.tools {
let identity = tool
.identity(&self.name)
.map_err(|source| ManifestError::BadName {
name: tool.name().to_string(),
source,
})?;
let (summary, capabilities) = match tool {
PluginToolSpec::Wasm(t) => {
let module = resolve_under_root(plugin_root, &t.module).map_err(|source| {
ManifestError::PathLaw {
tool: t.name.clone(),
source,
}
})?;
let caps =
resolve_capabilities(&t.capabilities, plugin_root).map_err(|source| {
ManifestError::PathLaw {
tool: t.name.clone(),
source,
}
})?;
(format!("wasm module {module}"), caps)
}
PluginToolSpec::Script(t) => {
let run = pin_from_plugin_root(&t.run, plugin_root).map_err(|source| {
ManifestError::PathLaw {
tool: t.name.clone(),
source,
}
})?;
(run.join(" "), Vec::new())
}
PluginToolSpec::Mcp(t) => {
let summary = match (&t.server.command, &t.server.url) {
(Some(cmd), _) => format!("mcp stdio: {}", cmd.join(" ")),
(_, Some(url)) => format!("mcp http: {url}"),
_ => "mcp server (invalid)".into(),
};
(summary, Vec::new())
}
};
tools.push(ReviewTool {
identity,
form: tool.form(),
summary,
timeout_secs: tool.timeout_secs(),
capabilities,
});
}
Ok(ReviewDigest {
name: self.name.clone(),
version: self.version.clone(),
tools,
skills: self.skills.clone(),
})
}
}
fn check_name(plugin_name: &str, segment: &str) -> Result<(), ManifestError> {
ToolIdentity::plugin(plugin_name, segment)
.map(|_| ())
.map_err(|source| ManifestError::BadName {
name: segment.to_string(),
source,
})
}
fn validate_server(tool: &str, server: &McpServerSpec) -> Result<(), ManifestError> {
let bad = |reason: &str| ManifestError::BadServer {
tool: tool.to_string(),
reason: reason.to_string(),
};
match (&server.command, &server.url) {
(Some(cmd), None) => {
if cmd.is_empty() {
return Err(bad("command must not be empty"));
}
if cmd.iter().any(|c| c.trim().is_empty()) {
return Err(bad("command argv entries must not be empty"));
}
if !server.headers.is_empty() {
return Err(bad("headers belong to the url form"));
}
}
(None, Some(url)) => {
if !(url.starts_with("https://") || url.starts_with("http://")) {
return Err(bad("url must be http(s)://"));
}
if !server.env.is_empty() {
return Err(bad("env belongs to the stdio command form"));
}
}
(Some(_), Some(_)) => return Err(bad("command and url are mutually exclusive")),
(None, None) => return Err(bad("either command or url is required")),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn root() -> std::path::PathBuf {
std::env::current_dir().unwrap().join("plugin-root-test")
}
fn minimal_json() -> serde_json::Value {
serde_json::json!({
"schemaVersion": 1,
"name": "my-tools",
"version": "0.1.0",
"tools": [{
"name": "deploy",
"form": "script",
"description": "deploy",
"run": ["scripts/deploy.sh", "${env}"],
"parameters": {"env": {"type": "string"}}
}]
})
}
#[test]
fn parses_design_example_shape() {
let raw = serde_json::json!({
"schemaVersion": 1,
"name": "my-tools",
"version": "0.1.0",
"tools": [
{
"name": "search", "form": "wasm",
"module": "wasm/search.wasm",
"description": "search",
"parameters": {"q": {"type": "string", "description": "query"}},
"capabilities": [{"type": "fs:read", "paths": ["./data"]}],
"timeout_secs": 30
},
{
"name": "deploy", "form": "script",
"run": ["scripts/deploy.sh", "${env}"],
"description": "deploy",
"parameters": {"env": {"type": "string"}},
"timeout_secs": 120
},
{
"name": "wiki", "form": "mcp",
"server": {
"command": ["python", "server/main.py"],
"env": {"WIKI_TOKEN": "${ENV:WIKI_TOKEN}"}
}
}
],
"skills": ["skills"]
});
let manifest = PluginManifest::from_json(&raw.to_string()).expect("design example parses");
assert_eq!(manifest.tools.len(), 3);
assert_eq!(manifest.tools[0].form(), "wasm");
assert_eq!(manifest.tools[1].form(), "script");
assert_eq!(manifest.tools[2].form(), "mcp");
assert_eq!(manifest.skills, vec!["skills"]);
}
#[test]
fn rejects_bad_schema_version() {
let mut raw = minimal_json();
raw["schemaVersion"] = serde_json::json!(2);
let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
assert!(matches!(err, ManifestError::BadSchemaVersion(2)), "{err}");
}
#[test]
fn rejects_reserved_plugin_name_and_bad_segments() {
for name in [
"mcp",
"script",
"plugin",
"My Tools",
"",
"a".repeat(33).as_str(),
] {
let mut raw = minimal_json();
raw["name"] = serde_json::json!(name);
let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
assert!(
matches!(err, ManifestError::BadName { .. } | ManifestError::Json(_)),
"{name:?} → {err}"
);
}
}
#[test]
fn rejects_duplicate_tool_names() {
let mut raw = minimal_json();
raw["tools"]
.as_array_mut()
.unwrap()
.push(minimal_json()["tools"][0].clone());
let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
assert!(
matches!(err, ManifestError::DuplicateTool { ref name } if name == "deploy"),
"{err}"
);
}
#[test]
fn rejects_form_field_bleed() {
let mut raw = minimal_json();
raw["tools"][0]["capabilities"] = serde_json::json!([{"type": "fs:read", "paths": ["."]}]);
assert!(matches!(
PluginManifest::from_json(&raw.to_string()),
Err(ManifestError::Json(_))
));
let mut raw = minimal_json();
raw["tools"][0]["module"] = serde_json::json!("wasm/x.wasm");
assert!(matches!(
PluginManifest::from_json(&raw.to_string()),
Err(ManifestError::Json(_))
));
let mut raw = minimal_json();
raw["tools"][0] = serde_json::json!({
"name": "wiki", "form": "mcp",
"description": "nope",
"server": {"url": "https://x"}
});
assert!(matches!(
PluginManifest::from_json(&raw.to_string()),
Err(ManifestError::Json(_))
));
}
#[test]
fn rejects_bad_capability_shapes() {
let mut raw = minimal_json();
raw["tools"][0] = serde_json::json!({
"name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d",
"capabilities": [{"type": "fs:read", "paths": []}]
});
let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
assert!(matches!(err, ManifestError::BadCapability { .. }), "{err}");
let mut raw = minimal_json();
raw["tools"][0] = serde_json::json!({
"name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d",
"capabilities": [{"type": "fs:read", "paths": ["."], "hosts": ["x"]}]
});
assert!(matches!(
PluginManifest::from_json(&raw.to_string()),
Err(ManifestError::Json(_))
));
}
#[test]
fn rejects_bad_mcp_server_spec() {
for server in [
serde_json::json!({"command": ["python", "s.py"], "url": "https://x"}),
serde_json::json!({}),
serde_json::json!({"url": "https://x", "env": {"A": "b"}}),
serde_json::json!({"url": "ftp://x"}),
serde_json::json!({"command": []}),
] {
let mut raw = minimal_json();
raw["tools"][0] = serde_json::json!({
"name": "wiki", "form": "mcp", "server": server
});
let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
assert!(
matches!(
err,
ManifestError::BadServer { .. } | ManifestError::Json(_)
),
"{server} → {err}"
);
}
}
#[test]
fn rejects_zero_timeout_and_hidden_exposure() {
let mut raw = minimal_json();
raw["tools"][0]["timeout_secs"] = serde_json::json!(0);
assert!(matches!(
PluginManifest::from_json(&raw.to_string()),
Err(ManifestError::BadTimeout { .. })
));
let mut raw = minimal_json();
raw["tools"][0]["exposure"] = serde_json::json!("hidden");
assert!(matches!(
PluginManifest::from_json(&raw.to_string()),
Err(ManifestError::BadExposure { .. })
));
}
#[test]
fn review_shows_full_view_with_resolved_paths() {
let raw = serde_json::json!({
"schemaVersion": 1,
"name": "my-tools",
"version": "0.1.0",
"tools": [
{
"name": "search", "form": "wasm",
"module": "wasm/search.wasm",
"description": "search",
"capabilities": [
{"type": "fs:read", "paths": ["./data"]},
{"type": "net:http", "hosts": ["API.Example.com"]}
],
"timeout_secs": 30
},
{
"name": "deploy", "form": "script",
"run": ["scripts/deploy.sh", "--env", "${env}"],
"description": "deploy"
}
]
});
let manifest = PluginManifest::from_json(&raw.to_string()).unwrap();
let root = root();
let digest = manifest.review(&root).unwrap();
assert_eq!(digest.name, "my-tools");
assert_eq!(digest.tools.len(), 2);
let wasm = &digest.tools[0];
assert_eq!(wasm.identity, "plugin.my-tools.search");
let data_abs = root.join("data").to_string_lossy().into_owned();
assert_eq!(
wasm.capabilities,
vec![
ResolvedCapability::FsRead {
paths: vec![data_abs]
},
ResolvedCapability::NetHttp {
hosts: vec!["api.example.com".into()]
}
]
);
let script = &digest.tools[1];
assert_eq!(script.identity, "plugin.my-tools.deploy");
let run_abs = root
.join("scripts")
.join("deploy.sh")
.to_string_lossy()
.into_owned();
assert_eq!(script.summary, format!("{run_abs} --env ${{env}}"));
}
#[test]
fn review_rejects_escaping_paths() {
let raw = serde_json::json!({
"schemaVersion": 1,
"name": "my-tools",
"version": "0.1.0",
"tools": [{
"name": "search", "form": "wasm",
"module": "wasm/search.wasm", "description": "d",
"capabilities": [{"type": "fs:read", "paths": ["../outside"]}]
}]
});
let manifest = PluginManifest::from_json(&raw.to_string()).unwrap();
let err = manifest.review(&root()).unwrap_err();
assert!(matches!(err, ManifestError::PathLaw { .. }), "{err}");
}
#[test]
fn round_trips_through_json() {
let manifest = PluginManifest::from_json(&minimal_json().to_string()).unwrap();
let back: PluginManifest =
serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap();
assert_eq!(manifest, back);
}
}