1use crate::config::Policy;
29use crate::mcp;
30use crate::provider::ProviderProfile;
31use crate::tools::{read_capped, Tool, ToolError, ToolOutcome, ToolSource};
32use async_trait::async_trait;
33use serde::Deserialize;
34use serde_json::{json, Value};
35use std::collections::BTreeMap;
36use std::path::{Path, PathBuf};
37use std::sync::{Arc, Mutex};
38use std::time::Duration;
39
40pub const API: u32 = 1;
42
43pub const MANIFEST: &str = "plugin.toml";
45
46const ARGS_ENV_MAX: usize = 64 * 1024;
50
51pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
53
54pub const MAX_TIMEOUT: Duration = Duration::from_secs(600);
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
59#[serde(rename_all = "lowercase")]
60pub enum Kind {
61 #[default]
63 Command,
64 Mcp,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
71#[serde(rename_all = "lowercase")]
72pub enum Cwd {
73 #[default]
75 Workspace,
76 Plugin,
78}
79
80#[derive(Debug, Clone, Deserialize)]
82#[serde(untagged)]
83pub enum Parameters {
84 File(String),
86 Inline(Box<toml::Value>),
88}
89
90#[derive(Debug, Clone, Deserialize)]
91#[serde(deny_unknown_fields)]
92pub struct ToolDef {
93 pub name: String,
94 pub description: String,
95 #[serde(default)]
96 pub parameters: Option<Parameters>,
97 #[serde(default)]
98 pub kind: Kind,
99 #[serde(default)]
101 pub command: Vec<String>,
102 #[serde(default)]
103 pub cwd: Cwd,
104 #[serde(default)]
105 pub timeout_secs: Option<u64>,
106 #[serde(default)]
108 pub policy: Option<Policy>,
109 #[serde(default)]
111 pub env: Vec<String>,
112 #[serde(default, rename = "override")]
114 pub override_builtin: bool,
115}
116
117#[derive(Debug, Clone, Deserialize)]
118#[serde(deny_unknown_fields)]
119pub struct PromptDef {
120 #[serde(default)]
121 pub text: Option<String>,
122 #[serde(default)]
124 pub file: Option<String>,
125}
126
127#[derive(Debug, Clone, Deserialize)]
128#[serde(deny_unknown_fields)]
129pub struct ProfileDef {
130 pub name: String,
131 #[serde(default = "yes")]
133 pub tool_choice: bool,
134 #[serde(default = "yes")]
136 pub stream_usage: bool,
137 #[serde(default)]
139 pub max_tokens_field: Option<String>,
140 #[serde(default = "yes")]
142 pub supports_tools: bool,
143 #[serde(default)]
146 pub body: Option<toml::Value>,
147 #[serde(default)]
151 pub reasoning: Option<crate::reasoning::Policy>,
152 #[serde(default)]
154 pub models: BTreeMap<String, ModelReasoningDef>,
155 #[serde(default)]
157 pub request: Option<RequestDef>,
158 #[serde(default)]
161 pub vision: Option<bool>,
162}
163
164#[derive(Debug, Clone, Deserialize, Default)]
166#[serde(deny_unknown_fields)]
167pub struct RequestDef {
168 #[serde(default)]
170 pub num_ctx: Option<u32>,
171 #[serde(default)]
173 pub num_ctx_field: Option<String>,
174 #[serde(default)]
176 pub max_output: Option<u32>,
177 #[serde(default)]
179 pub temperature: Option<TemperatureDef>,
180 #[serde(default)]
182 pub reject_response_formats: Vec<String>,
183 #[serde(default)]
185 pub aux_model: Option<String>,
186 #[serde(default)]
188 pub models: BTreeMap<String, LimitDef>,
189}
190
191#[derive(Debug, Clone, Deserialize)]
193#[serde(untagged)]
194pub enum TemperatureDef {
195 Mode(String),
196 Fixed { fixed: f32 },
197}
198
199#[derive(Debug, Clone, Deserialize, Default)]
201#[serde(deny_unknown_fields)]
202pub struct LimitDef {
203 #[serde(default)]
204 pub num_ctx: Option<u32>,
205 #[serde(default)]
206 pub max_output: Option<u32>,
207}
208
209impl From<&RequestDef> for crate::provider::RequestPolicy {
210 fn from(def: &RequestDef) -> Self {
211 Self {
212 num_ctx: def.num_ctx,
213 num_ctx_field: def.num_ctx_field.clone(),
214 max_output: def.max_output,
215 temperature: def.temperature.as_ref().map(|t| match t {
216 TemperatureDef::Fixed { fixed } => crate::provider::Temperature::Fixed(*fixed),
217 TemperatureDef::Mode(mode) if mode.eq_ignore_ascii_case("omit") => {
218 crate::provider::Temperature::Omit
219 }
220 TemperatureDef::Mode(_) => crate::provider::Temperature::Default,
221 }),
222 reject_response_formats: def.reject_response_formats.clone(),
223 aux_model: def.aux_model.clone(),
224 models: def
225 .models
226 .iter()
227 .map(|(id, limit)| {
228 (
229 id.clone(),
230 crate::provider::ModelLimits {
231 num_ctx: limit.num_ctx,
232 max_output: limit.max_output,
233 },
234 )
235 })
236 .collect(),
237 }
238 }
239}
240
241#[derive(Debug, Clone, Deserialize)]
243#[serde(untagged)]
244pub enum ModelReasoningDef {
245 Toggle(bool),
246 Policy(crate::reasoning::Policy),
247}
248
249fn yes() -> bool {
250 true
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
254#[serde(rename_all = "snake_case")]
255pub enum Event {
256 BeforeTool,
257 AfterTool,
258}
259
260#[derive(Debug, Clone, Deserialize)]
261#[serde(deny_unknown_fields)]
262pub struct HookDef {
263 pub event: Event,
264 #[serde(default)]
266 pub tool: Option<String>,
267 #[serde(default)]
268 pub command: Vec<String>,
269 #[serde(default)]
270 pub timeout_secs: Option<u64>,
271 #[serde(default)]
272 pub cwd: Cwd,
273 #[serde(default)]
274 pub env: Vec<String>,
275}
276
277#[derive(Debug, Clone, Deserialize)]
278#[serde(deny_unknown_fields)]
279pub struct Manifest {
280 pub name: String,
281 #[serde(default)]
282 pub version: String,
283 #[serde(default)]
284 pub description: String,
285 #[serde(default = "current_api")]
287 pub api: u32,
288 #[serde(default, rename = "tool")]
289 pub tools: Vec<ToolDef>,
290 #[serde(default, rename = "prompt")]
291 pub prompts: Vec<PromptDef>,
292 #[serde(default, rename = "provider_profile")]
293 pub provider_profiles: Vec<ProfileDef>,
294 #[serde(default, rename = "hook")]
295 pub hooks: Vec<HookDef>,
296 #[serde(default, rename = "mcp")]
299 pub mcp: Vec<crate::mcp::Spec>,
300}
301
302fn current_api() -> u32 {
303 API
304}
305
306#[derive(Debug, Clone)]
308pub struct Plugin {
309 pub name: String,
310 pub version: String,
311 pub description: String,
312 pub dir: PathBuf,
314 pub manifest: Manifest,
315 pub enabled: bool,
320}
321
322#[derive(Clone)]
325pub struct PluginTool {
326 pub tool: Arc<dyn Tool>,
327 pub policy: Policy,
328 pub source: ToolSource,
332}
333
334pub type ToolsAndProblems = (Vec<PluginTool>, Vec<String>);
335
336struct ServerRef<'a> {
339 spec: &'a mcp::Spec,
340 base: PathBuf,
342 owner: String,
344 source: ToolSource,
345}
346
347#[derive(Debug, Clone)]
349pub struct McpServerState {
350 pub name: String,
351 pub source: ToolSource,
352 pub owner: String,
353 pub command: String,
355 pub transport: crate::mcp::Transport,
358 pub program: String,
359 pub args: Vec<String>,
360 pub url: Option<String>,
361 pub policy: Policy,
362 pub prefix: String,
363 pub timeout_secs: u64,
364 pub disabled: bool,
365 pub tools: usize,
368 pub error: Option<String>,
369 pub token_env: Option<String>,
372 pub token: crate::mcp::TokenSource,
375 pub protocol: Option<String>,
378 pub server_name: Option<String>,
379 pub server_version: Option<String>,
380}
381
382fn describe_command(spec: &mcp::Spec) -> String {
385 match spec.transport {
386 crate::mcp::Transport::Stdio => {
387 let mut out = spec.command.clone();
388 for arg in &spec.args {
389 out.push(' ');
390 out.push_str(arg);
391 }
392 out
393 }
394 crate::mcp::Transport::Http => {
395 let url = spec.url.as_deref().unwrap_or("(no url declared)");
399 format!(
400 "http {}",
401 crate::config::redact_url(url).unwrap_or_else(|| url.to_string())
402 )
403 }
404 }
405}
406
407type StartedServer = Result<(Arc<crate::mcp::Server>, Vec<crate::mcp::RemoteTool>), String>;
411
412#[derive(Debug, Clone, Default)]
414pub struct Plugins {
415 pub plugins: Vec<Plugin>,
416 pub problems: Vec<String>,
419 scripts_dir: Option<PathBuf>,
422 mcp: Option<Duration>,
425 config_mcp: Vec<mcp::Spec>,
428 secrets: crate::mcp::Secrets,
432 servers: Arc<Mutex<BTreeMap<String, StartedServer>>>,
436}
437
438impl Plugins {
439 pub fn with_scripts_dir(mut self, dir: Option<PathBuf>) -> Self {
442 self.scripts_dir = dir;
443 self
444 }
445
446 pub fn with_mcp(mut self, settings: McpSettings) -> Self {
449 self.mcp = settings.0;
450 self
451 }
452
453 pub fn with_config_mcp(mut self, cfg: &crate::config::Config) -> Self {
460 self.config_mcp = cfg.mcp.clone();
461 self.secrets = cfg.dotenv.values.clone();
462 self
463 }
464
465 pub fn get(&self, name: &str) -> Option<&Plugin> {
466 self.plugins.iter().find(|p| p.name == name)
467 }
468
469 pub fn prompts(&self) -> Vec<String> {
472 self.plugins
473 .iter()
474 .flat_map(|p| p.manifest.prompts.iter())
475 .filter_map(|d| d.text.clone())
476 .collect()
477 }
478
479 pub fn provider_profiles(&self) -> Vec<ProviderProfile> {
482 let mut out: Vec<ProviderProfile> = Vec::new();
483 for plugin in &self.plugins {
484 for def in &plugin.manifest.provider_profiles {
485 let profile = profile_from_def(def);
486 match out.iter_mut().find(|p| p.name == profile.name) {
487 Some(slot) => *slot = profile,
488 None => out.push(profile),
489 }
490 }
491 }
492 out
493 }
494
495 pub fn tools(
499 &self,
500 workspace: &Path,
501 max_bytes: usize,
502 builtin: &[String],
503 ) -> ToolsAndProblems {
504 let mut out: Vec<PluginTool> = Vec::new();
505 let mut problems = Vec::new();
506 for plugin in &self.plugins {
507 for def in &plugin.manifest.tools {
508 let mut problem = |why: String| {
509 problems.push(format!(
510 "plugin `{}`: tool `{}`: {why}",
511 plugin.name, def.name
512 ));
513 };
514 if def.kind == Kind::Mcp {
515 problem(
518 concat!(
519 "kind = \"mcp\" belongs on a `[[mcp]]` section, not on one tool: ",
520 "an MCP server contributes all of its tools from a single entry"
521 )
522 .to_string(),
523 );
524 continue;
525 }
526 if def.command.is_empty() {
527 problem("no `command` given".into());
528 continue;
529 }
530 let taken = builtin.iter().any(|b| b == &def.name)
531 || out.iter().any(|t| t.tool.name() == def.name);
532 if taken && !def.override_builtin {
533 problem(
534 "collides with a tool that already exists; set `override = true` on it \
535 to replace it"
536 .into(),
537 );
538 continue;
539 }
540 let parameters = match &def.parameters {
541 None => json!({"type": "object", "properties": {}}),
542 Some(Parameters::Inline(v)) => match serde_json::to_value(v) {
543 Ok(v) => v,
544 Err(e) => {
545 problem(format!("inline parameters are not valid JSON: {e}"));
546 continue;
547 }
548 },
549 Some(Parameters::File(rel)) => {
550 let path = match manifest_path(&plugin.dir, rel) {
551 Ok(path) => path,
552 Err(why) => {
553 problem(why);
554 continue;
555 }
556 };
557 match read_data_file(&path) {
558 Ok(text) => match serde_json::from_str::<Value>(&text) {
559 Ok(v) => v,
560 Err(e) => {
561 problem(format!("{}: {e}", path.display()));
562 continue;
563 }
564 },
565 Err(e) => {
566 problem(format!("{}: {e}", path.display()));
567 continue;
568 }
569 }
570 }
571 };
572 let policy = def.policy.unwrap_or(Policy::Ask);
573 let tool = CommandTool {
574 name: def.name.clone(),
575 description: def.description.clone(),
576 parameters,
577 command: def.command.clone(),
578 plugin: plugin.name.clone(),
579 plugin_dir: plugin.dir.clone(),
580 workspace: workspace.to_path_buf(),
581 cwd: def.cwd,
582 timeout: clamp_timeout(def.timeout_secs),
583 env: def.env.clone(),
584 max_bytes,
585 scripts_dir: self.scripts_dir.clone(),
586 };
587 out.push(PluginTool {
588 tool: Arc::new(tool) as Arc<dyn Tool>,
589 policy,
590 source: ToolSource::Plugin(plugin.name.clone()),
591 });
592 }
593 }
594 self.mcp_tools(workspace, builtin, &mut out, &mut problems);
597 (out, problems)
598 }
599
600 fn servers(&self, workspace: &Path) -> (Vec<ServerRef<'_>>, Vec<String>) {
608 let mut problems = Vec::new();
609 let mut out: Vec<ServerRef> = Vec::new();
610 for plugin in &self.plugins {
611 for spec in &plugin.manifest.mcp {
612 out.push(ServerRef {
613 spec,
614 base: plugin.dir.clone(),
615 owner: format!("plugin `{}`", plugin.name),
616 source: ToolSource::Plugin(format!("mcp:{}", spec.name)),
617 });
618 }
619 }
620 for spec in &self.config_mcp {
621 if let Some(pos) = out.iter().position(|s| s.spec.name == spec.name) {
624 let shadowed = out.remove(pos);
625 problems.push(format!(
626 "{}: mcp `{}` is also declared in config.toml, which wins; the manifest entry is ignored",
627 shadowed.owner, spec.name
628 ));
629 }
630 out.push(ServerRef {
631 spec,
632 base: workspace.to_path_buf(),
633 owner: "config".to_string(),
634 source: ToolSource::Config(format!("mcp:{}", spec.name)),
635 });
636 }
637 (out, problems)
638 }
639
640 pub fn mcp_report(&self, workspace: &Path) -> (Vec<McpServerState>, Vec<String>) {
643 let (servers, shadowed) = self.servers(workspace);
644 let problems = shadowed;
647 let mut out = Vec::new();
648 for server in servers {
649 let started = if server.spec.disabled {
653 None
654 } else {
655 Some(self.start(server.spec, &server.base, workspace))
656 };
657 let (tools, error, handshake) = match &started {
658 None => (0, None, None),
659 Some(Ok((session, tools))) => (tools.len(), None, session.handshake()),
660 Some(Err(why)) => (0, Some(why.clone()), None),
661 };
662 let field = |key: &str| {
663 handshake
664 .as_ref()
665 .and_then(|h| h.get(key))
666 .and_then(|v| v.as_str())
667 .map(str::to_string)
668 };
669 let info = |key: &str| {
672 handshake
673 .as_ref()
674 .and_then(|h| h.get("serverInfo"))
675 .and_then(|i| i.get(key))
676 .and_then(|v| v.as_str())
677 .map(str::to_string)
678 };
679 out.push(McpServerState {
680 name: server.spec.name.clone(),
681 source: server.source,
682 owner: server.owner,
683 command: describe_command(server.spec),
684 transport: server.spec.transport,
685 program: server.spec.command.clone(),
686 args: server.spec.args.clone(),
687 url: server.spec.url.clone(),
688 policy: server.spec.policy,
689 prefix: server.spec.prefix.clone(),
690 timeout_secs: server
691 .spec
692 .timeout_secs
693 .or_else(|| self.mcp.map(|d| d.as_secs()))
694 .unwrap_or(0),
695 disabled: server.spec.disabled,
696 token_env: server.spec.token_env.clone(),
697 token: server.spec.token_source(&self.secrets),
698 tools,
699 error,
700 protocol: field("protocolVersion"),
701 server_name: info("name"),
702 server_version: info("version"),
703 });
704 }
705 (out, problems)
706 }
707
708 fn mcp_tools(
711 &self,
712 workspace: &Path,
713 builtin: &[String],
714 out: &mut Vec<PluginTool>,
715 problems: &mut Vec<String>,
716 ) {
717 if self.mcp.is_none() {
718 return;
719 }
720 let (servers, shadowed) = self.servers(workspace);
721 problems.extend(shadowed);
722 for server in servers {
723 if server.spec.disabled {
724 continue;
725 }
726 if let Err(why) = server.spec.validate() {
729 problems.push(format!(
730 "{}: mcp `{}`: {why}",
731 server.owner, server.spec.name
732 ));
733 continue;
734 }
735 let (session, tools) = match self.start(server.spec, &server.base, workspace) {
736 Ok(started) => started,
737 Err(why) => {
738 problems.push(why);
739 continue;
740 }
741 };
742 for remote in tools {
743 let tool = crate::mcp::McpTool::new(Arc::clone(&session), &remote);
744 let name = tool.name().to_string();
745 let published = format!("{}{}", session.prefix(), remote.name);
750 if name != published {
751 problems.push(format!(
752 "{}: mcp `{}`: tool {:?} is called as `{}` (a name must be [A-Za-z0-9_-], at most {} characters)",
753 server.owner,
754 server.spec.name,
755 remote.name,
756 name.trim_start_matches(session.prefix()),
757 crate::mcp::TOOL_NAME_MAX
758 ));
759 }
760 let taken =
764 builtin.iter().any(|b| b == &name) || out.iter().any(|t| t.tool.name() == name);
765 if taken && !session.override_builtin() {
766 problems.push(format!(
767 concat!(
768 "{}: mcp `{}`: tool `{}` collides with a tool that ",
769 "already exists; set `override = true` on the server entry to replace it"
770 ),
771 server.owner, server.spec.name, name
772 ));
773 continue;
774 }
775 let policy = session.policy_for(&remote.name);
776 out.push(PluginTool {
777 tool: Arc::new(tool) as Arc<dyn Tool>,
778 policy,
779 source: server.source.clone(),
780 });
781 }
782 }
783 }
784
785 fn start(&self, spec: &mcp::Spec, base: &Path, workspace: &Path) -> StartedServer {
789 let Some(default_timeout) = self.mcp else {
790 return Err("MCP is off for this process (`--no-mcp`)".to_string());
791 };
792 let key = format!("{}:{}", base.display(), spec.name);
793 let mut cache = self.servers.lock().unwrap_or_else(|e| e.into_inner());
794 cache
795 .entry(key)
796 .or_insert_with(|| {
797 crate::mcp::Server::start(spec, base, workspace, default_timeout, &self.secrets)
798 .map_err(|e| format!("mcp `{}`: {e}", spec.name))
799 })
800 .clone()
801 }
802
803 pub fn hooks(&self) -> Vec<Arc<Hook>> {
805 self.plugins
806 .iter()
807 .flat_map(|p| {
808 p.manifest.hooks.iter().map(move |def| {
809 Arc::new(Hook {
810 event: def.event,
811 tool: def.tool.clone(),
812 command: def.command.clone(),
813 timeout: clamp_timeout(def.timeout_secs),
814 cwd: def.cwd,
815 env: def.env.clone(),
816 plugin_dir: p.dir.clone(),
817 plugin: p.name.clone(),
818 max_bytes: 64 * 1024,
819 scripts_dir: self.scripts_dir.clone(),
820 })
821 })
822 })
823 .collect()
824 }
825}
826
827pub fn profile_from_def(def: &ProfileDef) -> ProviderProfile {
831 ProviderProfile {
832 name: def.name.clone(),
833 tool_choice: def.tool_choice,
834 stream_usage: def.stream_usage,
835 max_tokens_field: def.max_tokens_field.clone(),
836 supports_tools: def.supports_tools,
837 send_reasoning: false,
838 body: def
839 .body
840 .as_ref()
841 .and_then(|v| serde_json::to_value(v).ok())
842 .unwrap_or_else(|| serde_json::json!({})),
843 reasoning: def.reasoning.clone(),
844 request: def
845 .request
846 .as_ref()
847 .map(crate::provider::RequestPolicy::from)
848 .unwrap_or_default(),
849 vision: def.vision,
850 models: def
851 .models
852 .iter()
853 .map(|(id, entry)| {
854 let mapped = match entry {
855 ModelReasoningDef::Toggle(on) => crate::provider::ModelReasoning::Toggle(*on),
856 ModelReasoningDef::Policy(policy) => {
857 crate::provider::ModelReasoning::Policy(policy.clone())
858 }
859 };
860 (id.clone(), mapped)
861 })
862 .collect(),
863 }
864}
865
866pub(crate) fn clamp_timeout(secs: Option<u64>) -> Duration {
867 Duration::from_secs(secs.unwrap_or(DEFAULT_TIMEOUT.as_secs()))
868 .clamp(Duration::from_secs(1), MAX_TIMEOUT)
869}
870
871pub fn mcp_timeout(cfg: &crate::config::Config) -> Duration {
875 clamp_timeout(cfg.plugins.mcp_timeout_secs)
876}
877
878#[derive(Debug, Clone, Copy)]
882pub struct McpSettings(pub Option<Duration>);
883
884impl McpSettings {
885 pub fn from_config(cfg: &crate::config::Config) -> Self {
886 Self(if cfg.no_mcp {
887 None
888 } else {
889 Some(mcp_timeout(cfg))
890 })
891 }
892}
893
894fn declares_only_profiles(manifest: &Manifest) -> bool {
902 !manifest.provider_profiles.is_empty()
903 && manifest.tools.is_empty()
904 && manifest.prompts.is_empty()
905 && manifest.hooks.is_empty()
906 && manifest.mcp.is_empty()
907}
908
909pub fn load(dirs: &[PathBuf], enabled: &[String]) -> Plugins {
915 let mut out = Plugins {
916 mcp: Some(DEFAULT_TIMEOUT),
919 ..Default::default()
920 };
921 let mut loaded: Vec<String> = Vec::new();
922 let mut failed: Vec<String> = Vec::new();
923 for dir in dirs {
924 let Ok(entries) = std::fs::read_dir(dir) else {
925 continue;
926 };
927 let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
928 paths.sort();
929 for path in paths {
930 if !path.join(MANIFEST).is_file() {
931 continue;
932 }
933 let dir_name = path
934 .file_name()
935 .map(|n| n.to_string_lossy().to_string())
936 .unwrap_or_default();
937 let listed = enabled.contains(&dir_name);
938 if loaded.contains(&dir_name) {
939 continue;
940 }
941 if !listed {
942 match read_manifest(&path, &dir_name) {
946 Ok(mut plugin) if declares_only_profiles(&plugin.manifest) => {
947 loaded.push(dir_name);
948 plugin.enabled = false;
950 out.plugins.push(plugin);
951 }
952 _ => continue,
953 }
954 continue;
955 }
956 match read_manifest(&path, &dir_name) {
957 Ok(plugin) => {
958 loaded.push(dir_name);
959 out.plugins.push(plugin);
960 }
961 Err(why) => {
962 failed.push(dir_name);
963 out.problems.push(why);
964 }
965 }
966 }
967 }
968 for name in enabled {
969 if !loaded.contains(name) && !failed.contains(name) {
970 out.problems.push(format!(
971 "plugin `{name}` is enabled but was not found in any plugin directory"
972 ));
973 }
974 }
975 for plugin in &mut out.plugins {
978 let mut resolved = Vec::new();
979 let mut problems = Vec::new();
980 for def in &plugin.manifest.prompts {
981 match (&def.text, &def.file) {
982 (Some(text), None) => resolved.push(PromptDef {
983 text: Some(text.clone()),
984 file: None,
985 }),
986 (None, Some(rel)) => {
987 let path = match manifest_path(&plugin.dir, rel) {
988 Ok(path) => path,
989 Err(why) => {
990 problems.push(format!("plugin `{}`: prompt file {why}", plugin.name));
991 continue;
992 }
993 };
994 match read_prompt_file(&path) {
995 Ok((text, cut)) => {
996 if cut {
997 problems.push(format!(
998 "plugin `{}`: prompt file {} is over {MAX_MANIFEST_FILE_BYTES} bytes and was truncated",
999 plugin.name,
1000 path.display()
1001 ));
1002 }
1003 resolved.push(PromptDef {
1004 text: Some(text),
1005 file: None,
1006 })
1007 }
1008 Err(e) => problems.push(format!(
1009 "plugin `{}`: prompt file {}: {e}",
1010 plugin.name,
1011 path.display()
1012 )),
1013 }
1014 }
1015 (Some(_), Some(_)) => problems.push(format!(
1016 "plugin `{}`: a prompt must have either `text` or `file`, not both",
1017 plugin.name
1018 )),
1019 (None, None) => problems.push(format!(
1020 "plugin `{}`: a prompt needs `text` or `file`",
1021 plugin.name
1022 )),
1023 }
1024 }
1025 plugin.manifest.prompts = resolved;
1026 out.problems.extend(problems);
1027 }
1028 out
1029}
1030
1031pub const MAX_MANIFEST_FILE_BYTES: u64 = 256 * 1024;
1035
1036fn manifest_path(dir: &Path, rel: &str) -> std::result::Result<PathBuf, String> {
1049 if rel.trim().is_empty() {
1050 return Err("names no file".into());
1051 }
1052 let base = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
1053 let path = dir.join(rel);
1054 let resolved = std::fs::canonicalize(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1055 if !resolved.starts_with(&base) {
1056 return Err(format!(
1057 "{} points outside the plugin ({}); a manifest path has to stay inside its own \
1058 directory",
1059 path.display(),
1060 resolved.display()
1061 ));
1062 }
1063 match std::fs::metadata(&resolved) {
1064 Ok(meta) if meta.is_file() => Ok(resolved),
1065 Ok(_) => Err(format!("{} is not a regular file", resolved.display())),
1066 Err(e) => Err(format!("{}: {e}", resolved.display())),
1067 }
1068}
1069
1070fn read_prompt_file(path: &Path) -> Result<(String, bool), String> {
1080 use std::io::Read as _;
1081 let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
1082 let mut bytes = Vec::new();
1083 file.take(MAX_MANIFEST_FILE_BYTES + 1)
1084 .read_to_end(&mut bytes)
1085 .map_err(|e| e.to_string())?;
1086 let cut = bytes.len() as u64 > MAX_MANIFEST_FILE_BYTES;
1087 if !cut {
1088 let text = String::from_utf8(bytes).map_err(|e| {
1089 format!(
1090 "not valid UTF-8 (first bad byte at offset {})",
1091 e.utf8_error().valid_up_to()
1092 )
1093 })?;
1094 return Ok((text, false));
1095 }
1096 let mut text = String::from_utf8_lossy(&bytes[..MAX_MANIFEST_FILE_BYTES as usize]).into_owned();
1100 text.push_str(&format!(
1101 "\n\n… (prompt file truncated at {MAX_MANIFEST_FILE_BYTES} bytes)"
1102 ));
1103 Ok((text, true))
1104}
1105
1106fn read_data_file(path: &Path) -> Result<String, String> {
1109 let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
1110 if meta.len() > MAX_MANIFEST_FILE_BYTES {
1111 return Err(format!(
1112 "is {} bytes; the limit is {MAX_MANIFEST_FILE_BYTES}",
1113 meta.len()
1114 ));
1115 }
1116 std::fs::read_to_string(path).map_err(|e| e.to_string())
1117}
1118
1119fn read_manifest(dir: &Path, dir_name: &str) -> Result<Plugin, String> {
1120 let path = dir.join(MANIFEST);
1121 let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1122 let manifest: Manifest =
1123 toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
1124 if manifest.name != dir_name {
1125 return Err(format!(
1126 "{}: name {:?} does not match its directory {:?}",
1127 path.display(),
1128 manifest.name,
1129 dir_name
1130 ));
1131 }
1132 if manifest.api > API {
1133 return Err(format!(
1134 "{}: needs plugin api {}, this build speaks {API}",
1135 path.display(),
1136 manifest.api
1137 ));
1138 }
1139 for tool in &manifest.tools {
1140 let ok = !tool.name.trim().is_empty()
1141 && tool
1142 .name
1143 .chars()
1144 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
1145 if !ok {
1146 return Err(format!(
1147 "{}: tool name {:?} must be [A-Za-z0-9_-]",
1148 path.display(),
1149 tool.name
1150 ));
1151 }
1152 }
1153 Ok(Plugin {
1154 name: manifest.name.clone(),
1155 version: manifest.version.clone(),
1156 description: manifest.description.clone(),
1157 dir: dir.to_path_buf(),
1158 manifest,
1159 enabled: true,
1162 })
1163}
1164
1165pub(crate) const INHERITED_ENV: [&str; 4] = ["PATH", "HOME", "LANG", "TZ"];
1171
1172struct Context<'a> {
1173 plugin_dir: &'a Path,
1174 workspace: &'a Path,
1175 extra_env: &'a [String],
1176 scripts_dir: Option<&'a Path>,
1177 max_bytes: usize,
1178}
1179
1180struct Output {
1181 stdout: String,
1182 stderr: String,
1183 code: Option<i32>,
1184 stdout_cut: bool,
1185}
1186
1187async fn run_command(
1189 command: &[String],
1190 cwd: &Path,
1191 timeout: Duration,
1192 ctx: Context<'_>,
1193 stdin_json: Value,
1194) -> Result<Output, String> {
1195 let Some(bin) = command.first() else {
1196 return Err("no command".into());
1197 };
1198 let mut cmd = tokio::process::Command::new(bin);
1199 cmd.args(&command[1..])
1200 .current_dir(cwd)
1201 .env_clear()
1202 .stdin(std::process::Stdio::piped())
1203 .stdout(std::process::Stdio::piped())
1204 .stderr(std::process::Stdio::piped())
1205 .kill_on_drop(true);
1206 for key in INHERITED_ENV {
1207 if let Ok(v) = std::env::var(key) {
1208 cmd.env(key, v);
1209 }
1210 }
1211 for key in ctx.extra_env {
1212 if let Ok(v) = std::env::var(key) {
1213 cmd.env(key, v);
1214 }
1215 }
1216 if let Some(dir) = ctx.scripts_dir {
1217 cmd.env("ECLIPSE_SCRIPTS_DIR", dir);
1218 }
1219 cmd.env("ECLIPSE_PLUGIN_DIR", ctx.plugin_dir)
1220 .env("ECLIPSE_WORKSPACE", ctx.workspace);
1221 let payload = stdin_json.to_string();
1228 if payload.len() <= ARGS_ENV_MAX {
1229 cmd.env("ECLIPSE_ARGS", &payload);
1230 } else {
1231 cmd.env("ECLIPSE_ARGS_BYTES", payload.len().to_string());
1232 }
1233 if let Some(tool) = stdin_json.get("tool").and_then(|t| t.as_str()) {
1234 cmd.env("ECLIPSE_TOOL", tool);
1235 }
1236 #[cfg(unix)]
1237 cmd.process_group(0);
1238 let mut child = cmd
1239 .spawn()
1240 .map_err(|e| format!("failed to start `{bin}`: {e}"))?;
1241 let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
1242 let cap = ctx.max_bytes;
1243 let run = async {
1244 if let Some(mut stdin) = child.stdin.take() {
1249 use tokio::io::AsyncWriteExt;
1250 let _ = stdin.write_all(payload.as_bytes()).await;
1251 }
1252 let (out, err) = tokio::join!(read_capped(stdout, cap), read_capped(stderr, cap));
1253 (out, err, child.wait().await)
1254 };
1255 let outcome = tokio::time::timeout(timeout, run).await;
1256 if outcome.is_err() {
1257 stop_group(&mut child).await;
1262 }
1263 match outcome {
1264 Err(_) => Err(format!("timed out after {}s", timeout.as_secs())),
1265 Ok(((out, out_cut), (err, _), status)) => {
1266 let status = status.map_err(|e| format!("failed to wait: {e}"))?;
1267 Ok(Output {
1268 stdout: out,
1269 stderr: err,
1270 code: status.code(),
1271 stdout_cut: out_cut,
1272 })
1273 }
1274 }
1275}
1276
1277async fn stop_group(child: &mut tokio::process::Child) {
1279 #[cfg(unix)]
1280 if let Some(pid) = child.id() {
1281 unsafe {
1284 libc::kill(-(pid as i32), libc::SIGKILL);
1285 }
1286 }
1287 let _ = child.start_kill();
1288 let _ = child.wait().await;
1289}
1290
1291struct CommandTool {
1293 name: String,
1294 description: String,
1295 parameters: Value,
1296 command: Vec<String>,
1297 plugin: String,
1298 plugin_dir: PathBuf,
1299 workspace: PathBuf,
1300 cwd: Cwd,
1301 timeout: Duration,
1302 env: Vec<String>,
1303 max_bytes: usize,
1304 scripts_dir: Option<PathBuf>,
1305}
1306
1307#[async_trait]
1308impl Tool for CommandTool {
1309 fn name(&self) -> &str {
1310 &self.name
1311 }
1312 fn description(&self) -> &str {
1313 &self.description
1314 }
1315 fn parameters(&self) -> Value {
1316 self.parameters.clone()
1317 }
1318 fn describe_call(&self, args: &Value) -> String {
1319 format!("run {}({args}) from plugin {}", self.name, self.plugin)
1320 }
1321 async fn call(&self, args: Value) -> Result<String, ToolError> {
1322 let cwd = match self.cwd {
1323 Cwd::Workspace => self.workspace.clone(),
1324 Cwd::Plugin => self.plugin_dir.clone(),
1325 };
1326 let payload = json!({
1327 "tool": self.name,
1328 "arguments": args,
1329 "plugin": self.plugin,
1330 "workspace": self.workspace.display().to_string(),
1331 });
1332 let out = run_command(
1333 &self.command,
1334 &cwd,
1335 self.timeout,
1336 Context {
1337 plugin_dir: &self.plugin_dir,
1338 workspace: &self.workspace,
1339 extra_env: &self.env,
1340 scripts_dir: self.scripts_dir.as_deref(),
1341 max_bytes: self.max_bytes,
1342 },
1343 payload,
1344 )
1345 .await
1346 .map_err(ToolError::Failed)?;
1347 let truncated = if out.stdout_cut { "\n[truncated]" } else { "" };
1348 let stdout = out.stdout.trim_end_matches('\n');
1349 if out.code == Some(0) {
1350 return Ok(format!("{stdout}{truncated}"));
1351 }
1352 let code = out
1353 .code
1354 .map(|c| c.to_string())
1355 .unwrap_or_else(|| "signal".into());
1356 Err(ToolError::Failed(format!(
1357 "exit code {code}\nstdout:\n{stdout}{truncated}\nstderr:\n{}",
1358 out.stderr.trim_end_matches('\n')
1359 )))
1360 }
1361}
1362
1363pub struct Hook {
1365 event: Event,
1366 tool: Option<String>,
1367 command: Vec<String>,
1368 timeout: Duration,
1369 cwd: Cwd,
1370 env: Vec<String>,
1371 plugin_dir: PathBuf,
1372 plugin: String,
1373 max_bytes: usize,
1374 scripts_dir: Option<PathBuf>,
1375}
1376
1377impl Hook {
1378 fn matches(&self, tool: &str) -> bool {
1379 match &self.tool {
1380 None => true,
1381 Some(p) if p == "*" => true,
1382 Some(p) => p == tool,
1383 }
1384 }
1385}
1386
1387pub enum Verdict {
1389 Allow,
1390 Deny(String),
1392}
1393
1394#[derive(Default, Clone)]
1396pub struct Hooks {
1397 hooks: Vec<Arc<Hook>>,
1398 workspace: PathBuf,
1399 profile: String,
1400}
1401
1402impl Hooks {
1403 pub fn new(hooks: Vec<Arc<Hook>>, workspace: PathBuf, profile: impl Into<String>) -> Self {
1404 Self {
1405 hooks,
1406 workspace,
1407 profile: profile.into(),
1408 }
1409 }
1410
1411 pub async fn before(&self, tool: &str, arguments: &Value, call_id: Option<&str>) -> Verdict {
1419 for hook in self.hooks.iter().filter(|h| h.event == Event::BeforeTool) {
1420 if !hook.matches(tool) {
1421 continue;
1422 }
1423 let payload = json!({
1424 "event": "before_tool",
1425 "tool": tool,
1426 "arguments": arguments,
1427 "call_id": call_id,
1428 "plugin": hook.plugin,
1429 "workspace": self.workspace.display().to_string(),
1430 "profile": self.profile,
1431 });
1432 let out = self.run(hook, payload).await;
1433 match out {
1434 Ok(o) if o.code == Some(0) => continue,
1435 Ok(o) => {
1436 let reason = if !o.stderr.trim().is_empty() {
1437 o.stderr.trim().to_string()
1438 } else if !o.stdout.trim().is_empty() {
1439 o.stdout.trim().to_string()
1440 } else {
1441 format!("refused by plugin `{}`", hook.plugin)
1442 };
1443 return Verdict::Deny(reason);
1444 }
1445 Err(why) => {
1446 return Verdict::Deny(format!(
1447 "refused: the `{}` guard for this tool could not run ({why})",
1448 hook.plugin
1449 ))
1450 }
1451 }
1452 }
1453 Verdict::Allow
1454 }
1455
1456 pub async fn after(
1460 &self,
1461 tool: &str,
1462 arguments: &Value,
1463 outcome: ToolOutcome,
1464 call_id: Option<&str>,
1465 ) -> ToolOutcome {
1466 let mut outcome = outcome;
1467 for hook in self.hooks.iter().filter(|h| h.event == Event::AfterTool) {
1468 if !hook.matches(tool) {
1469 continue;
1470 }
1471 let payload = json!({
1472 "event": "after_tool",
1473 "tool": tool,
1474 "arguments": arguments,
1475 "output": outcome.output.clone(),
1476 "is_error": outcome.is_error,
1477 "call_id": call_id,
1478 "plugin": hook.plugin,
1479 "workspace": self.workspace.display().to_string(),
1480 "profile": self.profile,
1481 });
1482 if let Ok(o) = self.run(hook, payload).await {
1483 if o.code == Some(0) && !o.stdout.trim().is_empty() {
1484 outcome.output = o.stdout.trim_end_matches('\n').to_string();
1485 }
1486 }
1487 }
1488 outcome
1489 }
1490
1491 async fn run(&self, hook: &Hook, payload: Value) -> Result<Output, String> {
1492 let cwd = match hook.cwd {
1493 Cwd::Workspace => self.workspace.clone(),
1494 Cwd::Plugin => hook.plugin_dir.clone(),
1495 };
1496 run_command(
1497 &hook.command,
1498 &cwd,
1499 hook.timeout,
1500 Context {
1501 plugin_dir: &hook.plugin_dir,
1502 workspace: &self.workspace,
1503 extra_env: &hook.env,
1504 scripts_dir: hook.scripts_dir.as_deref(),
1505 max_bytes: hook.max_bytes,
1506 },
1507 payload,
1508 )
1509 .await
1510 }
1511}
1512
1513pub fn discover_all(dirs: &[PathBuf]) -> Vec<(String, PathBuf)> {
1516 let mut out: Vec<(String, PathBuf)> = Vec::new();
1517 for dir in dirs {
1518 let Ok(entries) = std::fs::read_dir(dir) else {
1519 continue;
1520 };
1521 let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
1522 paths.sort();
1523 for path in paths {
1524 if path.join(MANIFEST).is_file() {
1525 let name = path
1526 .file_name()
1527 .map(|n| n.to_string_lossy().to_string())
1528 .unwrap_or_default();
1529 if !out.iter().any(|(n, _)| n == &name) {
1530 out.push((name, path));
1531 }
1532 }
1533 }
1534 }
1535 out
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540 use super::*;
1541
1542 #[tokio::test]
1547 async fn a_timed_out_plugin_takes_its_grandchild_with_it() {
1548 let dir = tempfile::tempdir().unwrap();
1549 let pidfile = dir.path().join("grandchild.pid");
1550 let script = format!("sleep 30 & echo $! > {}; wait", pidfile.display());
1551 let ctx = Context {
1552 plugin_dir: dir.path(),
1553 workspace: dir.path(),
1554 extra_env: &[],
1555 scripts_dir: None,
1556 max_bytes: 64 * 1024,
1557 };
1558 let out = run_command(
1559 &["sh".into(), "-c".into(), script],
1560 dir.path(),
1561 std::time::Duration::from_millis(400),
1562 ctx,
1563 serde_json::json!({}),
1564 )
1565 .await;
1566 assert!(out.is_err(), "the timeout is the answer");
1567
1568 let pid: i32 = std::fs::read_to_string(&pidfile)
1569 .expect("the grandchild wrote its pid before the timeout")
1570 .trim()
1571 .parse()
1572 .unwrap();
1573 let mut gone = false;
1574 for _ in 0..20 {
1575 if unsafe { libc::kill(pid, 0) } != 0 {
1577 gone = true;
1578 break;
1579 }
1580 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1581 }
1582 assert!(gone, "the grandchild outlived the plugin that started it");
1583 }
1584
1585 #[test]
1588 fn an_mcp_listing_line_does_not_print_the_credentials_in_its_url() {
1589 let spec: mcp::Spec = toml::from_str(
1590 "name = \"gh\"\ntransport = \"http\"\nurl = \"https://user:pw@example.test/mcp?token=abc\"\n",
1591 )
1592 .unwrap();
1593 let line = describe_command(&spec);
1594 assert!(!line.contains("pw"), "{line}");
1595 assert!(!line.contains("abc"), "{line}");
1596 assert!(
1597 line.contains("example.test/mcp"),
1598 "the endpoint is still recognisable: {line}"
1599 );
1600
1601 let plain: mcp::Spec = toml::from_str(
1602 "name = \"plain\"\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n",
1603 )
1604 .unwrap();
1605 assert_eq!(
1606 describe_command(&plain),
1607 "http https://example.test/mcp",
1608 "nothing to hide, nothing changed"
1609 );
1610 }
1611
1612 fn write(dir: &Path, rel: &str, text: &str) {
1613 let p = dir.join(rel);
1614 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1615 std::fs::write(p, text).unwrap();
1616 }
1617
1618 fn manifest(dir: &Path, name: &str) {
1619 write(
1620 dir,
1621 "plugin.toml",
1622 &format!(
1623 "name = \"{name}\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1624 [[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
1625 command = [\"sh\", \"-c\", \"echo hello $ECLIPSE_ARGS\"]\n\
1626 policy = \"allow\"\n"
1627 ),
1628 );
1629 }
1630
1631 #[test]
1636 fn a_listing_says_where_a_token_env_resolves() {
1637 let tmp = tempfile::tempdir().unwrap();
1638 let kept = format!("ECLIPSE_TEST_LIST_{}", "TOKEN");
1641 let absent = format!("{kept}_UNSET");
1642 std::env::remove_var(&kept);
1643 std::env::remove_var(&absent);
1644 let mut cfg = crate::config::parse_text(&format!(
1645 "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
1646 url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{kept}\"\ndisabled = true\n\n\
1647 [[mcp]]\nname = \"dead\"\ntransport = \"http\"\n\
1648 url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{absent}\"\ndisabled = true\n"
1649 ))
1650 .unwrap();
1651 cfg.dotenv.values.insert(kept.clone(), "kept".to_string());
1653
1654 let loaded = load(&[], &[]).with_config_mcp(&cfg);
1655 let (rows, _) = loaded.mcp_report(tmp.path());
1656 let row = |name: &str| {
1657 rows.iter()
1658 .find(|r| r.name == name)
1659 .unwrap_or_else(|| panic!("{name} is not listed: {rows:?}"))
1660 };
1661 assert_eq!(row("ha").token_env.as_deref(), Some(kept.as_str()));
1662 assert_eq!(row("ha").token, crate::mcp::TokenSource::Dotenv);
1663 assert_eq!(row("ha").token.as_str(), ".env");
1664 assert_eq!(row("dead").token, crate::mcp::TokenSource::Unset);
1665 assert_eq!(row("dead").token.as_str(), "unset");
1666 }
1667
1668 #[test]
1671 fn a_config_server_shadows_a_manifest_server_of_the_same_name() {
1672 let tmp = tempfile::tempdir().unwrap();
1673 let dir = tmp.path().join("plugins");
1674 write(
1675 &dir.join("pack"),
1676 "plugin.toml",
1677 r#"name = "pack"
1678version = "0.1.0"
1679
1680[[mcp]]
1681name = "notes"
1682command = "true"
1683policy = "allow"
1684"#,
1685 );
1686 let cfg =
1690 crate::config::parse_text("[[mcp]]\nname = \"notes\"\ncommand = \"false\"\n").unwrap();
1691 let loaded = load(&[dir], &["pack".into()]).with_config_mcp(&cfg);
1692 let (servers, problems) = loaded.servers(tmp.path());
1693 assert_eq!(servers.len(), 1, "one server, not two");
1694 assert_eq!(servers[0].source.label(), "config:mcp:notes");
1695 assert_eq!(servers[0].spec.command, "false", "the config's command");
1696 assert!(
1697 problems.iter().any(|p| p.contains("which wins")),
1698 "the shadowed entry is said out loud: {problems:?}"
1699 );
1700
1701 let alone = load(&[tmp.path().join("plugins")], &["pack".into()]);
1703 let (servers, problems) = alone.servers(tmp.path());
1704 assert_eq!(servers[0].source.label(), "plugin:mcp:notes");
1705 assert!(problems.is_empty(), "{problems:?}");
1706 }
1707
1708 #[test]
1709 fn loads_an_enabled_plugin_and_its_tool() {
1710 let tmp = tempfile::tempdir().unwrap();
1711 let dir = tmp.path().join("plugins");
1712 manifest(&dir.join("greeter"), "greeter");
1713 let loaded = load(&[dir], &["greeter".into()]);
1714 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1715 assert_eq!(loaded.plugins.len(), 1);
1716 assert_eq!(loaded.plugins[0].name, "greeter");
1717 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
1718 assert!(problems.is_empty(), "{problems:?}");
1719 assert_eq!(tools.len(), 1);
1720 assert_eq!(tools[0].tool.name(), "greet");
1721 assert_eq!(tools[0].policy, Policy::Allow);
1722 }
1723
1724 #[cfg(unix)]
1729 #[tokio::test]
1730 async fn a_payload_too_big_for_the_environment_still_reaches_the_plugin() {
1731 let tmp = tempfile::tempdir().unwrap();
1732 let dir = tmp.path().join("plugins").join("sizer");
1733 write(&dir, "size.sh", "#!/bin/sh\nprintf 'args=%s bytes=%s stdin=%s\\n' \"${ECLIPSE_ARGS:+set}\" \"${ECLIPSE_ARGS_BYTES:-none}\" \"$(wc -c)\"\n");
1734 write(
1735 &dir,
1736 "plugin.toml",
1737 "name = \"sizer\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1738 [[tool]]\nname = \"size\"\ndescription = \"Report what it was given\"\n\
1739 command = [\"sh\", \"size.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\n",
1740 );
1741 let loaded = load(&[tmp.path().join("plugins")], &["sizer".into()]);
1742 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1743 let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1744 assert!(problems.is_empty(), "{problems:?}");
1745
1746 let big = "x".repeat(200 * 1024);
1747 let out = tools[0]
1748 .tool
1749 .call(json!({"body": big}))
1750 .await
1751 .expect("a large payload must not stop the plugin from starting");
1752 assert!(
1753 !out.contains("args=set"),
1754 "the copy does not go into the environment: {out}"
1755 );
1756 assert!(
1757 !out.contains("bytes=none"),
1758 "the size does, so a plugin can tell empty from too big: {out}"
1759 );
1760 assert!(
1761 !out.contains("stdin=0"),
1762 "and the payload itself arrives on stdin: {out}"
1763 );
1764 }
1765
1766 #[cfg(unix)]
1770 #[tokio::test]
1771 async fn a_plugin_that_never_reads_its_input_still_times_out() {
1772 let tmp = tempfile::tempdir().unwrap();
1773 let dir = tmp.path().join("plugins").join("deaf");
1774 write(&dir, "deaf.sh", "#!/bin/sh\nsleep 20\n");
1775 write(
1776 &dir,
1777 "plugin.toml",
1778 "name = \"deaf\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1779 [[tool]]\nname = \"deaf\"\ndescription = \"Never reads its input\"\n\
1780 command = [\"sh\", \"deaf.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\ntimeout_secs = 1\n",
1781 );
1782 let loaded = load(&[tmp.path().join("plugins")], &["deaf".into()]);
1783 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1784 let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1785 assert!(problems.is_empty(), "{problems:?}");
1786
1787 let big = "x".repeat(200 * 1024);
1788 let call = tokio::time::timeout(
1789 Duration::from_secs(8),
1790 tools[0].tool.call(json!({"body": big})),
1791 )
1792 .await
1793 .expect("a full pipe must not hold the call");
1794 let err = call.expect_err("it never answered");
1795 assert!(err.to_string().contains("timed out"), "{err}");
1796 }
1797
1798 #[test]
1799 fn a_plugin_that_is_not_enabled_is_ignored_without_noise() {
1800 let tmp = tempfile::tempdir().unwrap();
1801 let dir = tmp.path().join("plugins");
1802 manifest(&dir.join("greeter"), "greeter");
1803 let loaded = load(&[dir], &[]);
1804 assert!(loaded.plugins.is_empty());
1805 assert!(loaded.problems.is_empty());
1806 }
1807
1808 #[test]
1809 fn enabling_a_missing_plugin_is_reported() {
1810 let tmp = tempfile::tempdir().unwrap();
1811 let loaded = load(&[tmp.path().join("plugins")], &["nope".into()]);
1812 assert!(
1813 loaded.problems[0].contains("enabled but was not found"),
1814 "{:?}",
1815 loaded.problems
1816 );
1817 }
1818
1819 #[test]
1820 fn a_name_that_does_not_match_the_directory_is_rejected() {
1821 let tmp = tempfile::tempdir().unwrap();
1822 let dir = tmp.path().join("plugins");
1823 manifest(&dir.join("greeter"), "someone-else");
1824 let loaded = load(&[dir], &["greeter".into()]);
1825 assert!(loaded.plugins.is_empty());
1826 assert!(
1827 loaded.problems[0].contains("does not match"),
1828 "{:?}",
1829 loaded.problems
1830 );
1831 }
1832
1833 #[test]
1834 fn a_newer_api_is_refused() {
1835 let tmp = tempfile::tempdir().unwrap();
1836 let dir = tmp.path().join("plugins");
1837 write(
1838 &dir.join("future"),
1839 "plugin.toml",
1840 "name = \"future\"\napi = 99\n",
1841 );
1842 let loaded = load(&[dir], &["future".into()]);
1843 assert!(
1844 loaded.problems[0].contains("needs plugin api 99"),
1845 "{:?}",
1846 loaded.problems
1847 );
1848 }
1849
1850 #[test]
1851 fn unknown_manifest_keys_are_errors_not_silence() {
1852 let tmp = tempfile::tempdir().unwrap();
1853 let dir = tmp.path().join("plugins");
1854 write(
1855 &dir.join("typo"),
1856 "plugin.toml",
1857 "name = \"typo\"\n[tool]\nname = \"x\"\nemabled = true\n",
1858 );
1859 let loaded = load(&[dir], &["typo".into()]);
1860 assert!(loaded.plugins.is_empty());
1861 assert!(!loaded.problems.is_empty());
1862 }
1863
1864 #[test]
1865 fn a_profile_copy_shadows_the_shared_copy() {
1866 let tmp = tempfile::tempdir().unwrap();
1867 let (shared, profile) = (
1868 tmp.path().join("plugins"),
1869 tmp.path().join("profile-plugins"),
1870 );
1871 for (root, marker) in [(&shared, "shared"), (&profile, "profile")] {
1872 write(
1873 &root.join("greeter"),
1874 "plugin.toml",
1875 &format!("name = \"greeter\"\ndescription = \"{marker}\"\n"),
1876 );
1877 }
1878 let loaded = load(&[profile, shared], &["greeter".into()]);
1879 assert_eq!(loaded.plugins.len(), 1);
1880 assert_eq!(loaded.plugins[0].description, "profile");
1881 }
1882
1883 #[test]
1884 fn replacing_a_tool_needs_an_explicit_override() {
1885 let tmp = tempfile::tempdir().unwrap();
1886 let dir = tmp.path().join("plugins");
1887 write(
1888 &dir.join("shadow"),
1889 "plugin.toml",
1890 "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"nope\"\n\
1891 command = [\"true\"]\n",
1892 );
1893 let builtin = vec!["shell".to_string()];
1894 let loaded = load(std::slice::from_ref(&dir), &["shadow".into()]);
1895 let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1896 assert!(tools.is_empty(), "a silent override must not happen");
1897 assert!(problems[0].contains("override = true"), "{problems:?}");
1898
1899 write(
1900 &dir.join("shadow"),
1901 "plugin.toml",
1902 "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"mine\"\n\
1903 override = true\ncommand = [\"true\"]\n",
1904 );
1905 let loaded = load(&[dir], &["shadow".into()]);
1906 let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1907 assert!(problems.is_empty(), "{problems:?}");
1908 assert_eq!(tools.len(), 1);
1909 }
1910
1911 #[test]
1912 fn a_tool_without_a_command_or_with_mcp_is_rejected_with_a_reason() {
1913 let tmp = tempfile::tempdir().unwrap();
1914 let dir = tmp.path().join("plugins");
1915 write(
1916 &dir.join("broken"),
1917 "plugin.toml",
1918 "name = \"broken\"\n\
1919 [[tool]]\nname = \"no_cmd\"\ndescription = \"x\"\n\
1920 [[tool]]\nname = \"via_mcp\"\ndescription = \"x\"\nkind = \"mcp\"\n\
1921 command = [\"x\"]\n",
1922 );
1923 let loaded = load(&[dir], &["broken".into()]);
1924 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
1925 assert!(tools.is_empty());
1926 assert_eq!(problems.len(), 2, "{problems:?}");
1927 assert!(problems[0].contains("no `command`"), "{problems:?}");
1928 assert!(
1929 problems[1].contains("belongs on a `[[mcp]]` section"),
1930 "{problems:?}"
1931 );
1932 }
1933
1934 const MCP_FIXTURE: &str = r#"#!/usr/bin/env python3
1937import json, sys
1938
1939def send(obj):
1940 sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
1941
1942for line in sys.stdin:
1943 if not line.strip():
1944 continue
1945 msg = json.loads(line)
1946 mid, method = msg.get("id"), msg.get("method")
1947 params = msg.get("params") or {}
1948 if method == "initialize":
1949 send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
1950 "capabilities": {"tools": {}}, "serverInfo": {"name": "fixture", "version": "0"}}})
1951 elif method == "notifications/initialized":
1952 pass
1953 elif method == "tools/list":
1954 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1955 {"name": "read_text_file", "description": "Read a file",
1956 "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}},
1957 {"name": "write_text_file", "description": "Write a file"}]}})
1958 elif method == "tools/call":
1959 send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
1960 {"type": "text", "text": "called " + str(params.get("name"))}]}})
1961 elif mid is not None:
1962 send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no"}})
1963"#;
1964
1965 fn mcp_plugin(tmp: &Path, extra: &str) -> PathBuf {
1966 let dir = tmp.join("plugins");
1967 let script = dir.join("fs").join("server.py");
1968 std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1969 std::fs::write(&script, MCP_FIXTURE).unwrap();
1970 let manifest = format!(
1971 "name = \"fs\"\n\n[[mcp]]\nname = \"files\"\ncommand = \"python3\"\n\
1972 args = [\"{}\"]\ncwd = \"plugin\"\ntimeout_secs = 15\n{extra}\n",
1973 script.display()
1974 );
1975 write(&dir.join("fs"), "plugin.toml", &manifest);
1976 dir
1977 }
1978
1979 #[test]
1980 fn mcp_off_starts_no_server_at_all() {
1981 let tmp = tempfile::tempdir().unwrap();
1982 let dir = tmp.path().join("plugins");
1983 let marker = tmp.path().join("spawned");
1985 let script = dir.join("loud").join("server.sh");
1986 std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1987 std::fs::write(&script, format!("#!/bin/sh\ntouch {}\n", marker.display())).unwrap();
1988 write(
1989 &dir.join("loud"),
1990 "plugin.toml",
1991 &format!(
1992 "name = \"loud\"\n\n[[mcp]]\nname = \"loud\"\ncommand = \"/bin/sh\"\n\
1993 args = [\"{}\"]\n",
1994 script.display()
1995 ),
1996 );
1997
1998 let on = load(std::slice::from_ref(&dir), &["loud".into()]);
2001 let (_tools, problems) = on.tools(tmp.path(), 4096, &[]);
2002 assert!(
2003 !problems.is_empty(),
2004 "a bad server is reported when MCP is on"
2005 );
2006 assert!(
2007 marker.exists(),
2008 "when MCP is on, the server process really ran"
2009 );
2010
2011 std::fs::remove_file(&marker).unwrap();
2013 let off = load(&[dir], &["loud".into()]).with_mcp(McpSettings(None));
2014 let (tools, problems) = off.tools(tmp.path(), 4096, &[]);
2015 assert!(
2016 tools.is_empty(),
2017 "no tools from a server that was never asked"
2018 );
2019 assert!(
2020 problems.is_empty(),
2021 "nothing to complain about when nothing ran: {problems:?}"
2022 );
2023 assert!(
2024 !marker.exists(),
2025 "with MCP off, no server process was spawned"
2026 );
2027
2028 assert_eq!(
2031 mcp_timeout(&crate::config::Config::default()),
2032 DEFAULT_TIMEOUT
2033 );
2034 let mut cfg = crate::config::Config::default();
2035 cfg.plugins.mcp_timeout_secs = Some(5);
2036 assert_eq!(mcp_timeout(&cfg), Duration::from_secs(5));
2037 }
2038
2039 #[test]
2040 fn an_mcp_server_contributes_its_tools_with_their_own_source_and_policies() {
2041 if std::process::Command::new("python3")
2042 .arg("--version")
2043 .output()
2044 .map(|o| !o.status.success())
2045 .unwrap_or(true)
2046 {
2047 return;
2048 }
2049 let tmp = tempfile::tempdir().unwrap();
2050 let dir = mcp_plugin(tmp.path(), "policies = { read_text_file = \"allow\" }");
2051 let loaded = load(&[dir], &["fs".into()]);
2052 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2053 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2054 assert!(problems.is_empty(), "{problems:?}");
2055 let names: Vec<&str> = tools.iter().map(|t| t.tool.name()).collect();
2056 assert_eq!(names, ["read_text_file", "write_text_file"]);
2057 for t in &tools {
2059 assert_eq!(t.source.label(), "plugin:mcp:files", "{}", t.tool.name());
2060 }
2061 let read = tools
2063 .iter()
2064 .find(|t| t.tool.name() == "read_text_file")
2065 .unwrap();
2066 let write = tools
2067 .iter()
2068 .find(|t| t.tool.name() == "write_text_file")
2069 .unwrap();
2070 assert_eq!(read.policy, Policy::Allow);
2071 assert_eq!(write.policy, Policy::Ask);
2072 assert_eq!(
2074 read.tool.parameters()["properties"]["path"]["type"],
2075 "string"
2076 );
2077 let out = tokio::runtime::Builder::new_current_thread()
2079 .enable_all()
2080 .build()
2081 .unwrap()
2082 .block_on(read.tool.call(json!({"path": "a.txt"})))
2083 .unwrap();
2084 assert_eq!(out, "called read_text_file");
2085
2086 let (again, _) = loaded.tools(tmp.path(), 4096, &[]);
2089 assert_eq!(again.len(), 2);
2090 let out = tokio::runtime::Builder::new_current_thread()
2091 .enable_all()
2092 .build()
2093 .unwrap()
2094 .block_on(again[0].tool.call(json!({"path": "b.txt"})))
2095 .unwrap();
2096 assert_eq!(out, "called read_text_file");
2097 }
2098
2099 #[test]
2100 fn a_server_tool_that_collides_is_refused_unless_the_entry_says_override() {
2101 if std::process::Command::new("python3")
2102 .arg("--version")
2103 .output()
2104 .map(|o| !o.status.success())
2105 .unwrap_or(true)
2106 {
2107 return;
2108 }
2109 let tmp = tempfile::tempdir().unwrap();
2110 let dir = mcp_plugin(tmp.path(), "");
2111 let loaded = load(&[dir], &["fs".into()]);
2112 let builtin = vec!["read_text_file".to_string()];
2115 let (tools, problems) = loaded.tools(tmp.path(), 4096, &builtin);
2116 assert_eq!(tools.len(), 1, "the other one still loads");
2117 assert_eq!(tools[0].tool.name(), "write_text_file");
2118 assert!(
2119 problems[0].contains("collides") && problems[0].contains("override = true"),
2120 "{problems:?}"
2121 );
2122 }
2123
2124 #[test]
2125 fn a_server_that_will_not_start_is_one_problem_and_no_tools() {
2126 let tmp = tempfile::tempdir().unwrap();
2127 let dir = tmp.path().join("plugins");
2128 write(
2129 &dir.join("dead"),
2130 "plugin.toml",
2131 "name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
2132 );
2133 let loaded = load(&[dir], &["dead".into()]);
2134 assert!(loaded.problems.is_empty(), "the manifest itself is fine");
2135 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2136 assert!(tools.is_empty());
2137 assert!(
2138 problems[0].contains("could not start") && problems[0].contains("gone"),
2139 "{problems:?}"
2140 );
2141 }
2142
2143 #[test]
2144 fn inline_parameters_and_a_schema_file_both_work() {
2145 let tmp = tempfile::tempdir().unwrap();
2146 let dir = tmp.path().join("plugins");
2147 write(
2148 &dir.join("p"),
2149 "plugin.toml",
2150 "name = \"p\"\n\
2151 [[tool]]\nname = \"inline\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2152 parameters = { type = \"object\", properties = { n = { type = \"string\" } } }\n\
2153 [[tool]]\nname = \"from_file\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2154 parameters = \"tools/from_file.json\"\n",
2155 );
2156 write(
2157 &dir.join("p"),
2158 "tools/from_file.json",
2159 "{\"type\":\"object\",\"properties\":{\"n\":{\"type\":\"integer\"}}}",
2160 );
2161 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2162 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2163 assert!(problems.is_empty(), "{problems:?}");
2164 assert_eq!(
2165 tools[0].tool.parameters()["properties"]["n"]["type"],
2166 "string"
2167 );
2168 assert_eq!(
2169 tools[1].tool.parameters()["properties"]["n"]["type"],
2170 "integer"
2171 );
2172
2173 std::fs::remove_file(dir.join("p/tools/from_file.json")).unwrap();
2174 let loaded = load(&[dir], &["p".into()]);
2175 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2176 assert_eq!(tools.len(), 1);
2177 assert!(problems[0].contains("from_file.json"), "{problems:?}");
2178 }
2179
2180 #[cfg(unix)]
2181 #[tokio::test]
2182 async fn a_command_tool_gets_json_on_stdin_and_returns_stdout() {
2183 let tmp = tempfile::tempdir().unwrap();
2184 let dir = tmp.path().join("plugins");
2185 write(
2186 &dir.join("echoer"),
2187 "plugin.toml",
2188 "name = \"echoer\"\n[[tool]]\nname = \"echo_args\"\n\
2189 description = \"Echo the JSON it was given\"\n\
2190 command = [\"sh\", \"-c\", \"cat\"]\npolicy = \"allow\"\n",
2191 );
2192 let loaded = load(&[dir], &["echoer".into()]);
2193 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2194 let out = tools[0]
2195 .tool
2196 .call(json!({"path": "a.txt"}))
2197 .await
2198 .expect("tool should succeed");
2199 let sent: Value = serde_json::from_str(&out).unwrap();
2200 assert_eq!(sent["arguments"]["path"], "a.txt");
2201 assert_eq!(sent["tool"], "echo_args");
2202 }
2203
2204 #[cfg(unix)]
2205 #[tokio::test]
2206 async fn a_non_zero_exit_is_an_error_that_carries_both_streams() {
2207 let tmp = tempfile::tempdir().unwrap();
2208 let dir = tmp.path().join("plugins");
2209 write(
2210 &dir.join("fail"),
2211 "plugin.toml",
2212 "name = \"fail\"\n[[tool]]\nname = \"boom\"\ndescription = \"x\"\n\
2213 command = [\"sh\", \"-c\", \"echo out; echo bad >&2; exit 3\"]\npolicy = \"allow\"\n",
2214 );
2215 let loaded = load(&[dir], &["fail".into()]);
2216 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2217 let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2218 assert!(err.contains("exit code 3"), "{err}");
2219 assert!(err.contains("out") && err.contains("bad"), "{err}");
2220 }
2221
2222 #[cfg(unix)]
2223 #[tokio::test]
2224 async fn the_command_runs_in_the_workspace_and_only_sees_the_allowed_environment() {
2225 let tmp = tempfile::tempdir().unwrap();
2226 let (dir, ws) = (tmp.path().join("plugins"), tmp.path().join("ws"));
2227 std::fs::create_dir_all(&ws).unwrap();
2228 std::env::set_var("PLUGIN_TEST_SECRET", "leak-me");
2229 std::env::set_var("PLUGIN_TEST_ALLOWED", "ok");
2230 write(
2231 &dir.join("env"),
2232 "plugin.toml",
2233 "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2234 command = [\"sh\", \"-c\", \"pwd; echo secret=[${PLUGIN_TEST_SECRET:-}]; \
2235 echo allowed=[${PLUGIN_TEST_ALLOWED:-}]\"]\n\
2236 env = [\"PLUGIN_TEST_ALLOWED\"]\npolicy = \"allow\"\n",
2237 );
2238 let loaded = load(&[dir], &["env".into()]);
2239 let (tools, _) = loaded.tools(&ws, 4096, &[]);
2240 let out = tools[0].tool.call(json!({})).await.unwrap();
2241 let canonical = std::fs::canonicalize(&ws).unwrap();
2242 assert!(out.contains(&canonical.display().to_string()), "{out}");
2243 assert!(
2244 out.contains("secret=[]"),
2245 "the agent environment must not leak: {out}"
2246 );
2247 assert!(out.contains("allowed=[ok]"), "{out}");
2248 std::env::remove_var("PLUGIN_TEST_SECRET");
2249 std::env::remove_var("PLUGIN_TEST_ALLOWED");
2250 }
2251
2252 #[cfg(unix)]
2253 #[tokio::test]
2254 async fn a_plugin_tool_is_told_where_the_scripts_are_and_its_path_is_left_alone() {
2255 let tmp = tempfile::tempdir().unwrap();
2256 let dir = tmp.path().join("plugins");
2257 let scripts = tmp.path().join("scripts");
2258 write(
2259 &dir.join("env"),
2260 "plugin.toml",
2261 "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2262 command = [\"sh\", \"-c\", \"echo scripts=[${ECLIPSE_SCRIPTS_DIR:-}]; echo path=[$PATH]\"]\n\
2263 policy = \"allow\"\n",
2264 );
2265 let with = load(std::slice::from_ref(&dir), &["env".into()])
2266 .with_scripts_dir(Some(scripts.clone()));
2267 let (tools, _) = with.tools(tmp.path(), 4096, &[]);
2268 let out = tools[0].tool.call(json!({})).await.unwrap();
2269 assert!(
2270 out.contains(&format!("scripts=[{}]", scripts.display())),
2271 "{out}"
2272 );
2273 let path_line = out.lines().find(|l| l.starts_with("path=")).unwrap();
2274 assert!(
2275 !path_line.contains(&scripts.display().to_string()),
2276 "a plugin's PATH must not gain the scripts directory: {out}"
2277 );
2278
2279 let without = load(&[dir], &["env".into()]);
2280 let (tools, _) = without.tools(tmp.path(), 4096, &[]);
2281 let out = tools[0].tool.call(json!({})).await.unwrap();
2282 assert!(out.contains("scripts=[]"), "{out}");
2283 }
2284
2285 #[cfg(unix)]
2286 #[tokio::test]
2287 async fn a_hook_process_is_told_where_the_scripts_are_too() {
2288 let tmp = tempfile::tempdir().unwrap();
2289 let dir = tmp.path().join("plugins");
2290 write(
2291 &dir.join("guard"),
2292 "plugin.toml",
2293 "name = \"guard\"\n\
2294 [[hook]]\nevent = \"before_tool\"\n\
2295 command = [\"sh\", \"-c\", \"echo $ECLIPSE_SCRIPTS_DIR >&2; exit 2\"]\n",
2296 );
2297 let loaded = load(&[dir], &["guard".into()])
2298 .with_scripts_dir(Some(PathBuf::from("/somewhere/scripts")));
2299 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2300 match hooks.before("shell", &json!({}), None).await {
2301 Verdict::Deny(why) => assert_eq!(why, "/somewhere/scripts"),
2302 Verdict::Allow => panic!("the hook should have refused"),
2303 }
2304 }
2305
2306 #[cfg(unix)]
2307 #[tokio::test]
2308 async fn a_slow_tool_times_out() {
2309 let tmp = tempfile::tempdir().unwrap();
2310 let dir = tmp.path().join("plugins");
2311 write(
2312 &dir.join("slow"),
2313 "plugin.toml",
2314 "name = \"slow\"\n[[tool]]\nname = \"wait\"\ndescription = \"x\"\n\
2315 command = [\"sleep\", \"30\"]\ntimeout_secs = 1\npolicy = \"allow\"\n",
2316 );
2317 let loaded = load(&[dir], &["slow".into()]);
2318 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2319 let started = std::time::Instant::now();
2320 let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2321 assert!(err.contains("timed out after 1s"), "{err}");
2322 assert!(started.elapsed() < Duration::from_secs(10));
2323 }
2324
2325 #[test]
2326 fn prompt_fragments_are_read_in_order_and_a_broken_one_is_a_problem() {
2327 let tmp = tempfile::tempdir().unwrap();
2328 let dir = tmp.path().join("plugins");
2329 write(
2330 &dir.join("p"),
2331 "plugin.toml",
2332 "name = \"p\"\n\
2333 [[prompt]]\ntext = \"first\"\n\
2334 [[prompt]]\nfile = \"prompts/second.md\"\n",
2335 );
2336 write(&dir.join("p"), "prompts/second.md", "second");
2337 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2338 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2339 assert_eq!(loaded.prompts(), ["first", "second"]);
2340
2341 std::fs::remove_file(dir.join("p/prompts/second.md")).unwrap();
2342 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2343 assert_eq!(loaded.prompts(), ["first"]);
2344 assert!(
2345 loaded.problems[0].contains("prompt file"),
2346 "{:?}",
2347 loaded.problems
2348 );
2349
2350 write(
2351 &dir.join("p"),
2352 "plugin.toml",
2353 "name = \"p\"\n[[prompt]]\ntext = \"x\"\nfile = \"y\"\n",
2354 );
2355 let loaded = load(&[dir], &["p".into()]);
2356 assert!(loaded.prompts().is_empty());
2357 assert!(
2358 loaded.problems[0].contains("either `text` or `file`"),
2359 "{:?}",
2360 loaded.problems
2361 );
2362 }
2363
2364 #[test]
2368 fn a_manifest_path_that_points_outside_the_plugin_is_refused() {
2369 let tmp = tempfile::tempdir().unwrap();
2370 let dir = tmp.path().join("plugins");
2371 let secret = dir.join("id_rsa");
2373 write(&dir, "id_rsa", "-----BEGIN OPENSSH PRIVATE KEY-----\n");
2374
2375 write(
2377 &dir.join("p"),
2378 "plugin.toml",
2379 "name = \"p\"\n[[prompt]]\nfile = \"../id_rsa\"\n",
2380 );
2381 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2382 assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2383 assert!(
2384 loaded
2385 .problems
2386 .iter()
2387 .any(|p| p.contains("outside the plugin")),
2388 "{:?}",
2389 loaded.problems
2390 );
2391
2392 write(
2393 &dir.join("p"),
2394 "plugin.toml",
2395 &format!("name = \"p\"\n[[prompt]]\nfile = {secret:?}\n"),
2396 );
2397 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2398 assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2399 assert!(
2400 loaded
2401 .problems
2402 .iter()
2403 .any(|p| p.contains("outside the plugin")),
2404 "{:?}",
2405 loaded.problems
2406 );
2407
2408 write(
2410 &dir.join("p"),
2411 "plugin.toml",
2412 "name = \"p\"\n[[tool]]\nname = \"leak\"\ndescription = \"x\"\n\
2413 command = [\"echo\"]\nparameters = \"../id_rsa\"\npolicy = \"allow\"\n",
2414 );
2415 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2416 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2417 assert!(tools.is_empty(), "no tool was built from the link");
2418 assert!(
2419 problems.iter().any(|p| p.contains("outside the plugin")),
2420 "{:?}",
2421 problems
2422 );
2423 }
2424
2425 #[test]
2429 fn a_manifest_path_inside_the_plugin_is_read_and_a_directory_is_refused() {
2430 let tmp = tempfile::tempdir().unwrap();
2431 let dir = tmp.path().join("plugins");
2432 write(
2433 &dir.join("p"),
2434 "plugin.toml",
2435 "name = \"p\"\n[[prompt]]\nfile = \"prompts/first.md\"\n",
2436 );
2437 write(&dir.join("p"), "prompts/first.md", "inside");
2438 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2439 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2440 assert_eq!(loaded.prompts(), ["inside"]);
2441
2442 std::fs::create_dir_all(dir.join("p/prompts/dir.md")).unwrap();
2443 write(
2444 &dir.join("p"),
2445 "plugin.toml",
2446 "name = \"p\"\n[[prompt]]\nfile = \"prompts/dir.md\"\n",
2447 );
2448 let loaded = load(&[dir], &["p".into()]);
2449 assert!(loaded.prompts().is_empty());
2450 assert!(
2451 loaded
2452 .problems
2453 .iter()
2454 .any(|p| p.contains("not a regular file")),
2455 "{:?}",
2456 loaded.problems
2457 );
2458 }
2459
2460 #[test]
2466 fn a_plugin_loaded_for_its_profiles_is_not_enabled_and_has_no_skills_root() {
2467 let tmp = tempfile::tempdir().unwrap();
2468 let dir = tmp.path().join("plugins");
2469 write(
2470 &dir.join("wire"),
2471 "plugin.toml",
2472 "name = \"wire\"\n\
2473 [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n",
2474 );
2475 write(
2477 &dir.join("wire/skills/sneaky/SKILL.md"),
2478 "SKILL.md",
2479 "---\nname: sneaky\ndescription: not yours\n---\n\nx\n",
2480 );
2481
2482 let loaded = load(std::slice::from_ref(&dir), &[]);
2483 assert_eq!(
2484 loaded.plugins.len(),
2485 1,
2486 "loaded for its profiles: {:?}",
2487 loaded.problems
2488 );
2489 assert!(
2490 !loaded.plugins[0].enabled,
2491 "loaded is not the same as enabled"
2492 );
2493 let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2494 assert!(
2495 !roots.iter().any(|r| r.dir.ends_with("wire/skills")),
2496 "an unenabled plugin's skills are not roots: {roots:?}"
2497 );
2498
2499 let loaded = load(&[dir], &["wire".into()]);
2501 assert!(loaded.plugins[0].enabled);
2502 let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2503 assert!(roots.iter().any(|r| r.dir.ends_with("wire/skills")));
2504 }
2505
2506 #[test]
2507 fn provider_profiles_override_by_name_and_keep_order() {
2508 let tmp = tempfile::tempdir().unwrap();
2509 let dir = tmp.path().join("plugins");
2510 write(
2511 &dir.join("prov"),
2512 "plugin.toml",
2513 "name = \"prov\"\n\
2514 [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n\
2515 [provider_profile.body]\nchat_template_kwargs = { enable_thinking = false }\n\
2516 [[provider_profile]]\nname = \"acme\"\nsupports_tools = false\n",
2517 );
2518 let loaded = load(&[dir], &["prov".into()]);
2519 let profiles = loaded.provider_profiles();
2520 assert_eq!(profiles.len(), 2);
2521 assert_eq!(profiles[0].name, "llamacpp");
2522 assert!(!profiles[0].tool_choice);
2523 assert_eq!(
2524 profiles[0].body["chat_template_kwargs"]["enable_thinking"],
2525 json!(false)
2526 );
2527 assert!(!profiles[1].supports_tools);
2528 }
2529
2530 #[cfg(unix)]
2531 #[tokio::test]
2532 async fn a_before_tool_hook_can_refuse_with_a_reason() {
2533 let tmp = tempfile::tempdir().unwrap();
2534 let dir = tmp.path().join("plugins");
2535 write(
2536 &dir.join("guard"),
2537 "plugin.toml",
2538 "name = \"guard\"\n\
2539 [[hook]]\nevent = \"before_tool\"\ntool = \"shell\"\n\
2540 command = [\"sh\", \"-c\", \"echo 'no shell in this repo' >&2; exit 2\"]\n",
2541 );
2542 let loaded = load(&[dir], &["guard".into()]);
2543 assert_eq!(loaded.hooks().len(), 1);
2544 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2545 match hooks.before("shell", &json!({"command": "ls"}), None).await {
2546 Verdict::Deny(why) => assert_eq!(why, "no shell in this repo"),
2547 Verdict::Allow => panic!("the hook should have refused"),
2548 }
2549 assert!(matches!(
2550 hooks.before("read_file", &json!({}), None).await,
2551 Verdict::Allow
2552 ));
2553 }
2554
2555 #[cfg(unix)]
2556 #[tokio::test]
2557 async fn a_guard_that_cannot_run_refuses_rather_than_allowing() {
2558 let tmp = tempfile::tempdir().unwrap();
2559 let dir = tmp.path().join("plugins");
2560 write(
2561 &dir.join("broken-guard"),
2562 "plugin.toml",
2563 "name = \"broken-guard\"\n\
2564 [[hook]]\nevent = \"before_tool\"\ncommand = [\"./missing.sh\"]\ncwd = \"plugin\"\n",
2565 );
2566 let loaded = load(&[dir], &["broken-guard".into()]);
2567 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2568 match hooks.before("anything", &json!({}), None).await {
2569 Verdict::Deny(why) => assert!(why.contains("could not run"), "{why}"),
2570 Verdict::Allow => panic!("a guard that cannot run must not silently allow"),
2571 }
2572 }
2573
2574 #[cfg(unix)]
2575 #[tokio::test]
2576 async fn an_after_tool_hook_can_rewrite_the_output() {
2577 let tmp = tempfile::tempdir().unwrap();
2578 let dir = tmp.path().join("plugins");
2579 write(
2582 &dir.join("redact"),
2583 "plugin.toml",
2584 "name = \"redact\"\n\
2585 [[hook]]\nevent = \"after_tool\"\n\
2586 command = [\"sh\", \"-c\", \"printf 'the [redacted] is here'\"]\n",
2587 );
2588 let loaded = load(std::slice::from_ref(&dir), &["redact".into()]);
2589 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2590 let out = hooks
2591 .after(
2592 "read_file",
2593 &json!({}),
2594 ToolOutcome {
2595 output: "the secret is here".into(),
2596 is_error: false,
2597 malformed: false,
2598 deferred: false,
2599 },
2600 None,
2601 )
2602 .await;
2603 assert_eq!(out.output, "the [redacted] is here");
2604 assert!(!out.is_error);
2605
2606 write(
2608 &dir.join("quiet"),
2609 "plugin.toml",
2610 "name = \"quiet\"\n\
2611 [[hook]]\nevent = \"after_tool\"\ncommand = [\"true\"]\n",
2612 );
2613 let quiet = load(&[dir], &["quiet".into()]);
2614 let hooks = Hooks::new(quiet.hooks(), PathBuf::from("/tmp"), "default");
2615 let out = hooks
2616 .after(
2617 "read_file",
2618 &json!({}),
2619 ToolOutcome {
2620 output: "unchanged".into(),
2621 is_error: true,
2622 malformed: false,
2623 deferred: false,
2624 },
2625 None,
2626 )
2627 .await;
2628 assert_eq!(out.output, "unchanged");
2629 assert!(out.is_error);
2630 }
2631
2632 #[test]
2633 fn the_shipped_examples_all_load() {
2634 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/plugins");
2636 if !root.is_dir() {
2637 return;
2638 }
2639 let names: Vec<String> = discover_all(std::slice::from_ref(&root))
2640 .into_iter()
2641 .map(|(name, _)| name)
2642 .collect();
2643 assert!(!names.is_empty(), "no examples found in {}", root.display());
2644 let loaded = load(std::slice::from_ref(&root), &names);
2645 assert!(
2646 loaded.problems.is_empty(),
2647 "the shipped examples must load cleanly: {:?}",
2648 loaded.problems
2649 );
2650 let (tools, problems) = loaded.tools(&root, 4096, &[]);
2651 assert!(problems.is_empty(), "{problems:?}");
2652 assert_eq!(tools.len(), 3, "git_status, git_diff, git_log");
2653 assert_eq!(loaded.provider_profiles().len(), 1);
2654 assert_eq!(loaded.hooks().len(), 1);
2655 assert!(!loaded.prompts().is_empty());
2656 }
2657
2658 #[test]
2659 fn discover_all_lists_manifests_whether_enabled_or_not() {
2660 let tmp = tempfile::tempdir().unwrap();
2661 let dir = tmp.path().join("plugins");
2662 manifest(&dir.join("a"), "a");
2663 manifest(&dir.join("b"), "b");
2664 std::fs::create_dir_all(dir.join("not-a-plugin")).unwrap();
2665 let found = discover_all(&[dir]);
2666 assert_eq!(found.len(), 2);
2667 }
2668
2669 #[cfg(unix)]
2670 #[tokio::test]
2671 async fn a_hook_payload_names_the_tool_call_it_is_about() {
2672 let tmp = tempfile::tempdir().unwrap();
2675 let dir = tmp.path().join("plugins");
2676 write(
2677 &dir.join("echo-payload"),
2678 "plugin.toml",
2679 "name = \"echo-payload\"\n\
2680 [[hook]]\nevent = \"after_tool\"\ncommand = [\"sh\", \"-c\", \"cat\"]\n",
2681 );
2682 let loaded = load(&[dir], &["echo-payload".into()]);
2683 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2684 let outcome = || ToolOutcome {
2685 output: "x".into(),
2686 is_error: false,
2687 malformed: false,
2688 deferred: false,
2689 };
2690 let named = hooks
2691 .after("read_file", &json!({}), outcome(), Some("c7"))
2692 .await;
2693 assert!(
2694 named.output.contains("\"call_id\":\"c7\""),
2695 "a hook must be able to tell concurrent calls apart: {}",
2696 named.output
2697 );
2698 let unnamed = hooks.after("read_file", &json!({}), outcome(), None).await;
2700 assert!(
2701 unnamed.output.contains("\"call_id\":null"),
2702 "{}",
2703 unnamed.output
2704 );
2705 }
2706}
2707
2708#[cfg(test)]
2709mod size_cap_tests {
2710 use super::*;
2711
2712 fn write(dir: &Path, rel: &str, text: &str) {
2713 let p = dir.join(rel);
2714 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
2715 std::fs::write(p, text).unwrap();
2716 }
2717
2718 #[test]
2721 fn an_oversized_prompt_file_is_cut_and_says_so() {
2722 let tmp = tempfile::tempdir().unwrap();
2723 let dir = tmp.path().join("plugins");
2724 write(
2725 &dir.join("longprompt"),
2726 "plugin.toml",
2727 "name = \"longprompt\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2728 [[prompt]]\nfile = \"prompts/rules.md\"\n",
2729 );
2730 let line = "keep the answer short and cite the file. ";
2732 let body = line.repeat((MAX_MANIFEST_FILE_BYTES as usize / line.len()) + 10);
2733 write(&dir.join("longprompt"), "prompts/rules.md", &body);
2734
2735 let loaded = load(&[dir], &["longprompt".into()]);
2736 assert!(
2737 loaded
2738 .problems
2739 .iter()
2740 .any(|p| p.contains("truncated") && p.contains("rules.md")),
2741 "the truncation is reported to the human: {:?}",
2742 loaded.problems
2743 );
2744 let text = loaded.plugins[0].manifest.prompts[0]
2745 .text
2746 .as_deref()
2747 .expect("the prompt resolves");
2748 assert!(
2749 text.len() <= MAX_MANIFEST_FILE_BYTES as usize + 128,
2750 "the prompt is capped, not passed through: {} bytes",
2751 text.len()
2752 );
2753 assert!(
2754 text.ends_with("bytes)"),
2755 "and the model is told the text is incomplete: …{}",
2756 &text[text.len().saturating_sub(80)..]
2757 );
2758 assert!(
2759 text.contains(line.trim()),
2760 "the part that arrived is the real text, not a placeholder"
2761 );
2762 }
2763
2764 #[test]
2767 fn an_oversized_parameters_file_is_refused_not_truncated() {
2768 let tmp = tempfile::tempdir().unwrap();
2769 let dir = tmp.path().join("plugins");
2770 write(
2771 &dir.join("paramtool"),
2772 "plugin.toml",
2773 "name = \"paramtool\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2774 [[tool]]\nname = \"thing\"\ndescription = \"A thing\"\n\
2775 command = [\"sh\", \"-c\", \"echo hi\"]\npolicy = \"allow\"\n\
2776 parameters = \"params.json\"\n",
2777 );
2778 let filler = "x".repeat(MAX_MANIFEST_FILE_BYTES as usize + 1);
2779 write(
2780 &dir.join("paramtool"),
2781 "params.json",
2782 &format!("{{\"type\":\"object\",\"description\":\"{filler}\"}}"),
2783 );
2784
2785 let loaded = load(&[dir], &["paramtool".into()]);
2786 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2787 assert!(
2788 problems
2789 .iter()
2790 .any(|p| p.contains("limit is") && p.contains("params.json")),
2791 "the refusal names the file and both sizes: {problems:?}"
2792 );
2793 assert!(
2794 tools.is_empty(),
2795 "the tool is not loaded with parameters nobody could read"
2796 );
2797 }
2798}