use crate::config::Policy;
use crate::mcp;
use crate::provider::ProviderProfile;
use crate::tools::{read_capped, Tool, ToolError, ToolOutcome, ToolSource};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
pub const API: u32 = 1;
pub const MANIFEST: &str = "plugin.toml";
const ARGS_ENV_MAX: usize = 64 * 1024;
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub const MAX_TIMEOUT: Duration = Duration::from_secs(600);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
#[default]
Command,
Mcp,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Cwd {
#[default]
Workspace,
Plugin,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Parameters {
File(String),
Inline(Box<toml::Value>),
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ToolDef {
pub name: String,
pub description: String,
#[serde(default)]
pub parameters: Option<Parameters>,
#[serde(default)]
pub kind: Kind,
#[serde(default)]
pub command: Vec<String>,
#[serde(default)]
pub cwd: Cwd,
#[serde(default)]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub policy: Option<Policy>,
#[serde(default)]
pub env: Vec<String>,
#[serde(default, rename = "override")]
pub override_builtin: bool,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PromptDef {
#[serde(default)]
pub text: Option<String>,
#[serde(default)]
pub file: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileDef {
pub name: String,
#[serde(default = "yes")]
pub tool_choice: bool,
#[serde(default = "yes")]
pub stream_usage: bool,
#[serde(default)]
pub max_tokens_field: Option<String>,
#[serde(default = "yes")]
pub supports_tools: bool,
#[serde(default)]
pub body: Option<toml::Value>,
#[serde(default)]
pub reasoning: Option<crate::reasoning::Policy>,
#[serde(default)]
pub models: BTreeMap<String, ModelReasoningDef>,
#[serde(default)]
pub request: Option<RequestDef>,
#[serde(default)]
pub vision: Option<bool>,
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct RequestDef {
#[serde(default)]
pub num_ctx: Option<u32>,
#[serde(default)]
pub num_ctx_field: Option<String>,
#[serde(default)]
pub max_output: Option<u32>,
#[serde(default)]
pub temperature: Option<TemperatureDef>,
#[serde(default)]
pub reject_response_formats: Vec<String>,
#[serde(default)]
pub aux_model: Option<String>,
#[serde(default)]
pub models: BTreeMap<String, LimitDef>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum TemperatureDef {
Mode(String),
Fixed { fixed: f32 },
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct LimitDef {
#[serde(default)]
pub num_ctx: Option<u32>,
#[serde(default)]
pub max_output: Option<u32>,
}
impl From<&RequestDef> for crate::provider::RequestPolicy {
fn from(def: &RequestDef) -> Self {
Self {
num_ctx: def.num_ctx,
num_ctx_field: def.num_ctx_field.clone(),
max_output: def.max_output,
temperature: def.temperature.as_ref().map(|t| match t {
TemperatureDef::Fixed { fixed } => crate::provider::Temperature::Fixed(*fixed),
TemperatureDef::Mode(mode) if mode.eq_ignore_ascii_case("omit") => {
crate::provider::Temperature::Omit
}
TemperatureDef::Mode(_) => crate::provider::Temperature::Default,
}),
reject_response_formats: def.reject_response_formats.clone(),
aux_model: def.aux_model.clone(),
models: def
.models
.iter()
.map(|(id, limit)| {
(
id.clone(),
crate::provider::ModelLimits {
num_ctx: limit.num_ctx,
max_output: limit.max_output,
},
)
})
.collect(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum ModelReasoningDef {
Toggle(bool),
Policy(crate::reasoning::Policy),
}
fn yes() -> bool {
true
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Event {
BeforeTool,
AfterTool,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HookDef {
pub event: Event,
#[serde(default)]
pub tool: Option<String>,
#[serde(default)]
pub command: Vec<String>,
#[serde(default)]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub cwd: Cwd,
#[serde(default)]
pub env: Vec<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
pub name: String,
#[serde(default)]
pub version: String,
#[serde(default)]
pub description: String,
#[serde(default = "current_api")]
pub api: u32,
#[serde(default, rename = "tool")]
pub tools: Vec<ToolDef>,
#[serde(default, rename = "prompt")]
pub prompts: Vec<PromptDef>,
#[serde(default, rename = "provider_profile")]
pub provider_profiles: Vec<ProfileDef>,
#[serde(default, rename = "hook")]
pub hooks: Vec<HookDef>,
#[serde(default, rename = "mcp")]
pub mcp: Vec<crate::mcp::Spec>,
}
fn current_api() -> u32 {
API
}
#[derive(Debug, Clone)]
pub struct Plugin {
pub name: String,
pub version: String,
pub description: String,
pub dir: PathBuf,
pub manifest: Manifest,
pub enabled: bool,
}
#[derive(Clone)]
pub struct PluginTool {
pub tool: Arc<dyn Tool>,
pub policy: Policy,
pub source: ToolSource,
}
pub type ToolsAndProblems = (Vec<PluginTool>, Vec<String>);
struct ServerRef<'a> {
spec: &'a mcp::Spec,
base: PathBuf,
owner: String,
source: ToolSource,
}
#[derive(Debug, Clone)]
pub struct McpServerState {
pub name: String,
pub source: ToolSource,
pub owner: String,
pub command: String,
pub transport: crate::mcp::Transport,
pub program: String,
pub args: Vec<String>,
pub url: Option<String>,
pub policy: Policy,
pub prefix: String,
pub timeout_secs: u64,
pub disabled: bool,
pub tools: usize,
pub error: Option<String>,
pub token_env: Option<String>,
pub token: crate::mcp::TokenSource,
pub protocol: Option<String>,
pub server_name: Option<String>,
pub server_version: Option<String>,
}
fn describe_command(spec: &mcp::Spec) -> String {
match spec.transport {
crate::mcp::Transport::Stdio => {
let mut out = spec.command.clone();
for arg in &spec.args {
out.push(' ');
out.push_str(arg);
}
out
}
crate::mcp::Transport::Http => {
let url = spec.url.as_deref().unwrap_or("(no url declared)");
format!(
"http {}",
crate::config::redact_url(url).unwrap_or_else(|| url.to_string())
)
}
}
}
type StartedServer = Result<(Arc<crate::mcp::Server>, Vec<crate::mcp::RemoteTool>), String>;
#[derive(Debug, Clone, Default)]
pub struct Plugins {
pub plugins: Vec<Plugin>,
pub problems: Vec<String>,
scripts_dir: Option<PathBuf>,
mcp: Option<Duration>,
config_mcp: Vec<mcp::Spec>,
secrets: crate::mcp::Secrets,
servers: Arc<Mutex<BTreeMap<String, StartedServer>>>,
}
impl Plugins {
pub fn with_scripts_dir(mut self, dir: Option<PathBuf>) -> Self {
self.scripts_dir = dir;
self
}
pub fn with_mcp(mut self, settings: McpSettings) -> Self {
self.mcp = settings.0;
self
}
pub fn with_config_mcp(mut self, cfg: &crate::config::Config) -> Self {
self.config_mcp = cfg.mcp.clone();
self.secrets = cfg.dotenv.values.clone();
self
}
pub fn get(&self, name: &str) -> Option<&Plugin> {
self.plugins.iter().find(|p| p.name == name)
}
pub fn prompts(&self) -> Vec<String> {
self.plugins
.iter()
.flat_map(|p| p.manifest.prompts.iter())
.filter_map(|d| d.text.clone())
.collect()
}
pub fn provider_profiles(&self) -> Vec<ProviderProfile> {
let mut out: Vec<ProviderProfile> = Vec::new();
for plugin in &self.plugins {
for def in &plugin.manifest.provider_profiles {
let profile = profile_from_def(def);
match out.iter_mut().find(|p| p.name == profile.name) {
Some(slot) => *slot = profile,
None => out.push(profile),
}
}
}
out
}
pub fn tools(
&self,
workspace: &Path,
max_bytes: usize,
builtin: &[String],
) -> ToolsAndProblems {
let mut out: Vec<PluginTool> = Vec::new();
let mut problems = Vec::new();
for plugin in &self.plugins {
for def in &plugin.manifest.tools {
let mut problem = |why: String| {
problems.push(format!(
"plugin `{}`: tool `{}`: {why}",
plugin.name, def.name
));
};
if def.kind == Kind::Mcp {
problem(
concat!(
"kind = \"mcp\" belongs on a `[[mcp]]` section, not on one tool: ",
"an MCP server contributes all of its tools from a single entry"
)
.to_string(),
);
continue;
}
if def.command.is_empty() {
problem("no `command` given".into());
continue;
}
let taken = builtin.iter().any(|b| b == &def.name)
|| out.iter().any(|t| t.tool.name() == def.name);
if taken && !def.override_builtin {
problem(
"collides with a tool that already exists; set `override = true` on it \
to replace it"
.into(),
);
continue;
}
let parameters = match &def.parameters {
None => json!({"type": "object", "properties": {}}),
Some(Parameters::Inline(v)) => match serde_json::to_value(v) {
Ok(v) => v,
Err(e) => {
problem(format!("inline parameters are not valid JSON: {e}"));
continue;
}
},
Some(Parameters::File(rel)) => {
let path = match manifest_path(&plugin.dir, rel) {
Ok(path) => path,
Err(why) => {
problem(why);
continue;
}
};
match read_data_file(&path) {
Ok(text) => match serde_json::from_str::<Value>(&text) {
Ok(v) => v,
Err(e) => {
problem(format!("{}: {e}", path.display()));
continue;
}
},
Err(e) => {
problem(format!("{}: {e}", path.display()));
continue;
}
}
}
};
let policy = def.policy.unwrap_or(Policy::Ask);
let tool = CommandTool {
name: def.name.clone(),
description: def.description.clone(),
parameters,
command: def.command.clone(),
plugin: plugin.name.clone(),
plugin_dir: plugin.dir.clone(),
workspace: workspace.to_path_buf(),
cwd: def.cwd,
timeout: clamp_timeout(def.timeout_secs),
env: def.env.clone(),
max_bytes,
scripts_dir: self.scripts_dir.clone(),
};
out.push(PluginTool {
tool: Arc::new(tool) as Arc<dyn Tool>,
policy,
source: ToolSource::Plugin(plugin.name.clone()),
});
}
}
self.mcp_tools(workspace, builtin, &mut out, &mut problems);
(out, problems)
}
fn servers(&self, workspace: &Path) -> (Vec<ServerRef<'_>>, Vec<String>) {
let mut problems = Vec::new();
let mut out: Vec<ServerRef> = Vec::new();
for plugin in &self.plugins {
for spec in &plugin.manifest.mcp {
out.push(ServerRef {
spec,
base: plugin.dir.clone(),
owner: format!("plugin `{}`", plugin.name),
source: ToolSource::Plugin(format!("mcp:{}", spec.name)),
});
}
}
for spec in &self.config_mcp {
if let Some(pos) = out.iter().position(|s| s.spec.name == spec.name) {
let shadowed = out.remove(pos);
problems.push(format!(
"{}: mcp `{}` is also declared in config.toml, which wins; the manifest entry is ignored",
shadowed.owner, spec.name
));
}
out.push(ServerRef {
spec,
base: workspace.to_path_buf(),
owner: "config".to_string(),
source: ToolSource::Config(format!("mcp:{}", spec.name)),
});
}
(out, problems)
}
pub fn mcp_report(&self, workspace: &Path) -> (Vec<McpServerState>, Vec<String>) {
let (servers, shadowed) = self.servers(workspace);
let problems = shadowed;
let mut out = Vec::new();
for server in servers {
let started = if server.spec.disabled {
None
} else {
Some(self.start(server.spec, &server.base, workspace))
};
let (tools, error, handshake) = match &started {
None => (0, None, None),
Some(Ok((session, tools))) => (tools.len(), None, session.handshake()),
Some(Err(why)) => (0, Some(why.clone()), None),
};
let field = |key: &str| {
handshake
.as_ref()
.and_then(|h| h.get(key))
.and_then(|v| v.as_str())
.map(str::to_string)
};
let info = |key: &str| {
handshake
.as_ref()
.and_then(|h| h.get("serverInfo"))
.and_then(|i| i.get(key))
.and_then(|v| v.as_str())
.map(str::to_string)
};
out.push(McpServerState {
name: server.spec.name.clone(),
source: server.source,
owner: server.owner,
command: describe_command(server.spec),
transport: server.spec.transport,
program: server.spec.command.clone(),
args: server.spec.args.clone(),
url: server.spec.url.clone(),
policy: server.spec.policy,
prefix: server.spec.prefix.clone(),
timeout_secs: server
.spec
.timeout_secs
.or_else(|| self.mcp.map(|d| d.as_secs()))
.unwrap_or(0),
disabled: server.spec.disabled,
token_env: server.spec.token_env.clone(),
token: server.spec.token_source(&self.secrets),
tools,
error,
protocol: field("protocolVersion"),
server_name: info("name"),
server_version: info("version"),
});
}
(out, problems)
}
fn mcp_tools(
&self,
workspace: &Path,
builtin: &[String],
out: &mut Vec<PluginTool>,
problems: &mut Vec<String>,
) {
if self.mcp.is_none() {
return;
}
let (servers, shadowed) = self.servers(workspace);
problems.extend(shadowed);
for server in servers {
if server.spec.disabled {
continue;
}
if let Err(why) = server.spec.validate() {
problems.push(format!(
"{}: mcp `{}`: {why}",
server.owner, server.spec.name
));
continue;
}
let (session, tools) = match self.start(server.spec, &server.base, workspace) {
Ok(started) => started,
Err(why) => {
problems.push(why);
continue;
}
};
for remote in tools {
let tool = crate::mcp::McpTool::new(Arc::clone(&session), &remote);
let name = tool.name().to_string();
let published = format!("{}{}", session.prefix(), remote.name);
if name != published {
problems.push(format!(
"{}: mcp `{}`: tool {:?} is called as `{}` (a name must be [A-Za-z0-9_-], at most {} characters)",
server.owner,
server.spec.name,
remote.name,
name.trim_start_matches(session.prefix()),
crate::mcp::TOOL_NAME_MAX
));
}
let taken =
builtin.iter().any(|b| b == &name) || out.iter().any(|t| t.tool.name() == name);
if taken && !session.override_builtin() {
problems.push(format!(
concat!(
"{}: mcp `{}`: tool `{}` collides with a tool that ",
"already exists; set `override = true` on the server entry to replace it"
),
server.owner, server.spec.name, name
));
continue;
}
let policy = session.policy_for(&remote.name);
out.push(PluginTool {
tool: Arc::new(tool) as Arc<dyn Tool>,
policy,
source: server.source.clone(),
});
}
}
}
fn start(&self, spec: &mcp::Spec, base: &Path, workspace: &Path) -> StartedServer {
let Some(default_timeout) = self.mcp else {
return Err("MCP is off for this process (`--no-mcp`)".to_string());
};
let key = format!("{}:{}", base.display(), spec.name);
let mut cache = self.servers.lock().unwrap_or_else(|e| e.into_inner());
cache
.entry(key)
.or_insert_with(|| {
crate::mcp::Server::start(spec, base, workspace, default_timeout, &self.secrets)
.map_err(|e| format!("mcp `{}`: {e}", spec.name))
})
.clone()
}
pub fn hooks(&self) -> Vec<Arc<Hook>> {
self.plugins
.iter()
.flat_map(|p| {
p.manifest.hooks.iter().map(move |def| {
Arc::new(Hook {
event: def.event,
tool: def.tool.clone(),
command: def.command.clone(),
timeout: clamp_timeout(def.timeout_secs),
cwd: def.cwd,
env: def.env.clone(),
plugin_dir: p.dir.clone(),
plugin: p.name.clone(),
max_bytes: 64 * 1024,
scripts_dir: self.scripts_dir.clone(),
})
})
})
.collect()
}
}
pub fn profile_from_def(def: &ProfileDef) -> ProviderProfile {
ProviderProfile {
name: def.name.clone(),
tool_choice: def.tool_choice,
stream_usage: def.stream_usage,
max_tokens_field: def.max_tokens_field.clone(),
supports_tools: def.supports_tools,
send_reasoning: false,
body: def
.body
.as_ref()
.and_then(|v| serde_json::to_value(v).ok())
.unwrap_or_else(|| serde_json::json!({})),
reasoning: def.reasoning.clone(),
request: def
.request
.as_ref()
.map(crate::provider::RequestPolicy::from)
.unwrap_or_default(),
vision: def.vision,
models: def
.models
.iter()
.map(|(id, entry)| {
let mapped = match entry {
ModelReasoningDef::Toggle(on) => crate::provider::ModelReasoning::Toggle(*on),
ModelReasoningDef::Policy(policy) => {
crate::provider::ModelReasoning::Policy(policy.clone())
}
};
(id.clone(), mapped)
})
.collect(),
}
}
pub(crate) fn clamp_timeout(secs: Option<u64>) -> Duration {
Duration::from_secs(secs.unwrap_or(DEFAULT_TIMEOUT.as_secs()))
.clamp(Duration::from_secs(1), MAX_TIMEOUT)
}
pub fn mcp_timeout(cfg: &crate::config::Config) -> Duration {
clamp_timeout(cfg.plugins.mcp_timeout_secs)
}
#[derive(Debug, Clone, Copy)]
pub struct McpSettings(pub Option<Duration>);
impl McpSettings {
pub fn from_config(cfg: &crate::config::Config) -> Self {
Self(if cfg.no_mcp {
None
} else {
Some(mcp_timeout(cfg))
})
}
}
fn declares_only_profiles(manifest: &Manifest) -> bool {
!manifest.provider_profiles.is_empty()
&& manifest.tools.is_empty()
&& manifest.prompts.is_empty()
&& manifest.hooks.is_empty()
&& manifest.mcp.is_empty()
}
pub fn load(dirs: &[PathBuf], enabled: &[String]) -> Plugins {
let mut out = Plugins {
mcp: Some(DEFAULT_TIMEOUT),
..Default::default()
};
let mut loaded: Vec<String> = Vec::new();
let mut failed: Vec<String> = Vec::new();
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
paths.sort();
for path in paths {
if !path.join(MANIFEST).is_file() {
continue;
}
let dir_name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
let listed = enabled.contains(&dir_name);
if loaded.contains(&dir_name) {
continue;
}
if !listed {
match read_manifest(&path, &dir_name) {
Ok(mut plugin) if declares_only_profiles(&plugin.manifest) => {
loaded.push(dir_name);
plugin.enabled = false;
out.plugins.push(plugin);
}
_ => continue,
}
continue;
}
match read_manifest(&path, &dir_name) {
Ok(plugin) => {
loaded.push(dir_name);
out.plugins.push(plugin);
}
Err(why) => {
failed.push(dir_name);
out.problems.push(why);
}
}
}
}
for name in enabled {
if !loaded.contains(name) && !failed.contains(name) {
out.problems.push(format!(
"plugin `{name}` is enabled but was not found in any plugin directory"
));
}
}
for plugin in &mut out.plugins {
let mut resolved = Vec::new();
let mut problems = Vec::new();
for def in &plugin.manifest.prompts {
match (&def.text, &def.file) {
(Some(text), None) => resolved.push(PromptDef {
text: Some(text.clone()),
file: None,
}),
(None, Some(rel)) => {
let path = match manifest_path(&plugin.dir, rel) {
Ok(path) => path,
Err(why) => {
problems.push(format!("plugin `{}`: prompt file {why}", plugin.name));
continue;
}
};
match read_prompt_file(&path) {
Ok((text, cut)) => {
if cut {
problems.push(format!(
"plugin `{}`: prompt file {} is over {MAX_MANIFEST_FILE_BYTES} bytes and was truncated",
plugin.name,
path.display()
));
}
resolved.push(PromptDef {
text: Some(text),
file: None,
})
}
Err(e) => problems.push(format!(
"plugin `{}`: prompt file {}: {e}",
plugin.name,
path.display()
)),
}
}
(Some(_), Some(_)) => problems.push(format!(
"plugin `{}`: a prompt must have either `text` or `file`, not both",
plugin.name
)),
(None, None) => problems.push(format!(
"plugin `{}`: a prompt needs `text` or `file`",
plugin.name
)),
}
}
plugin.manifest.prompts = resolved;
out.problems.extend(problems);
}
out
}
pub const MAX_MANIFEST_FILE_BYTES: u64 = 256 * 1024;
fn manifest_path(dir: &Path, rel: &str) -> std::result::Result<PathBuf, String> {
if rel.trim().is_empty() {
return Err("names no file".into());
}
let base = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
let path = dir.join(rel);
let resolved = std::fs::canonicalize(&path).map_err(|e| format!("{}: {e}", path.display()))?;
if !resolved.starts_with(&base) {
return Err(format!(
"{} points outside the plugin ({}); a manifest path has to stay inside its own \
directory",
path.display(),
resolved.display()
));
}
match std::fs::metadata(&resolved) {
Ok(meta) if meta.is_file() => Ok(resolved),
Ok(_) => Err(format!("{} is not a regular file", resolved.display())),
Err(e) => Err(format!("{}: {e}", resolved.display())),
}
}
fn read_prompt_file(path: &Path) -> Result<(String, bool), String> {
use std::io::Read as _;
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
file.take(MAX_MANIFEST_FILE_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
let cut = bytes.len() as u64 > MAX_MANIFEST_FILE_BYTES;
if !cut {
let text = String::from_utf8(bytes).map_err(|e| {
format!(
"not valid UTF-8 (first bad byte at offset {})",
e.utf8_error().valid_up_to()
)
})?;
return Ok((text, false));
}
let mut text = String::from_utf8_lossy(&bytes[..MAX_MANIFEST_FILE_BYTES as usize]).into_owned();
text.push_str(&format!(
"\n\n… (prompt file truncated at {MAX_MANIFEST_FILE_BYTES} bytes)"
));
Ok((text, true))
}
fn read_data_file(path: &Path) -> Result<String, String> {
let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
if meta.len() > MAX_MANIFEST_FILE_BYTES {
return Err(format!(
"is {} bytes; the limit is {MAX_MANIFEST_FILE_BYTES}",
meta.len()
));
}
std::fs::read_to_string(path).map_err(|e| e.to_string())
}
fn read_manifest(dir: &Path, dir_name: &str) -> Result<Plugin, String> {
let path = dir.join(MANIFEST);
let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
let manifest: Manifest =
toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
if manifest.name != dir_name {
return Err(format!(
"{}: name {:?} does not match its directory {:?}",
path.display(),
manifest.name,
dir_name
));
}
if manifest.api > API {
return Err(format!(
"{}: needs plugin api {}, this build speaks {API}",
path.display(),
manifest.api
));
}
for tool in &manifest.tools {
let ok = !tool.name.trim().is_empty()
&& tool
.name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
if !ok {
return Err(format!(
"{}: tool name {:?} must be [A-Za-z0-9_-]",
path.display(),
tool.name
));
}
}
Ok(Plugin {
name: manifest.name.clone(),
version: manifest.version.clone(),
description: manifest.description.clone(),
dir: dir.to_path_buf(),
manifest,
enabled: true,
})
}
pub(crate) const INHERITED_ENV: [&str; 4] = ["PATH", "HOME", "LANG", "TZ"];
struct Context<'a> {
plugin_dir: &'a Path,
workspace: &'a Path,
extra_env: &'a [String],
scripts_dir: Option<&'a Path>,
max_bytes: usize,
}
struct Output {
stdout: String,
stderr: String,
code: Option<i32>,
stdout_cut: bool,
}
async fn run_command(
command: &[String],
cwd: &Path,
timeout: Duration,
ctx: Context<'_>,
stdin_json: Value,
) -> Result<Output, String> {
let Some(bin) = command.first() else {
return Err("no command".into());
};
let mut cmd = tokio::process::Command::new(bin);
cmd.args(&command[1..])
.current_dir(cwd)
.env_clear()
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
for key in INHERITED_ENV {
if let Ok(v) = std::env::var(key) {
cmd.env(key, v);
}
}
for key in ctx.extra_env {
if let Ok(v) = std::env::var(key) {
cmd.env(key, v);
}
}
if let Some(dir) = ctx.scripts_dir {
cmd.env("ECLIPSE_SCRIPTS_DIR", dir);
}
cmd.env("ECLIPSE_PLUGIN_DIR", ctx.plugin_dir)
.env("ECLIPSE_WORKSPACE", ctx.workspace);
let payload = stdin_json.to_string();
if payload.len() <= ARGS_ENV_MAX {
cmd.env("ECLIPSE_ARGS", &payload);
} else {
cmd.env("ECLIPSE_ARGS_BYTES", payload.len().to_string());
}
if let Some(tool) = stdin_json.get("tool").and_then(|t| t.as_str()) {
cmd.env("ECLIPSE_TOOL", tool);
}
#[cfg(unix)]
cmd.process_group(0);
let mut child = cmd
.spawn()
.map_err(|e| format!("failed to start `{bin}`: {e}"))?;
let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
let cap = ctx.max_bytes;
let run = async {
if let Some(mut stdin) = child.stdin.take() {
use tokio::io::AsyncWriteExt;
let _ = stdin.write_all(payload.as_bytes()).await;
}
let (out, err) = tokio::join!(read_capped(stdout, cap), read_capped(stderr, cap));
(out, err, child.wait().await)
};
let outcome = tokio::time::timeout(timeout, run).await;
if outcome.is_err() {
stop_group(&mut child).await;
}
match outcome {
Err(_) => Err(format!("timed out after {}s", timeout.as_secs())),
Ok(((out, out_cut), (err, _), status)) => {
let status = status.map_err(|e| format!("failed to wait: {e}"))?;
Ok(Output {
stdout: out,
stderr: err,
code: status.code(),
stdout_cut: out_cut,
})
}
}
}
async fn stop_group(child: &mut tokio::process::Child) {
#[cfg(unix)]
if let Some(pid) = child.id() {
unsafe {
libc::kill(-(pid as i32), libc::SIGKILL);
}
}
let _ = child.start_kill();
let _ = child.wait().await;
}
struct CommandTool {
name: String,
description: String,
parameters: Value,
command: Vec<String>,
plugin: String,
plugin_dir: PathBuf,
workspace: PathBuf,
cwd: Cwd,
timeout: Duration,
env: Vec<String>,
max_bytes: usize,
scripts_dir: Option<PathBuf>,
}
#[async_trait]
impl Tool for CommandTool {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
&self.description
}
fn parameters(&self) -> Value {
self.parameters.clone()
}
fn describe_call(&self, args: &Value) -> String {
format!("run {}({args}) from plugin {}", self.name, self.plugin)
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let cwd = match self.cwd {
Cwd::Workspace => self.workspace.clone(),
Cwd::Plugin => self.plugin_dir.clone(),
};
let payload = json!({
"tool": self.name,
"arguments": args,
"plugin": self.plugin,
"workspace": self.workspace.display().to_string(),
});
let out = run_command(
&self.command,
&cwd,
self.timeout,
Context {
plugin_dir: &self.plugin_dir,
workspace: &self.workspace,
extra_env: &self.env,
scripts_dir: self.scripts_dir.as_deref(),
max_bytes: self.max_bytes,
},
payload,
)
.await
.map_err(ToolError::Failed)?;
let truncated = if out.stdout_cut { "\n[truncated]" } else { "" };
let stdout = out.stdout.trim_end_matches('\n');
if out.code == Some(0) {
return Ok(format!("{stdout}{truncated}"));
}
let code = out
.code
.map(|c| c.to_string())
.unwrap_or_else(|| "signal".into());
Err(ToolError::Failed(format!(
"exit code {code}\nstdout:\n{stdout}{truncated}\nstderr:\n{}",
out.stderr.trim_end_matches('\n')
)))
}
}
pub struct Hook {
event: Event,
tool: Option<String>,
command: Vec<String>,
timeout: Duration,
cwd: Cwd,
env: Vec<String>,
plugin_dir: PathBuf,
plugin: String,
max_bytes: usize,
scripts_dir: Option<PathBuf>,
}
impl Hook {
fn matches(&self, tool: &str) -> bool {
match &self.tool {
None => true,
Some(p) if p == "*" => true,
Some(p) => p == tool,
}
}
}
pub enum Verdict {
Allow,
Deny(String),
}
#[derive(Default, Clone)]
pub struct Hooks {
hooks: Vec<Arc<Hook>>,
workspace: PathBuf,
profile: String,
}
impl Hooks {
pub fn new(hooks: Vec<Arc<Hook>>, workspace: PathBuf, profile: impl Into<String>) -> Self {
Self {
hooks,
workspace,
profile: profile.into(),
}
}
pub async fn before(&self, tool: &str, arguments: &Value, call_id: Option<&str>) -> Verdict {
for hook in self.hooks.iter().filter(|h| h.event == Event::BeforeTool) {
if !hook.matches(tool) {
continue;
}
let payload = json!({
"event": "before_tool",
"tool": tool,
"arguments": arguments,
"call_id": call_id,
"plugin": hook.plugin,
"workspace": self.workspace.display().to_string(),
"profile": self.profile,
});
let out = self.run(hook, payload).await;
match out {
Ok(o) if o.code == Some(0) => continue,
Ok(o) => {
let reason = if !o.stderr.trim().is_empty() {
o.stderr.trim().to_string()
} else if !o.stdout.trim().is_empty() {
o.stdout.trim().to_string()
} else {
format!("refused by plugin `{}`", hook.plugin)
};
return Verdict::Deny(reason);
}
Err(why) => {
return Verdict::Deny(format!(
"refused: the `{}` guard for this tool could not run ({why})",
hook.plugin
))
}
}
}
Verdict::Allow
}
pub async fn after(
&self,
tool: &str,
arguments: &Value,
outcome: ToolOutcome,
call_id: Option<&str>,
) -> ToolOutcome {
let mut outcome = outcome;
for hook in self.hooks.iter().filter(|h| h.event == Event::AfterTool) {
if !hook.matches(tool) {
continue;
}
let payload = json!({
"event": "after_tool",
"tool": tool,
"arguments": arguments,
"output": outcome.output.clone(),
"is_error": outcome.is_error,
"call_id": call_id,
"plugin": hook.plugin,
"workspace": self.workspace.display().to_string(),
"profile": self.profile,
});
if let Ok(o) = self.run(hook, payload).await {
if o.code == Some(0) && !o.stdout.trim().is_empty() {
outcome.output = o.stdout.trim_end_matches('\n').to_string();
}
}
}
outcome
}
async fn run(&self, hook: &Hook, payload: Value) -> Result<Output, String> {
let cwd = match hook.cwd {
Cwd::Workspace => self.workspace.clone(),
Cwd::Plugin => hook.plugin_dir.clone(),
};
run_command(
&hook.command,
&cwd,
hook.timeout,
Context {
plugin_dir: &hook.plugin_dir,
workspace: &self.workspace,
extra_env: &hook.env,
scripts_dir: hook.scripts_dir.as_deref(),
max_bytes: hook.max_bytes,
},
payload,
)
.await
}
}
pub fn discover_all(dirs: &[PathBuf]) -> Vec<(String, PathBuf)> {
let mut out: Vec<(String, PathBuf)> = Vec::new();
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
paths.sort();
for path in paths {
if path.join(MANIFEST).is_file() {
let name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
if !out.iter().any(|(n, _)| n == &name) {
out.push((name, path));
}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_timed_out_plugin_takes_its_grandchild_with_it() {
let dir = tempfile::tempdir().unwrap();
let pidfile = dir.path().join("grandchild.pid");
let script = format!("sleep 30 & echo $! > {}; wait", pidfile.display());
let ctx = Context {
plugin_dir: dir.path(),
workspace: dir.path(),
extra_env: &[],
scripts_dir: None,
max_bytes: 64 * 1024,
};
let out = run_command(
&["sh".into(), "-c".into(), script],
dir.path(),
std::time::Duration::from_millis(400),
ctx,
serde_json::json!({}),
)
.await;
assert!(out.is_err(), "the timeout is the answer");
let pid: i32 = std::fs::read_to_string(&pidfile)
.expect("the grandchild wrote its pid before the timeout")
.trim()
.parse()
.unwrap();
let mut gone = false;
for _ in 0..20 {
if unsafe { libc::kill(pid, 0) } != 0 {
gone = true;
break;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
assert!(gone, "the grandchild outlived the plugin that started it");
}
#[test]
fn an_mcp_listing_line_does_not_print_the_credentials_in_its_url() {
let spec: mcp::Spec = toml::from_str(
"name = \"gh\"\ntransport = \"http\"\nurl = \"https://user:pw@example.test/mcp?token=abc\"\n",
)
.unwrap();
let line = describe_command(&spec);
assert!(!line.contains("pw"), "{line}");
assert!(!line.contains("abc"), "{line}");
assert!(
line.contains("example.test/mcp"),
"the endpoint is still recognisable: {line}"
);
let plain: mcp::Spec = toml::from_str(
"name = \"plain\"\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n",
)
.unwrap();
assert_eq!(
describe_command(&plain),
"http https://example.test/mcp",
"nothing to hide, nothing changed"
);
}
fn write(dir: &Path, rel: &str, text: &str) {
let p = dir.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
fn manifest(dir: &Path, name: &str) {
write(
dir,
"plugin.toml",
&format!(
"name = \"{name}\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
[[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
command = [\"sh\", \"-c\", \"echo hello $ECLIPSE_ARGS\"]\n\
policy = \"allow\"\n"
),
);
}
#[test]
fn a_listing_says_where_a_token_env_resolves() {
let tmp = tempfile::tempdir().unwrap();
let kept = format!("ECLIPSE_TEST_LIST_{}", "TOKEN");
let absent = format!("{kept}_UNSET");
std::env::remove_var(&kept);
std::env::remove_var(&absent);
let mut cfg = crate::config::parse_text(&format!(
"[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{kept}\"\ndisabled = true\n\n\
[[mcp]]\nname = \"dead\"\ntransport = \"http\"\n\
url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{absent}\"\ndisabled = true\n"
))
.unwrap();
cfg.dotenv.values.insert(kept.clone(), "kept".to_string());
let loaded = load(&[], &[]).with_config_mcp(&cfg);
let (rows, _) = loaded.mcp_report(tmp.path());
let row = |name: &str| {
rows.iter()
.find(|r| r.name == name)
.unwrap_or_else(|| panic!("{name} is not listed: {rows:?}"))
};
assert_eq!(row("ha").token_env.as_deref(), Some(kept.as_str()));
assert_eq!(row("ha").token, crate::mcp::TokenSource::Dotenv);
assert_eq!(row("ha").token.as_str(), ".env");
assert_eq!(row("dead").token, crate::mcp::TokenSource::Unset);
assert_eq!(row("dead").token.as_str(), "unset");
}
#[test]
fn a_config_server_shadows_a_manifest_server_of_the_same_name() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("pack"),
"plugin.toml",
r#"name = "pack"
version = "0.1.0"
[[mcp]]
name = "notes"
command = "true"
policy = "allow"
"#,
);
let cfg =
crate::config::parse_text("[[mcp]]\nname = \"notes\"\ncommand = \"false\"\n").unwrap();
let loaded = load(&[dir], &["pack".into()]).with_config_mcp(&cfg);
let (servers, problems) = loaded.servers(tmp.path());
assert_eq!(servers.len(), 1, "one server, not two");
assert_eq!(servers[0].source.label(), "config:mcp:notes");
assert_eq!(servers[0].spec.command, "false", "the config's command");
assert!(
problems.iter().any(|p| p.contains("which wins")),
"the shadowed entry is said out loud: {problems:?}"
);
let alone = load(&[tmp.path().join("plugins")], &["pack".into()]);
let (servers, problems) = alone.servers(tmp.path());
assert_eq!(servers[0].source.label(), "plugin:mcp:notes");
assert!(problems.is_empty(), "{problems:?}");
}
#[test]
fn loads_an_enabled_plugin_and_its_tool() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
manifest(&dir.join("greeter"), "greeter");
let loaded = load(&[dir], &["greeter".into()]);
assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
assert_eq!(loaded.plugins.len(), 1);
assert_eq!(loaded.plugins[0].name, "greeter");
let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
assert!(problems.is_empty(), "{problems:?}");
assert_eq!(tools.len(), 1);
assert_eq!(tools[0].tool.name(), "greet");
assert_eq!(tools[0].policy, Policy::Allow);
}
#[cfg(unix)]
#[tokio::test]
async fn a_payload_too_big_for_the_environment_still_reaches_the_plugin() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins").join("sizer");
write(&dir, "size.sh", "#!/bin/sh\nprintf 'args=%s bytes=%s stdin=%s\\n' \"${ECLIPSE_ARGS:+set}\" \"${ECLIPSE_ARGS_BYTES:-none}\" \"$(wc -c)\"\n");
write(
&dir,
"plugin.toml",
"name = \"sizer\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
[[tool]]\nname = \"size\"\ndescription = \"Report what it was given\"\n\
command = [\"sh\", \"size.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\n",
);
let loaded = load(&[tmp.path().join("plugins")], &["sizer".into()]);
assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
assert!(problems.is_empty(), "{problems:?}");
let big = "x".repeat(200 * 1024);
let out = tools[0]
.tool
.call(json!({"body": big}))
.await
.expect("a large payload must not stop the plugin from starting");
assert!(
!out.contains("args=set"),
"the copy does not go into the environment: {out}"
);
assert!(
!out.contains("bytes=none"),
"the size does, so a plugin can tell empty from too big: {out}"
);
assert!(
!out.contains("stdin=0"),
"and the payload itself arrives on stdin: {out}"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_plugin_that_never_reads_its_input_still_times_out() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins").join("deaf");
write(&dir, "deaf.sh", "#!/bin/sh\nsleep 20\n");
write(
&dir,
"plugin.toml",
"name = \"deaf\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
[[tool]]\nname = \"deaf\"\ndescription = \"Never reads its input\"\n\
command = [\"sh\", \"deaf.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\ntimeout_secs = 1\n",
);
let loaded = load(&[tmp.path().join("plugins")], &["deaf".into()]);
assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
assert!(problems.is_empty(), "{problems:?}");
let big = "x".repeat(200 * 1024);
let call = tokio::time::timeout(
Duration::from_secs(8),
tools[0].tool.call(json!({"body": big})),
)
.await
.expect("a full pipe must not hold the call");
let err = call.expect_err("it never answered");
assert!(err.to_string().contains("timed out"), "{err}");
}
#[test]
fn a_plugin_that_is_not_enabled_is_ignored_without_noise() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
manifest(&dir.join("greeter"), "greeter");
let loaded = load(&[dir], &[]);
assert!(loaded.plugins.is_empty());
assert!(loaded.problems.is_empty());
}
#[test]
fn enabling_a_missing_plugin_is_reported() {
let tmp = tempfile::tempdir().unwrap();
let loaded = load(&[tmp.path().join("plugins")], &["nope".into()]);
assert!(
loaded.problems[0].contains("enabled but was not found"),
"{:?}",
loaded.problems
);
}
#[test]
fn a_name_that_does_not_match_the_directory_is_rejected() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
manifest(&dir.join("greeter"), "someone-else");
let loaded = load(&[dir], &["greeter".into()]);
assert!(loaded.plugins.is_empty());
assert!(
loaded.problems[0].contains("does not match"),
"{:?}",
loaded.problems
);
}
#[test]
fn a_newer_api_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("future"),
"plugin.toml",
"name = \"future\"\napi = 99\n",
);
let loaded = load(&[dir], &["future".into()]);
assert!(
loaded.problems[0].contains("needs plugin api 99"),
"{:?}",
loaded.problems
);
}
#[test]
fn unknown_manifest_keys_are_errors_not_silence() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("typo"),
"plugin.toml",
"name = \"typo\"\n[tool]\nname = \"x\"\nemabled = true\n",
);
let loaded = load(&[dir], &["typo".into()]);
assert!(loaded.plugins.is_empty());
assert!(!loaded.problems.is_empty());
}
#[test]
fn a_profile_copy_shadows_the_shared_copy() {
let tmp = tempfile::tempdir().unwrap();
let (shared, profile) = (
tmp.path().join("plugins"),
tmp.path().join("profile-plugins"),
);
for (root, marker) in [(&shared, "shared"), (&profile, "profile")] {
write(
&root.join("greeter"),
"plugin.toml",
&format!("name = \"greeter\"\ndescription = \"{marker}\"\n"),
);
}
let loaded = load(&[profile, shared], &["greeter".into()]);
assert_eq!(loaded.plugins.len(), 1);
assert_eq!(loaded.plugins[0].description, "profile");
}
#[test]
fn replacing_a_tool_needs_an_explicit_override() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("shadow"),
"plugin.toml",
"name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"nope\"\n\
command = [\"true\"]\n",
);
let builtin = vec!["shell".to_string()];
let loaded = load(std::slice::from_ref(&dir), &["shadow".into()]);
let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
assert!(tools.is_empty(), "a silent override must not happen");
assert!(problems[0].contains("override = true"), "{problems:?}");
write(
&dir.join("shadow"),
"plugin.toml",
"name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"mine\"\n\
override = true\ncommand = [\"true\"]\n",
);
let loaded = load(&[dir], &["shadow".into()]);
let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
assert!(problems.is_empty(), "{problems:?}");
assert_eq!(tools.len(), 1);
}
#[test]
fn a_tool_without_a_command_or_with_mcp_is_rejected_with_a_reason() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("broken"),
"plugin.toml",
"name = \"broken\"\n\
[[tool]]\nname = \"no_cmd\"\ndescription = \"x\"\n\
[[tool]]\nname = \"via_mcp\"\ndescription = \"x\"\nkind = \"mcp\"\n\
command = [\"x\"]\n",
);
let loaded = load(&[dir], &["broken".into()]);
let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
assert!(tools.is_empty());
assert_eq!(problems.len(), 2, "{problems:?}");
assert!(problems[0].contains("no `command`"), "{problems:?}");
assert!(
problems[1].contains("belongs on a `[[mcp]]` section"),
"{problems:?}"
);
}
const MCP_FIXTURE: &str = r#"#!/usr/bin/env python3
import json, sys
def send(obj):
sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
for line in sys.stdin:
if not line.strip():
continue
msg = json.loads(line)
mid, method = msg.get("id"), msg.get("method")
params = msg.get("params") or {}
if method == "initialize":
send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}}, "serverInfo": {"name": "fixture", "version": "0"}}})
elif method == "notifications/initialized":
pass
elif method == "tools/list":
send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
{"name": "read_text_file", "description": "Read a file",
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}},
{"name": "write_text_file", "description": "Write a file"}]}})
elif method == "tools/call":
send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
{"type": "text", "text": "called " + str(params.get("name"))}]}})
elif mid is not None:
send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no"}})
"#;
fn mcp_plugin(tmp: &Path, extra: &str) -> PathBuf {
let dir = tmp.join("plugins");
let script = dir.join("fs").join("server.py");
std::fs::create_dir_all(script.parent().unwrap()).unwrap();
std::fs::write(&script, MCP_FIXTURE).unwrap();
let manifest = format!(
"name = \"fs\"\n\n[[mcp]]\nname = \"files\"\ncommand = \"python3\"\n\
args = [\"{}\"]\ncwd = \"plugin\"\ntimeout_secs = 15\n{extra}\n",
script.display()
);
write(&dir.join("fs"), "plugin.toml", &manifest);
dir
}
#[test]
fn mcp_off_starts_no_server_at_all() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
let marker = tmp.path().join("spawned");
let script = dir.join("loud").join("server.sh");
std::fs::create_dir_all(script.parent().unwrap()).unwrap();
std::fs::write(&script, format!("#!/bin/sh\ntouch {}\n", marker.display())).unwrap();
write(
&dir.join("loud"),
"plugin.toml",
&format!(
"name = \"loud\"\n\n[[mcp]]\nname = \"loud\"\ncommand = \"/bin/sh\"\n\
args = [\"{}\"]\n",
script.display()
),
);
let on = load(std::slice::from_ref(&dir), &["loud".into()]);
let (_tools, problems) = on.tools(tmp.path(), 4096, &[]);
assert!(
!problems.is_empty(),
"a bad server is reported when MCP is on"
);
assert!(
marker.exists(),
"when MCP is on, the server process really ran"
);
std::fs::remove_file(&marker).unwrap();
let off = load(&[dir], &["loud".into()]).with_mcp(McpSettings(None));
let (tools, problems) = off.tools(tmp.path(), 4096, &[]);
assert!(
tools.is_empty(),
"no tools from a server that was never asked"
);
assert!(
problems.is_empty(),
"nothing to complain about when nothing ran: {problems:?}"
);
assert!(
!marker.exists(),
"with MCP off, no server process was spawned"
);
assert_eq!(
mcp_timeout(&crate::config::Config::default()),
DEFAULT_TIMEOUT
);
let mut cfg = crate::config::Config::default();
cfg.plugins.mcp_timeout_secs = Some(5);
assert_eq!(mcp_timeout(&cfg), Duration::from_secs(5));
}
#[test]
fn an_mcp_server_contributes_its_tools_with_their_own_source_and_policies() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.map(|o| !o.status.success())
.unwrap_or(true)
{
return;
}
let tmp = tempfile::tempdir().unwrap();
let dir = mcp_plugin(tmp.path(), "policies = { read_text_file = \"allow\" }");
let loaded = load(&[dir], &["fs".into()]);
assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
assert!(problems.is_empty(), "{problems:?}");
let names: Vec<&str> = tools.iter().map(|t| t.tool.name()).collect();
assert_eq!(names, ["read_text_file", "write_text_file"]);
for t in &tools {
assert_eq!(t.source.label(), "plugin:mcp:files", "{}", t.tool.name());
}
let read = tools
.iter()
.find(|t| t.tool.name() == "read_text_file")
.unwrap();
let write = tools
.iter()
.find(|t| t.tool.name() == "write_text_file")
.unwrap();
assert_eq!(read.policy, Policy::Allow);
assert_eq!(write.policy, Policy::Ask);
assert_eq!(
read.tool.parameters()["properties"]["path"]["type"],
"string"
);
let out = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(read.tool.call(json!({"path": "a.txt"})))
.unwrap();
assert_eq!(out, "called read_text_file");
let (again, _) = loaded.tools(tmp.path(), 4096, &[]);
assert_eq!(again.len(), 2);
let out = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(again[0].tool.call(json!({"path": "b.txt"})))
.unwrap();
assert_eq!(out, "called read_text_file");
}
#[test]
fn a_server_tool_that_collides_is_refused_unless_the_entry_says_override() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.map(|o| !o.status.success())
.unwrap_or(true)
{
return;
}
let tmp = tempfile::tempdir().unwrap();
let dir = mcp_plugin(tmp.path(), "");
let loaded = load(&[dir], &["fs".into()]);
let builtin = vec!["read_text_file".to_string()];
let (tools, problems) = loaded.tools(tmp.path(), 4096, &builtin);
assert_eq!(tools.len(), 1, "the other one still loads");
assert_eq!(tools[0].tool.name(), "write_text_file");
assert!(
problems[0].contains("collides") && problems[0].contains("override = true"),
"{problems:?}"
);
}
#[test]
fn a_server_that_will_not_start_is_one_problem_and_no_tools() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("dead"),
"plugin.toml",
"name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
);
let loaded = load(&[dir], &["dead".into()]);
assert!(loaded.problems.is_empty(), "the manifest itself is fine");
let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
assert!(tools.is_empty());
assert!(
problems[0].contains("could not start") && problems[0].contains("gone"),
"{problems:?}"
);
}
#[test]
fn inline_parameters_and_a_schema_file_both_work() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("p"),
"plugin.toml",
"name = \"p\"\n\
[[tool]]\nname = \"inline\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
parameters = { type = \"object\", properties = { n = { type = \"string\" } } }\n\
[[tool]]\nname = \"from_file\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
parameters = \"tools/from_file.json\"\n",
);
write(
&dir.join("p"),
"tools/from_file.json",
"{\"type\":\"object\",\"properties\":{\"n\":{\"type\":\"integer\"}}}",
);
let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
assert!(problems.is_empty(), "{problems:?}");
assert_eq!(
tools[0].tool.parameters()["properties"]["n"]["type"],
"string"
);
assert_eq!(
tools[1].tool.parameters()["properties"]["n"]["type"],
"integer"
);
std::fs::remove_file(dir.join("p/tools/from_file.json")).unwrap();
let loaded = load(&[dir], &["p".into()]);
let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
assert_eq!(tools.len(), 1);
assert!(problems[0].contains("from_file.json"), "{problems:?}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_command_tool_gets_json_on_stdin_and_returns_stdout() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("echoer"),
"plugin.toml",
"name = \"echoer\"\n[[tool]]\nname = \"echo_args\"\n\
description = \"Echo the JSON it was given\"\n\
command = [\"sh\", \"-c\", \"cat\"]\npolicy = \"allow\"\n",
);
let loaded = load(&[dir], &["echoer".into()]);
let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
let out = tools[0]
.tool
.call(json!({"path": "a.txt"}))
.await
.expect("tool should succeed");
let sent: Value = serde_json::from_str(&out).unwrap();
assert_eq!(sent["arguments"]["path"], "a.txt");
assert_eq!(sent["tool"], "echo_args");
}
#[cfg(unix)]
#[tokio::test]
async fn a_non_zero_exit_is_an_error_that_carries_both_streams() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("fail"),
"plugin.toml",
"name = \"fail\"\n[[tool]]\nname = \"boom\"\ndescription = \"x\"\n\
command = [\"sh\", \"-c\", \"echo out; echo bad >&2; exit 3\"]\npolicy = \"allow\"\n",
);
let loaded = load(&[dir], &["fail".into()]);
let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
assert!(err.contains("exit code 3"), "{err}");
assert!(err.contains("out") && err.contains("bad"), "{err}");
}
#[cfg(unix)]
#[tokio::test]
async fn the_command_runs_in_the_workspace_and_only_sees_the_allowed_environment() {
let tmp = tempfile::tempdir().unwrap();
let (dir, ws) = (tmp.path().join("plugins"), tmp.path().join("ws"));
std::fs::create_dir_all(&ws).unwrap();
std::env::set_var("PLUGIN_TEST_SECRET", "leak-me");
std::env::set_var("PLUGIN_TEST_ALLOWED", "ok");
write(
&dir.join("env"),
"plugin.toml",
"name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
command = [\"sh\", \"-c\", \"pwd; echo secret=[${PLUGIN_TEST_SECRET:-}]; \
echo allowed=[${PLUGIN_TEST_ALLOWED:-}]\"]\n\
env = [\"PLUGIN_TEST_ALLOWED\"]\npolicy = \"allow\"\n",
);
let loaded = load(&[dir], &["env".into()]);
let (tools, _) = loaded.tools(&ws, 4096, &[]);
let out = tools[0].tool.call(json!({})).await.unwrap();
let canonical = std::fs::canonicalize(&ws).unwrap();
assert!(out.contains(&canonical.display().to_string()), "{out}");
assert!(
out.contains("secret=[]"),
"the agent environment must not leak: {out}"
);
assert!(out.contains("allowed=[ok]"), "{out}");
std::env::remove_var("PLUGIN_TEST_SECRET");
std::env::remove_var("PLUGIN_TEST_ALLOWED");
}
#[cfg(unix)]
#[tokio::test]
async fn a_plugin_tool_is_told_where_the_scripts_are_and_its_path_is_left_alone() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
let scripts = tmp.path().join("scripts");
write(
&dir.join("env"),
"plugin.toml",
"name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
command = [\"sh\", \"-c\", \"echo scripts=[${ECLIPSE_SCRIPTS_DIR:-}]; echo path=[$PATH]\"]\n\
policy = \"allow\"\n",
);
let with = load(std::slice::from_ref(&dir), &["env".into()])
.with_scripts_dir(Some(scripts.clone()));
let (tools, _) = with.tools(tmp.path(), 4096, &[]);
let out = tools[0].tool.call(json!({})).await.unwrap();
assert!(
out.contains(&format!("scripts=[{}]", scripts.display())),
"{out}"
);
let path_line = out.lines().find(|l| l.starts_with("path=")).unwrap();
assert!(
!path_line.contains(&scripts.display().to_string()),
"a plugin's PATH must not gain the scripts directory: {out}"
);
let without = load(&[dir], &["env".into()]);
let (tools, _) = without.tools(tmp.path(), 4096, &[]);
let out = tools[0].tool.call(json!({})).await.unwrap();
assert!(out.contains("scripts=[]"), "{out}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_hook_process_is_told_where_the_scripts_are_too() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("guard"),
"plugin.toml",
"name = \"guard\"\n\
[[hook]]\nevent = \"before_tool\"\n\
command = [\"sh\", \"-c\", \"echo $ECLIPSE_SCRIPTS_DIR >&2; exit 2\"]\n",
);
let loaded = load(&[dir], &["guard".into()])
.with_scripts_dir(Some(PathBuf::from("/somewhere/scripts")));
let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
match hooks.before("shell", &json!({}), None).await {
Verdict::Deny(why) => assert_eq!(why, "/somewhere/scripts"),
Verdict::Allow => panic!("the hook should have refused"),
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_slow_tool_times_out() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("slow"),
"plugin.toml",
"name = \"slow\"\n[[tool]]\nname = \"wait\"\ndescription = \"x\"\n\
command = [\"sleep\", \"30\"]\ntimeout_secs = 1\npolicy = \"allow\"\n",
);
let loaded = load(&[dir], &["slow".into()]);
let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
let started = std::time::Instant::now();
let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
assert!(err.contains("timed out after 1s"), "{err}");
assert!(started.elapsed() < Duration::from_secs(10));
}
#[test]
fn prompt_fragments_are_read_in_order_and_a_broken_one_is_a_problem() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("p"),
"plugin.toml",
"name = \"p\"\n\
[[prompt]]\ntext = \"first\"\n\
[[prompt]]\nfile = \"prompts/second.md\"\n",
);
write(&dir.join("p"), "prompts/second.md", "second");
let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
assert_eq!(loaded.prompts(), ["first", "second"]);
std::fs::remove_file(dir.join("p/prompts/second.md")).unwrap();
let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
assert_eq!(loaded.prompts(), ["first"]);
assert!(
loaded.problems[0].contains("prompt file"),
"{:?}",
loaded.problems
);
write(
&dir.join("p"),
"plugin.toml",
"name = \"p\"\n[[prompt]]\ntext = \"x\"\nfile = \"y\"\n",
);
let loaded = load(&[dir], &["p".into()]);
assert!(loaded.prompts().is_empty());
assert!(
loaded.problems[0].contains("either `text` or `file`"),
"{:?}",
loaded.problems
);
}
#[test]
fn a_manifest_path_that_points_outside_the_plugin_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
let secret = dir.join("id_rsa");
write(&dir, "id_rsa", "-----BEGIN OPENSSH PRIVATE KEY-----\n");
write(
&dir.join("p"),
"plugin.toml",
"name = \"p\"\n[[prompt]]\nfile = \"../id_rsa\"\n",
);
let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
assert!(
loaded
.problems
.iter()
.any(|p| p.contains("outside the plugin")),
"{:?}",
loaded.problems
);
write(
&dir.join("p"),
"plugin.toml",
&format!("name = \"p\"\n[[prompt]]\nfile = {secret:?}\n"),
);
let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
assert!(
loaded
.problems
.iter()
.any(|p| p.contains("outside the plugin")),
"{:?}",
loaded.problems
);
write(
&dir.join("p"),
"plugin.toml",
"name = \"p\"\n[[tool]]\nname = \"leak\"\ndescription = \"x\"\n\
command = [\"echo\"]\nparameters = \"../id_rsa\"\npolicy = \"allow\"\n",
);
let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
assert!(tools.is_empty(), "no tool was built from the link");
assert!(
problems.iter().any(|p| p.contains("outside the plugin")),
"{:?}",
problems
);
}
#[test]
fn a_manifest_path_inside_the_plugin_is_read_and_a_directory_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("p"),
"plugin.toml",
"name = \"p\"\n[[prompt]]\nfile = \"prompts/first.md\"\n",
);
write(&dir.join("p"), "prompts/first.md", "inside");
let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
assert_eq!(loaded.prompts(), ["inside"]);
std::fs::create_dir_all(dir.join("p/prompts/dir.md")).unwrap();
write(
&dir.join("p"),
"plugin.toml",
"name = \"p\"\n[[prompt]]\nfile = \"prompts/dir.md\"\n",
);
let loaded = load(&[dir], &["p".into()]);
assert!(loaded.prompts().is_empty());
assert!(
loaded
.problems
.iter()
.any(|p| p.contains("not a regular file")),
"{:?}",
loaded.problems
);
}
#[test]
fn a_plugin_loaded_for_its_profiles_is_not_enabled_and_has_no_skills_root() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("wire"),
"plugin.toml",
"name = \"wire\"\n\
[[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n",
);
write(
&dir.join("wire/skills/sneaky/SKILL.md"),
"SKILL.md",
"---\nname: sneaky\ndescription: not yours\n---\n\nx\n",
);
let loaded = load(std::slice::from_ref(&dir), &[]);
assert_eq!(
loaded.plugins.len(),
1,
"loaded for its profiles: {:?}",
loaded.problems
);
assert!(
!loaded.plugins[0].enabled,
"loaded is not the same as enabled"
);
let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
assert!(
!roots.iter().any(|r| r.dir.ends_with("wire/skills")),
"an unenabled plugin's skills are not roots: {roots:?}"
);
let loaded = load(&[dir], &["wire".into()]);
assert!(loaded.plugins[0].enabled);
let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
assert!(roots.iter().any(|r| r.dir.ends_with("wire/skills")));
}
#[test]
fn provider_profiles_override_by_name_and_keep_order() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("prov"),
"plugin.toml",
"name = \"prov\"\n\
[[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n\
[provider_profile.body]\nchat_template_kwargs = { enable_thinking = false }\n\
[[provider_profile]]\nname = \"acme\"\nsupports_tools = false\n",
);
let loaded = load(&[dir], &["prov".into()]);
let profiles = loaded.provider_profiles();
assert_eq!(profiles.len(), 2);
assert_eq!(profiles[0].name, "llamacpp");
assert!(!profiles[0].tool_choice);
assert_eq!(
profiles[0].body["chat_template_kwargs"]["enable_thinking"],
json!(false)
);
assert!(!profiles[1].supports_tools);
}
#[cfg(unix)]
#[tokio::test]
async fn a_before_tool_hook_can_refuse_with_a_reason() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("guard"),
"plugin.toml",
"name = \"guard\"\n\
[[hook]]\nevent = \"before_tool\"\ntool = \"shell\"\n\
command = [\"sh\", \"-c\", \"echo 'no shell in this repo' >&2; exit 2\"]\n",
);
let loaded = load(&[dir], &["guard".into()]);
assert_eq!(loaded.hooks().len(), 1);
let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
match hooks.before("shell", &json!({"command": "ls"}), None).await {
Verdict::Deny(why) => assert_eq!(why, "no shell in this repo"),
Verdict::Allow => panic!("the hook should have refused"),
}
assert!(matches!(
hooks.before("read_file", &json!({}), None).await,
Verdict::Allow
));
}
#[cfg(unix)]
#[tokio::test]
async fn a_guard_that_cannot_run_refuses_rather_than_allowing() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("broken-guard"),
"plugin.toml",
"name = \"broken-guard\"\n\
[[hook]]\nevent = \"before_tool\"\ncommand = [\"./missing.sh\"]\ncwd = \"plugin\"\n",
);
let loaded = load(&[dir], &["broken-guard".into()]);
let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
match hooks.before("anything", &json!({}), None).await {
Verdict::Deny(why) => assert!(why.contains("could not run"), "{why}"),
Verdict::Allow => panic!("a guard that cannot run must not silently allow"),
}
}
#[cfg(unix)]
#[tokio::test]
async fn an_after_tool_hook_can_rewrite_the_output() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("redact"),
"plugin.toml",
"name = \"redact\"\n\
[[hook]]\nevent = \"after_tool\"\n\
command = [\"sh\", \"-c\", \"printf 'the [redacted] is here'\"]\n",
);
let loaded = load(std::slice::from_ref(&dir), &["redact".into()]);
let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
let out = hooks
.after(
"read_file",
&json!({}),
ToolOutcome {
output: "the secret is here".into(),
is_error: false,
malformed: false,
deferred: false,
},
None,
)
.await;
assert_eq!(out.output, "the [redacted] is here");
assert!(!out.is_error);
write(
&dir.join("quiet"),
"plugin.toml",
"name = \"quiet\"\n\
[[hook]]\nevent = \"after_tool\"\ncommand = [\"true\"]\n",
);
let quiet = load(&[dir], &["quiet".into()]);
let hooks = Hooks::new(quiet.hooks(), PathBuf::from("/tmp"), "default");
let out = hooks
.after(
"read_file",
&json!({}),
ToolOutcome {
output: "unchanged".into(),
is_error: true,
malformed: false,
deferred: false,
},
None,
)
.await;
assert_eq!(out.output, "unchanged");
assert!(out.is_error);
}
#[test]
fn the_shipped_examples_all_load() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/plugins");
if !root.is_dir() {
return;
}
let names: Vec<String> = discover_all(std::slice::from_ref(&root))
.into_iter()
.map(|(name, _)| name)
.collect();
assert!(!names.is_empty(), "no examples found in {}", root.display());
let loaded = load(std::slice::from_ref(&root), &names);
assert!(
loaded.problems.is_empty(),
"the shipped examples must load cleanly: {:?}",
loaded.problems
);
let (tools, problems) = loaded.tools(&root, 4096, &[]);
assert!(problems.is_empty(), "{problems:?}");
assert_eq!(tools.len(), 3, "git_status, git_diff, git_log");
assert_eq!(loaded.provider_profiles().len(), 1);
assert_eq!(loaded.hooks().len(), 1);
assert!(!loaded.prompts().is_empty());
}
#[test]
fn discover_all_lists_manifests_whether_enabled_or_not() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
manifest(&dir.join("a"), "a");
manifest(&dir.join("b"), "b");
std::fs::create_dir_all(dir.join("not-a-plugin")).unwrap();
let found = discover_all(&[dir]);
assert_eq!(found.len(), 2);
}
#[cfg(unix)]
#[tokio::test]
async fn a_hook_payload_names_the_tool_call_it_is_about() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("echo-payload"),
"plugin.toml",
"name = \"echo-payload\"\n\
[[hook]]\nevent = \"after_tool\"\ncommand = [\"sh\", \"-c\", \"cat\"]\n",
);
let loaded = load(&[dir], &["echo-payload".into()]);
let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
let outcome = || ToolOutcome {
output: "x".into(),
is_error: false,
malformed: false,
deferred: false,
};
let named = hooks
.after("read_file", &json!({}), outcome(), Some("c7"))
.await;
assert!(
named.output.contains("\"call_id\":\"c7\""),
"a hook must be able to tell concurrent calls apart: {}",
named.output
);
let unnamed = hooks.after("read_file", &json!({}), outcome(), None).await;
assert!(
unnamed.output.contains("\"call_id\":null"),
"{}",
unnamed.output
);
}
}
#[cfg(test)]
mod size_cap_tests {
use super::*;
fn write(dir: &Path, rel: &str, text: &str) {
let p = dir.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
#[test]
fn an_oversized_prompt_file_is_cut_and_says_so() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("longprompt"),
"plugin.toml",
"name = \"longprompt\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
[[prompt]]\nfile = \"prompts/rules.md\"\n",
);
let line = "keep the answer short and cite the file. ";
let body = line.repeat((MAX_MANIFEST_FILE_BYTES as usize / line.len()) + 10);
write(&dir.join("longprompt"), "prompts/rules.md", &body);
let loaded = load(&[dir], &["longprompt".into()]);
assert!(
loaded
.problems
.iter()
.any(|p| p.contains("truncated") && p.contains("rules.md")),
"the truncation is reported to the human: {:?}",
loaded.problems
);
let text = loaded.plugins[0].manifest.prompts[0]
.text
.as_deref()
.expect("the prompt resolves");
assert!(
text.len() <= MAX_MANIFEST_FILE_BYTES as usize + 128,
"the prompt is capped, not passed through: {} bytes",
text.len()
);
assert!(
text.ends_with("bytes)"),
"and the model is told the text is incomplete: …{}",
&text[text.len().saturating_sub(80)..]
);
assert!(
text.contains(line.trim()),
"the part that arrived is the real text, not a placeholder"
);
}
#[test]
fn an_oversized_parameters_file_is_refused_not_truncated() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
write(
&dir.join("paramtool"),
"plugin.toml",
"name = \"paramtool\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
[[tool]]\nname = \"thing\"\ndescription = \"A thing\"\n\
command = [\"sh\", \"-c\", \"echo hi\"]\npolicy = \"allow\"\n\
parameters = \"params.json\"\n",
);
let filler = "x".repeat(MAX_MANIFEST_FILE_BYTES as usize + 1);
write(
&dir.join("paramtool"),
"params.json",
&format!("{{\"type\":\"object\",\"description\":\"{filler}\"}}"),
);
let loaded = load(&[dir], &["paramtool".into()]);
let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
assert!(
problems
.iter()
.any(|p| p.contains("limit is") && p.contains("params.json")),
"the refusal names the file and both sizes: {problems:?}"
);
assert!(
tools.is_empty(),
"the tool is not loaded with parameters nobody could read"
);
}
}