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 => format!(
395 "http {}",
396 spec.url.as_deref().unwrap_or("(no url declared)")
397 ),
398 }
399}
400
401type StartedServer = Result<(Arc<crate::mcp::Server>, Vec<crate::mcp::RemoteTool>), String>;
405
406#[derive(Debug, Clone, Default)]
408pub struct Plugins {
409 pub plugins: Vec<Plugin>,
410 pub problems: Vec<String>,
413 scripts_dir: Option<PathBuf>,
416 mcp: Option<Duration>,
419 config_mcp: Vec<mcp::Spec>,
422 secrets: crate::mcp::Secrets,
426 servers: Arc<Mutex<BTreeMap<String, StartedServer>>>,
430}
431
432impl Plugins {
433 pub fn with_scripts_dir(mut self, dir: Option<PathBuf>) -> Self {
436 self.scripts_dir = dir;
437 self
438 }
439
440 pub fn with_mcp(mut self, settings: McpSettings) -> Self {
443 self.mcp = settings.0;
444 self
445 }
446
447 pub fn with_config_mcp(mut self, cfg: &crate::config::Config) -> Self {
454 self.config_mcp = cfg.mcp.clone();
455 self.secrets = cfg.dotenv.values.clone();
456 self
457 }
458
459 pub fn get(&self, name: &str) -> Option<&Plugin> {
460 self.plugins.iter().find(|p| p.name == name)
461 }
462
463 pub fn prompts(&self) -> Vec<String> {
466 self.plugins
467 .iter()
468 .flat_map(|p| p.manifest.prompts.iter())
469 .filter_map(|d| d.text.clone())
470 .collect()
471 }
472
473 pub fn provider_profiles(&self) -> Vec<ProviderProfile> {
476 let mut out: Vec<ProviderProfile> = Vec::new();
477 for plugin in &self.plugins {
478 for def in &plugin.manifest.provider_profiles {
479 let profile = profile_from_def(def);
480 match out.iter_mut().find(|p| p.name == profile.name) {
481 Some(slot) => *slot = profile,
482 None => out.push(profile),
483 }
484 }
485 }
486 out
487 }
488
489 pub fn tools(
493 &self,
494 workspace: &Path,
495 max_bytes: usize,
496 builtin: &[String],
497 ) -> ToolsAndProblems {
498 let mut out: Vec<PluginTool> = Vec::new();
499 let mut problems = Vec::new();
500 for plugin in &self.plugins {
501 for def in &plugin.manifest.tools {
502 let mut problem = |why: String| {
503 problems.push(format!(
504 "plugin `{}`: tool `{}`: {why}",
505 plugin.name, def.name
506 ));
507 };
508 if def.kind == Kind::Mcp {
509 problem(
512 concat!(
513 "kind = \"mcp\" belongs on a `[[mcp]]` section, not on one tool: ",
514 "an MCP server contributes all of its tools from a single entry"
515 )
516 .to_string(),
517 );
518 continue;
519 }
520 if def.command.is_empty() {
521 problem("no `command` given".into());
522 continue;
523 }
524 let taken = builtin.iter().any(|b| b == &def.name)
525 || out.iter().any(|t| t.tool.name() == def.name);
526 if taken && !def.override_builtin {
527 problem(
528 "collides with a tool that already exists; set `override = true` on it \
529 to replace it"
530 .into(),
531 );
532 continue;
533 }
534 let parameters = match &def.parameters {
535 None => json!({"type": "object", "properties": {}}),
536 Some(Parameters::Inline(v)) => match serde_json::to_value(v) {
537 Ok(v) => v,
538 Err(e) => {
539 problem(format!("inline parameters are not valid JSON: {e}"));
540 continue;
541 }
542 },
543 Some(Parameters::File(rel)) => {
544 let path = match manifest_path(&plugin.dir, rel) {
545 Ok(path) => path,
546 Err(why) => {
547 problem(why);
548 continue;
549 }
550 };
551 match read_data_file(&path) {
552 Ok(text) => match serde_json::from_str::<Value>(&text) {
553 Ok(v) => v,
554 Err(e) => {
555 problem(format!("{}: {e}", path.display()));
556 continue;
557 }
558 },
559 Err(e) => {
560 problem(format!("{}: {e}", path.display()));
561 continue;
562 }
563 }
564 }
565 };
566 let policy = def.policy.unwrap_or(Policy::Ask);
567 let tool = CommandTool {
568 name: def.name.clone(),
569 description: def.description.clone(),
570 parameters,
571 command: def.command.clone(),
572 plugin: plugin.name.clone(),
573 plugin_dir: plugin.dir.clone(),
574 workspace: workspace.to_path_buf(),
575 cwd: def.cwd,
576 timeout: clamp_timeout(def.timeout_secs),
577 env: def.env.clone(),
578 max_bytes,
579 scripts_dir: self.scripts_dir.clone(),
580 };
581 out.push(PluginTool {
582 tool: Arc::new(tool) as Arc<dyn Tool>,
583 policy,
584 source: ToolSource::Plugin(plugin.name.clone()),
585 });
586 }
587 }
588 self.mcp_tools(workspace, builtin, &mut out, &mut problems);
591 (out, problems)
592 }
593
594 fn servers(&self, workspace: &Path) -> (Vec<ServerRef<'_>>, Vec<String>) {
602 let mut problems = Vec::new();
603 let mut out: Vec<ServerRef> = Vec::new();
604 for plugin in &self.plugins {
605 for spec in &plugin.manifest.mcp {
606 out.push(ServerRef {
607 spec,
608 base: plugin.dir.clone(),
609 owner: format!("plugin `{}`", plugin.name),
610 source: ToolSource::Plugin(format!("mcp:{}", spec.name)),
611 });
612 }
613 }
614 for spec in &self.config_mcp {
615 if let Some(pos) = out.iter().position(|s| s.spec.name == spec.name) {
618 let shadowed = out.remove(pos);
619 problems.push(format!(
620 "{}: mcp `{}` is also declared in config.toml, which wins; the manifest entry is ignored",
621 shadowed.owner, spec.name
622 ));
623 }
624 out.push(ServerRef {
625 spec,
626 base: workspace.to_path_buf(),
627 owner: "config".to_string(),
628 source: ToolSource::Config(format!("mcp:{}", spec.name)),
629 });
630 }
631 (out, problems)
632 }
633
634 pub fn mcp_report(&self, workspace: &Path) -> (Vec<McpServerState>, Vec<String>) {
637 let (servers, shadowed) = self.servers(workspace);
638 let problems = shadowed;
641 let mut out = Vec::new();
642 for server in servers {
643 let started = if server.spec.disabled {
647 None
648 } else {
649 Some(self.start(server.spec, &server.base, workspace))
650 };
651 let (tools, error, handshake) = match &started {
652 None => (0, None, None),
653 Some(Ok((session, tools))) => (tools.len(), None, session.handshake()),
654 Some(Err(why)) => (0, Some(why.clone()), None),
655 };
656 let field = |key: &str| {
657 handshake
658 .as_ref()
659 .and_then(|h| h.get(key))
660 .and_then(|v| v.as_str())
661 .map(str::to_string)
662 };
663 let info = |key: &str| {
666 handshake
667 .as_ref()
668 .and_then(|h| h.get("serverInfo"))
669 .and_then(|i| i.get(key))
670 .and_then(|v| v.as_str())
671 .map(str::to_string)
672 };
673 out.push(McpServerState {
674 name: server.spec.name.clone(),
675 source: server.source,
676 owner: server.owner,
677 command: describe_command(server.spec),
678 transport: server.spec.transport,
679 program: server.spec.command.clone(),
680 args: server.spec.args.clone(),
681 url: server.spec.url.clone(),
682 policy: server.spec.policy,
683 prefix: server.spec.prefix.clone(),
684 timeout_secs: server
685 .spec
686 .timeout_secs
687 .or_else(|| self.mcp.map(|d| d.as_secs()))
688 .unwrap_or(0),
689 disabled: server.spec.disabled,
690 token_env: server.spec.token_env.clone(),
691 token: server.spec.token_source(&self.secrets),
692 tools,
693 error,
694 protocol: field("protocolVersion"),
695 server_name: info("name"),
696 server_version: info("version"),
697 });
698 }
699 (out, problems)
700 }
701
702 fn mcp_tools(
705 &self,
706 workspace: &Path,
707 builtin: &[String],
708 out: &mut Vec<PluginTool>,
709 problems: &mut Vec<String>,
710 ) {
711 if self.mcp.is_none() {
712 return;
713 }
714 let (servers, shadowed) = self.servers(workspace);
715 problems.extend(shadowed);
716 for server in servers {
717 if server.spec.disabled {
718 continue;
719 }
720 if let Err(why) = server.spec.validate() {
723 problems.push(format!(
724 "{}: mcp `{}`: {why}",
725 server.owner, server.spec.name
726 ));
727 continue;
728 }
729 let (session, tools) = match self.start(server.spec, &server.base, workspace) {
730 Ok(started) => started,
731 Err(why) => {
732 problems.push(why);
733 continue;
734 }
735 };
736 for remote in tools {
737 let tool = crate::mcp::McpTool::new(Arc::clone(&session), &remote);
738 let name = tool.name().to_string();
739 let published = format!("{}{}", session.prefix(), remote.name);
744 if name != published {
745 problems.push(format!(
746 "{}: mcp `{}`: tool {:?} is called as `{}` (a name must be [A-Za-z0-9_-], at most {} characters)",
747 server.owner,
748 server.spec.name,
749 remote.name,
750 name.trim_start_matches(session.prefix()),
751 crate::mcp::TOOL_NAME_MAX
752 ));
753 }
754 let taken =
758 builtin.iter().any(|b| b == &name) || out.iter().any(|t| t.tool.name() == name);
759 if taken && !session.override_builtin() {
760 problems.push(format!(
761 concat!(
762 "{}: mcp `{}`: tool `{}` collides with a tool that ",
763 "already exists; set `override = true` on the server entry to replace it"
764 ),
765 server.owner, server.spec.name, name
766 ));
767 continue;
768 }
769 let policy = session.policy_for(&remote.name);
770 out.push(PluginTool {
771 tool: Arc::new(tool) as Arc<dyn Tool>,
772 policy,
773 source: server.source.clone(),
774 });
775 }
776 }
777 }
778
779 fn start(&self, spec: &mcp::Spec, base: &Path, workspace: &Path) -> StartedServer {
783 let Some(default_timeout) = self.mcp else {
784 return Err("MCP is off for this process (`--no-mcp`)".to_string());
785 };
786 let key = format!("{}:{}", base.display(), spec.name);
787 let mut cache = self.servers.lock().unwrap_or_else(|e| e.into_inner());
788 cache
789 .entry(key)
790 .or_insert_with(|| {
791 crate::mcp::Server::start(spec, base, workspace, default_timeout, &self.secrets)
792 .map_err(|e| format!("mcp `{}`: {e}", spec.name))
793 })
794 .clone()
795 }
796
797 pub fn hooks(&self) -> Vec<Arc<Hook>> {
799 self.plugins
800 .iter()
801 .flat_map(|p| {
802 p.manifest.hooks.iter().map(move |def| {
803 Arc::new(Hook {
804 event: def.event,
805 tool: def.tool.clone(),
806 command: def.command.clone(),
807 timeout: clamp_timeout(def.timeout_secs),
808 cwd: def.cwd,
809 env: def.env.clone(),
810 plugin_dir: p.dir.clone(),
811 plugin: p.name.clone(),
812 max_bytes: 64 * 1024,
813 scripts_dir: self.scripts_dir.clone(),
814 })
815 })
816 })
817 .collect()
818 }
819}
820
821pub fn profile_from_def(def: &ProfileDef) -> ProviderProfile {
825 ProviderProfile {
826 name: def.name.clone(),
827 tool_choice: def.tool_choice,
828 stream_usage: def.stream_usage,
829 max_tokens_field: def.max_tokens_field.clone(),
830 supports_tools: def.supports_tools,
831 send_reasoning: false,
832 body: def
833 .body
834 .as_ref()
835 .and_then(|v| serde_json::to_value(v).ok())
836 .unwrap_or_else(|| serde_json::json!({})),
837 reasoning: def.reasoning.clone(),
838 request: def
839 .request
840 .as_ref()
841 .map(crate::provider::RequestPolicy::from)
842 .unwrap_or_default(),
843 vision: def.vision,
844 models: def
845 .models
846 .iter()
847 .map(|(id, entry)| {
848 let mapped = match entry {
849 ModelReasoningDef::Toggle(on) => crate::provider::ModelReasoning::Toggle(*on),
850 ModelReasoningDef::Policy(policy) => {
851 crate::provider::ModelReasoning::Policy(policy.clone())
852 }
853 };
854 (id.clone(), mapped)
855 })
856 .collect(),
857 }
858}
859
860pub(crate) fn clamp_timeout(secs: Option<u64>) -> Duration {
861 Duration::from_secs(secs.unwrap_or(DEFAULT_TIMEOUT.as_secs()))
862 .clamp(Duration::from_secs(1), MAX_TIMEOUT)
863}
864
865pub fn mcp_timeout(cfg: &crate::config::Config) -> Duration {
869 clamp_timeout(cfg.plugins.mcp_timeout_secs)
870}
871
872#[derive(Debug, Clone, Copy)]
876pub struct McpSettings(pub Option<Duration>);
877
878impl McpSettings {
879 pub fn from_config(cfg: &crate::config::Config) -> Self {
880 Self(if cfg.no_mcp {
881 None
882 } else {
883 Some(mcp_timeout(cfg))
884 })
885 }
886}
887
888fn declares_only_profiles(manifest: &Manifest) -> bool {
896 !manifest.provider_profiles.is_empty()
897 && manifest.tools.is_empty()
898 && manifest.prompts.is_empty()
899 && manifest.hooks.is_empty()
900 && manifest.mcp.is_empty()
901}
902
903pub fn load(dirs: &[PathBuf], enabled: &[String]) -> Plugins {
909 let mut out = Plugins {
910 mcp: Some(DEFAULT_TIMEOUT),
913 ..Default::default()
914 };
915 let mut loaded: Vec<String> = Vec::new();
916 let mut failed: Vec<String> = Vec::new();
917 for dir in dirs {
918 let Ok(entries) = std::fs::read_dir(dir) else {
919 continue;
920 };
921 let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
922 paths.sort();
923 for path in paths {
924 if !path.join(MANIFEST).is_file() {
925 continue;
926 }
927 let dir_name = path
928 .file_name()
929 .map(|n| n.to_string_lossy().to_string())
930 .unwrap_or_default();
931 let listed = enabled.contains(&dir_name);
932 if loaded.contains(&dir_name) {
933 continue;
934 }
935 if !listed {
936 match read_manifest(&path, &dir_name) {
940 Ok(mut plugin) if declares_only_profiles(&plugin.manifest) => {
941 loaded.push(dir_name);
942 plugin.enabled = false;
944 out.plugins.push(plugin);
945 }
946 _ => continue,
947 }
948 continue;
949 }
950 match read_manifest(&path, &dir_name) {
951 Ok(plugin) => {
952 loaded.push(dir_name);
953 out.plugins.push(plugin);
954 }
955 Err(why) => {
956 failed.push(dir_name);
957 out.problems.push(why);
958 }
959 }
960 }
961 }
962 for name in enabled {
963 if !loaded.contains(name) && !failed.contains(name) {
964 out.problems.push(format!(
965 "plugin `{name}` is enabled but was not found in any plugin directory"
966 ));
967 }
968 }
969 for plugin in &mut out.plugins {
972 let mut resolved = Vec::new();
973 let mut problems = Vec::new();
974 for def in &plugin.manifest.prompts {
975 match (&def.text, &def.file) {
976 (Some(text), None) => resolved.push(PromptDef {
977 text: Some(text.clone()),
978 file: None,
979 }),
980 (None, Some(rel)) => {
981 let path = match manifest_path(&plugin.dir, rel) {
982 Ok(path) => path,
983 Err(why) => {
984 problems.push(format!("plugin `{}`: prompt file {why}", plugin.name));
985 continue;
986 }
987 };
988 match read_prompt_file(&path) {
989 Ok((text, cut)) => {
990 if cut {
991 problems.push(format!(
992 "plugin `{}`: prompt file {} is over {MAX_MANIFEST_FILE_BYTES} bytes and was truncated",
993 plugin.name,
994 path.display()
995 ));
996 }
997 resolved.push(PromptDef {
998 text: Some(text),
999 file: None,
1000 })
1001 }
1002 Err(e) => problems.push(format!(
1003 "plugin `{}`: prompt file {}: {e}",
1004 plugin.name,
1005 path.display()
1006 )),
1007 }
1008 }
1009 (Some(_), Some(_)) => problems.push(format!(
1010 "plugin `{}`: a prompt must have either `text` or `file`, not both",
1011 plugin.name
1012 )),
1013 (None, None) => problems.push(format!(
1014 "plugin `{}`: a prompt needs `text` or `file`",
1015 plugin.name
1016 )),
1017 }
1018 }
1019 plugin.manifest.prompts = resolved;
1020 out.problems.extend(problems);
1021 }
1022 out
1023}
1024
1025pub const MAX_MANIFEST_FILE_BYTES: u64 = 256 * 1024;
1029
1030fn manifest_path(dir: &Path, rel: &str) -> std::result::Result<PathBuf, String> {
1043 if rel.trim().is_empty() {
1044 return Err("names no file".into());
1045 }
1046 let base = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
1047 let path = dir.join(rel);
1048 let resolved = std::fs::canonicalize(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1049 if !resolved.starts_with(&base) {
1050 return Err(format!(
1051 "{} points outside the plugin ({}); a manifest path has to stay inside its own \
1052 directory",
1053 path.display(),
1054 resolved.display()
1055 ));
1056 }
1057 match std::fs::metadata(&resolved) {
1058 Ok(meta) if meta.is_file() => Ok(resolved),
1059 Ok(_) => Err(format!("{} is not a regular file", resolved.display())),
1060 Err(e) => Err(format!("{}: {e}", resolved.display())),
1061 }
1062}
1063
1064fn read_prompt_file(path: &Path) -> Result<(String, bool), String> {
1074 use std::io::Read as _;
1075 let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
1076 let mut bytes = Vec::new();
1077 file.take(MAX_MANIFEST_FILE_BYTES + 1)
1078 .read_to_end(&mut bytes)
1079 .map_err(|e| e.to_string())?;
1080 let cut = bytes.len() as u64 > MAX_MANIFEST_FILE_BYTES;
1081 if !cut {
1082 let text = String::from_utf8(bytes).map_err(|e| {
1083 format!(
1084 "not valid UTF-8 (first bad byte at offset {})",
1085 e.utf8_error().valid_up_to()
1086 )
1087 })?;
1088 return Ok((text, false));
1089 }
1090 let mut text = String::from_utf8_lossy(&bytes[..MAX_MANIFEST_FILE_BYTES as usize]).into_owned();
1094 text.push_str(&format!(
1095 "\n\n… (prompt file truncated at {MAX_MANIFEST_FILE_BYTES} bytes)"
1096 ));
1097 Ok((text, true))
1098}
1099
1100fn read_data_file(path: &Path) -> Result<String, String> {
1103 let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
1104 if meta.len() > MAX_MANIFEST_FILE_BYTES {
1105 return Err(format!(
1106 "is {} bytes; the limit is {MAX_MANIFEST_FILE_BYTES}",
1107 meta.len()
1108 ));
1109 }
1110 std::fs::read_to_string(path).map_err(|e| e.to_string())
1111}
1112
1113fn read_manifest(dir: &Path, dir_name: &str) -> Result<Plugin, String> {
1114 let path = dir.join(MANIFEST);
1115 let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1116 let manifest: Manifest =
1117 toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
1118 if manifest.name != dir_name {
1119 return Err(format!(
1120 "{}: name {:?} does not match its directory {:?}",
1121 path.display(),
1122 manifest.name,
1123 dir_name
1124 ));
1125 }
1126 if manifest.api > API {
1127 return Err(format!(
1128 "{}: needs plugin api {}, this build speaks {API}",
1129 path.display(),
1130 manifest.api
1131 ));
1132 }
1133 for tool in &manifest.tools {
1134 let ok = !tool.name.trim().is_empty()
1135 && tool
1136 .name
1137 .chars()
1138 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
1139 if !ok {
1140 return Err(format!(
1141 "{}: tool name {:?} must be [A-Za-z0-9_-]",
1142 path.display(),
1143 tool.name
1144 ));
1145 }
1146 }
1147 Ok(Plugin {
1148 name: manifest.name.clone(),
1149 version: manifest.version.clone(),
1150 description: manifest.description.clone(),
1151 dir: dir.to_path_buf(),
1152 manifest,
1153 enabled: true,
1156 })
1157}
1158
1159pub(crate) const INHERITED_ENV: [&str; 4] = ["PATH", "HOME", "LANG", "TZ"];
1165
1166struct Context<'a> {
1167 plugin_dir: &'a Path,
1168 workspace: &'a Path,
1169 extra_env: &'a [String],
1170 scripts_dir: Option<&'a Path>,
1171 max_bytes: usize,
1172}
1173
1174struct Output {
1175 stdout: String,
1176 stderr: String,
1177 code: Option<i32>,
1178 stdout_cut: bool,
1179}
1180
1181async fn run_command(
1183 command: &[String],
1184 cwd: &Path,
1185 timeout: Duration,
1186 ctx: Context<'_>,
1187 stdin_json: Value,
1188) -> Result<Output, String> {
1189 let Some(bin) = command.first() else {
1190 return Err("no command".into());
1191 };
1192 let mut cmd = tokio::process::Command::new(bin);
1193 cmd.args(&command[1..])
1194 .current_dir(cwd)
1195 .env_clear()
1196 .stdin(std::process::Stdio::piped())
1197 .stdout(std::process::Stdio::piped())
1198 .stderr(std::process::Stdio::piped())
1199 .kill_on_drop(true);
1200 for key in INHERITED_ENV {
1201 if let Ok(v) = std::env::var(key) {
1202 cmd.env(key, v);
1203 }
1204 }
1205 for key in ctx.extra_env {
1206 if let Ok(v) = std::env::var(key) {
1207 cmd.env(key, v);
1208 }
1209 }
1210 if let Some(dir) = ctx.scripts_dir {
1211 cmd.env("ECLIPSE_SCRIPTS_DIR", dir);
1212 }
1213 cmd.env("ECLIPSE_PLUGIN_DIR", ctx.plugin_dir)
1214 .env("ECLIPSE_WORKSPACE", ctx.workspace);
1215 let payload = stdin_json.to_string();
1222 if payload.len() <= ARGS_ENV_MAX {
1223 cmd.env("ECLIPSE_ARGS", &payload);
1224 } else {
1225 cmd.env("ECLIPSE_ARGS_BYTES", payload.len().to_string());
1226 }
1227 if let Some(tool) = stdin_json.get("tool").and_then(|t| t.as_str()) {
1228 cmd.env("ECLIPSE_TOOL", tool);
1229 }
1230 #[cfg(unix)]
1231 cmd.process_group(0);
1232 let mut child = cmd
1233 .spawn()
1234 .map_err(|e| format!("failed to start `{bin}`: {e}"))?;
1235 let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
1236 let cap = ctx.max_bytes;
1237 let run = async {
1238 if let Some(mut stdin) = child.stdin.take() {
1243 use tokio::io::AsyncWriteExt;
1244 let _ = stdin.write_all(payload.as_bytes()).await;
1245 }
1246 let (out, err) = tokio::join!(read_capped(stdout, cap), read_capped(stderr, cap));
1247 (out, err, child.wait().await)
1248 };
1249 match tokio::time::timeout(timeout, run).await {
1250 Err(_) => Err(format!("timed out after {}s", timeout.as_secs())),
1251 Ok(((out, out_cut), (err, _), status)) => {
1252 let status = status.map_err(|e| format!("failed to wait: {e}"))?;
1253 Ok(Output {
1254 stdout: out,
1255 stderr: err,
1256 code: status.code(),
1257 stdout_cut: out_cut,
1258 })
1259 }
1260 }
1261}
1262
1263struct CommandTool {
1265 name: String,
1266 description: String,
1267 parameters: Value,
1268 command: Vec<String>,
1269 plugin: String,
1270 plugin_dir: PathBuf,
1271 workspace: PathBuf,
1272 cwd: Cwd,
1273 timeout: Duration,
1274 env: Vec<String>,
1275 max_bytes: usize,
1276 scripts_dir: Option<PathBuf>,
1277}
1278
1279#[async_trait]
1280impl Tool for CommandTool {
1281 fn name(&self) -> &str {
1282 &self.name
1283 }
1284 fn description(&self) -> &str {
1285 &self.description
1286 }
1287 fn parameters(&self) -> Value {
1288 self.parameters.clone()
1289 }
1290 fn describe_call(&self, args: &Value) -> String {
1291 format!("run {}({args}) from plugin {}", self.name, self.plugin)
1292 }
1293 async fn call(&self, args: Value) -> Result<String, ToolError> {
1294 let cwd = match self.cwd {
1295 Cwd::Workspace => self.workspace.clone(),
1296 Cwd::Plugin => self.plugin_dir.clone(),
1297 };
1298 let payload = json!({
1299 "tool": self.name,
1300 "arguments": args,
1301 "plugin": self.plugin,
1302 "workspace": self.workspace.display().to_string(),
1303 });
1304 let out = run_command(
1305 &self.command,
1306 &cwd,
1307 self.timeout,
1308 Context {
1309 plugin_dir: &self.plugin_dir,
1310 workspace: &self.workspace,
1311 extra_env: &self.env,
1312 scripts_dir: self.scripts_dir.as_deref(),
1313 max_bytes: self.max_bytes,
1314 },
1315 payload,
1316 )
1317 .await
1318 .map_err(ToolError::Failed)?;
1319 let truncated = if out.stdout_cut { "\n[truncated]" } else { "" };
1320 let stdout = out.stdout.trim_end_matches('\n');
1321 if out.code == Some(0) {
1322 return Ok(format!("{stdout}{truncated}"));
1323 }
1324 let code = out
1325 .code
1326 .map(|c| c.to_string())
1327 .unwrap_or_else(|| "signal".into());
1328 Err(ToolError::Failed(format!(
1329 "exit code {code}\nstdout:\n{stdout}{truncated}\nstderr:\n{}",
1330 out.stderr.trim_end_matches('\n')
1331 )))
1332 }
1333}
1334
1335pub struct Hook {
1337 event: Event,
1338 tool: Option<String>,
1339 command: Vec<String>,
1340 timeout: Duration,
1341 cwd: Cwd,
1342 env: Vec<String>,
1343 plugin_dir: PathBuf,
1344 plugin: String,
1345 max_bytes: usize,
1346 scripts_dir: Option<PathBuf>,
1347}
1348
1349impl Hook {
1350 fn matches(&self, tool: &str) -> bool {
1351 match &self.tool {
1352 None => true,
1353 Some(p) if p == "*" => true,
1354 Some(p) => p == tool,
1355 }
1356 }
1357}
1358
1359pub enum Verdict {
1361 Allow,
1362 Deny(String),
1364}
1365
1366#[derive(Default, Clone)]
1368pub struct Hooks {
1369 hooks: Vec<Arc<Hook>>,
1370 workspace: PathBuf,
1371 profile: String,
1372}
1373
1374impl Hooks {
1375 pub fn new(hooks: Vec<Arc<Hook>>, workspace: PathBuf, profile: impl Into<String>) -> Self {
1376 Self {
1377 hooks,
1378 workspace,
1379 profile: profile.into(),
1380 }
1381 }
1382
1383 pub async fn before(&self, tool: &str, arguments: &Value, call_id: Option<&str>) -> Verdict {
1391 for hook in self.hooks.iter().filter(|h| h.event == Event::BeforeTool) {
1392 if !hook.matches(tool) {
1393 continue;
1394 }
1395 let payload = json!({
1396 "event": "before_tool",
1397 "tool": tool,
1398 "arguments": arguments,
1399 "call_id": call_id,
1400 "plugin": hook.plugin,
1401 "workspace": self.workspace.display().to_string(),
1402 "profile": self.profile,
1403 });
1404 let out = self.run(hook, payload).await;
1405 match out {
1406 Ok(o) if o.code == Some(0) => continue,
1407 Ok(o) => {
1408 let reason = if !o.stderr.trim().is_empty() {
1409 o.stderr.trim().to_string()
1410 } else if !o.stdout.trim().is_empty() {
1411 o.stdout.trim().to_string()
1412 } else {
1413 format!("refused by plugin `{}`", hook.plugin)
1414 };
1415 return Verdict::Deny(reason);
1416 }
1417 Err(why) => {
1418 return Verdict::Deny(format!(
1419 "refused: the `{}` guard for this tool could not run ({why})",
1420 hook.plugin
1421 ))
1422 }
1423 }
1424 }
1425 Verdict::Allow
1426 }
1427
1428 pub async fn after(
1432 &self,
1433 tool: &str,
1434 arguments: &Value,
1435 outcome: ToolOutcome,
1436 call_id: Option<&str>,
1437 ) -> ToolOutcome {
1438 let mut outcome = outcome;
1439 for hook in self.hooks.iter().filter(|h| h.event == Event::AfterTool) {
1440 if !hook.matches(tool) {
1441 continue;
1442 }
1443 let payload = json!({
1444 "event": "after_tool",
1445 "tool": tool,
1446 "arguments": arguments,
1447 "output": outcome.output.clone(),
1448 "is_error": outcome.is_error,
1449 "call_id": call_id,
1450 "plugin": hook.plugin,
1451 "workspace": self.workspace.display().to_string(),
1452 "profile": self.profile,
1453 });
1454 if let Ok(o) = self.run(hook, payload).await {
1455 if o.code == Some(0) && !o.stdout.trim().is_empty() {
1456 outcome.output = o.stdout.trim_end_matches('\n').to_string();
1457 }
1458 }
1459 }
1460 outcome
1461 }
1462
1463 async fn run(&self, hook: &Hook, payload: Value) -> Result<Output, String> {
1464 let cwd = match hook.cwd {
1465 Cwd::Workspace => self.workspace.clone(),
1466 Cwd::Plugin => hook.plugin_dir.clone(),
1467 };
1468 run_command(
1469 &hook.command,
1470 &cwd,
1471 hook.timeout,
1472 Context {
1473 plugin_dir: &hook.plugin_dir,
1474 workspace: &self.workspace,
1475 extra_env: &hook.env,
1476 scripts_dir: hook.scripts_dir.as_deref(),
1477 max_bytes: hook.max_bytes,
1478 },
1479 payload,
1480 )
1481 .await
1482 }
1483}
1484
1485pub fn discover_all(dirs: &[PathBuf]) -> Vec<(String, PathBuf)> {
1488 let mut out: Vec<(String, PathBuf)> = Vec::new();
1489 for dir in dirs {
1490 let Ok(entries) = std::fs::read_dir(dir) else {
1491 continue;
1492 };
1493 let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
1494 paths.sort();
1495 for path in paths {
1496 if path.join(MANIFEST).is_file() {
1497 let name = path
1498 .file_name()
1499 .map(|n| n.to_string_lossy().to_string())
1500 .unwrap_or_default();
1501 if !out.iter().any(|(n, _)| n == &name) {
1502 out.push((name, path));
1503 }
1504 }
1505 }
1506 }
1507 out
1508}
1509
1510#[cfg(test)]
1511mod tests {
1512 use super::*;
1513
1514 fn write(dir: &Path, rel: &str, text: &str) {
1515 let p = dir.join(rel);
1516 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1517 std::fs::write(p, text).unwrap();
1518 }
1519
1520 fn manifest(dir: &Path, name: &str) {
1521 write(
1522 dir,
1523 "plugin.toml",
1524 &format!(
1525 "name = \"{name}\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1526 [[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
1527 command = [\"sh\", \"-c\", \"echo hello $ECLIPSE_ARGS\"]\n\
1528 policy = \"allow\"\n"
1529 ),
1530 );
1531 }
1532
1533 #[test]
1538 fn a_listing_says_where_a_token_env_resolves() {
1539 let tmp = tempfile::tempdir().unwrap();
1540 let kept = format!("ECLIPSE_TEST_LIST_{}", "TOKEN");
1543 let absent = format!("{kept}_UNSET");
1544 std::env::remove_var(&kept);
1545 std::env::remove_var(&absent);
1546 let mut cfg = crate::config::parse_text(&format!(
1547 "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
1548 url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{kept}\"\ndisabled = true\n\n\
1549 [[mcp]]\nname = \"dead\"\ntransport = \"http\"\n\
1550 url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{absent}\"\ndisabled = true\n"
1551 ))
1552 .unwrap();
1553 cfg.dotenv.values.insert(kept.clone(), "kept".to_string());
1555
1556 let loaded = load(&[], &[]).with_config_mcp(&cfg);
1557 let (rows, _) = loaded.mcp_report(tmp.path());
1558 let row = |name: &str| {
1559 rows.iter()
1560 .find(|r| r.name == name)
1561 .unwrap_or_else(|| panic!("{name} is not listed: {rows:?}"))
1562 };
1563 assert_eq!(row("ha").token_env.as_deref(), Some(kept.as_str()));
1564 assert_eq!(row("ha").token, crate::mcp::TokenSource::Dotenv);
1565 assert_eq!(row("ha").token.as_str(), ".env");
1566 assert_eq!(row("dead").token, crate::mcp::TokenSource::Unset);
1567 assert_eq!(row("dead").token.as_str(), "unset");
1568 }
1569
1570 #[test]
1573 fn a_config_server_shadows_a_manifest_server_of_the_same_name() {
1574 let tmp = tempfile::tempdir().unwrap();
1575 let dir = tmp.path().join("plugins");
1576 write(
1577 &dir.join("pack"),
1578 "plugin.toml",
1579 r#"name = "pack"
1580version = "0.1.0"
1581
1582[[mcp]]
1583name = "notes"
1584command = "true"
1585policy = "allow"
1586"#,
1587 );
1588 let cfg =
1592 crate::config::parse_text("[[mcp]]\nname = \"notes\"\ncommand = \"false\"\n").unwrap();
1593 let loaded = load(&[dir], &["pack".into()]).with_config_mcp(&cfg);
1594 let (servers, problems) = loaded.servers(tmp.path());
1595 assert_eq!(servers.len(), 1, "one server, not two");
1596 assert_eq!(servers[0].source.label(), "config:mcp:notes");
1597 assert_eq!(servers[0].spec.command, "false", "the config's command");
1598 assert!(
1599 problems.iter().any(|p| p.contains("which wins")),
1600 "the shadowed entry is said out loud: {problems:?}"
1601 );
1602
1603 let alone = load(&[tmp.path().join("plugins")], &["pack".into()]);
1605 let (servers, problems) = alone.servers(tmp.path());
1606 assert_eq!(servers[0].source.label(), "plugin:mcp:notes");
1607 assert!(problems.is_empty(), "{problems:?}");
1608 }
1609
1610 #[test]
1611 fn loads_an_enabled_plugin_and_its_tool() {
1612 let tmp = tempfile::tempdir().unwrap();
1613 let dir = tmp.path().join("plugins");
1614 manifest(&dir.join("greeter"), "greeter");
1615 let loaded = load(&[dir], &["greeter".into()]);
1616 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1617 assert_eq!(loaded.plugins.len(), 1);
1618 assert_eq!(loaded.plugins[0].name, "greeter");
1619 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
1620 assert!(problems.is_empty(), "{problems:?}");
1621 assert_eq!(tools.len(), 1);
1622 assert_eq!(tools[0].tool.name(), "greet");
1623 assert_eq!(tools[0].policy, Policy::Allow);
1624 }
1625
1626 #[cfg(unix)]
1631 #[tokio::test]
1632 async fn a_payload_too_big_for_the_environment_still_reaches_the_plugin() {
1633 let tmp = tempfile::tempdir().unwrap();
1634 let dir = tmp.path().join("plugins").join("sizer");
1635 write(&dir, "size.sh", "#!/bin/sh\nprintf 'args=%s bytes=%s stdin=%s\\n' \"${ECLIPSE_ARGS:+set}\" \"${ECLIPSE_ARGS_BYTES:-none}\" \"$(wc -c)\"\n");
1636 write(
1637 &dir,
1638 "plugin.toml",
1639 "name = \"sizer\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1640 [[tool]]\nname = \"size\"\ndescription = \"Report what it was given\"\n\
1641 command = [\"sh\", \"size.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\n",
1642 );
1643 let loaded = load(&[tmp.path().join("plugins")], &["sizer".into()]);
1644 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1645 let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1646 assert!(problems.is_empty(), "{problems:?}");
1647
1648 let big = "x".repeat(200 * 1024);
1649 let out = tools[0]
1650 .tool
1651 .call(json!({"body": big}))
1652 .await
1653 .expect("a large payload must not stop the plugin from starting");
1654 assert!(
1655 !out.contains("args=set"),
1656 "the copy does not go into the environment: {out}"
1657 );
1658 assert!(
1659 !out.contains("bytes=none"),
1660 "the size does, so a plugin can tell empty from too big: {out}"
1661 );
1662 assert!(
1663 !out.contains("stdin=0"),
1664 "and the payload itself arrives on stdin: {out}"
1665 );
1666 }
1667
1668 #[cfg(unix)]
1672 #[tokio::test]
1673 async fn a_plugin_that_never_reads_its_input_still_times_out() {
1674 let tmp = tempfile::tempdir().unwrap();
1675 let dir = tmp.path().join("plugins").join("deaf");
1676 write(&dir, "deaf.sh", "#!/bin/sh\nsleep 20\n");
1677 write(
1678 &dir,
1679 "plugin.toml",
1680 "name = \"deaf\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1681 [[tool]]\nname = \"deaf\"\ndescription = \"Never reads its input\"\n\
1682 command = [\"sh\", \"deaf.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\ntimeout_secs = 1\n",
1683 );
1684 let loaded = load(&[tmp.path().join("plugins")], &["deaf".into()]);
1685 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1686 let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1687 assert!(problems.is_empty(), "{problems:?}");
1688
1689 let big = "x".repeat(200 * 1024);
1690 let call = tokio::time::timeout(
1691 Duration::from_secs(8),
1692 tools[0].tool.call(json!({"body": big})),
1693 )
1694 .await
1695 .expect("a full pipe must not hold the call");
1696 let err = call.expect_err("it never answered");
1697 assert!(err.to_string().contains("timed out"), "{err}");
1698 }
1699
1700 #[test]
1701 fn a_plugin_that_is_not_enabled_is_ignored_without_noise() {
1702 let tmp = tempfile::tempdir().unwrap();
1703 let dir = tmp.path().join("plugins");
1704 manifest(&dir.join("greeter"), "greeter");
1705 let loaded = load(&[dir], &[]);
1706 assert!(loaded.plugins.is_empty());
1707 assert!(loaded.problems.is_empty());
1708 }
1709
1710 #[test]
1711 fn enabling_a_missing_plugin_is_reported() {
1712 let tmp = tempfile::tempdir().unwrap();
1713 let loaded = load(&[tmp.path().join("plugins")], &["nope".into()]);
1714 assert!(
1715 loaded.problems[0].contains("enabled but was not found"),
1716 "{:?}",
1717 loaded.problems
1718 );
1719 }
1720
1721 #[test]
1722 fn a_name_that_does_not_match_the_directory_is_rejected() {
1723 let tmp = tempfile::tempdir().unwrap();
1724 let dir = tmp.path().join("plugins");
1725 manifest(&dir.join("greeter"), "someone-else");
1726 let loaded = load(&[dir], &["greeter".into()]);
1727 assert!(loaded.plugins.is_empty());
1728 assert!(
1729 loaded.problems[0].contains("does not match"),
1730 "{:?}",
1731 loaded.problems
1732 );
1733 }
1734
1735 #[test]
1736 fn a_newer_api_is_refused() {
1737 let tmp = tempfile::tempdir().unwrap();
1738 let dir = tmp.path().join("plugins");
1739 write(
1740 &dir.join("future"),
1741 "plugin.toml",
1742 "name = \"future\"\napi = 99\n",
1743 );
1744 let loaded = load(&[dir], &["future".into()]);
1745 assert!(
1746 loaded.problems[0].contains("needs plugin api 99"),
1747 "{:?}",
1748 loaded.problems
1749 );
1750 }
1751
1752 #[test]
1753 fn unknown_manifest_keys_are_errors_not_silence() {
1754 let tmp = tempfile::tempdir().unwrap();
1755 let dir = tmp.path().join("plugins");
1756 write(
1757 &dir.join("typo"),
1758 "plugin.toml",
1759 "name = \"typo\"\n[tool]\nname = \"x\"\nemabled = true\n",
1760 );
1761 let loaded = load(&[dir], &["typo".into()]);
1762 assert!(loaded.plugins.is_empty());
1763 assert!(!loaded.problems.is_empty());
1764 }
1765
1766 #[test]
1767 fn a_profile_copy_shadows_the_shared_copy() {
1768 let tmp = tempfile::tempdir().unwrap();
1769 let (shared, profile) = (
1770 tmp.path().join("plugins"),
1771 tmp.path().join("profile-plugins"),
1772 );
1773 for (root, marker) in [(&shared, "shared"), (&profile, "profile")] {
1774 write(
1775 &root.join("greeter"),
1776 "plugin.toml",
1777 &format!("name = \"greeter\"\ndescription = \"{marker}\"\n"),
1778 );
1779 }
1780 let loaded = load(&[profile, shared], &["greeter".into()]);
1781 assert_eq!(loaded.plugins.len(), 1);
1782 assert_eq!(loaded.plugins[0].description, "profile");
1783 }
1784
1785 #[test]
1786 fn replacing_a_tool_needs_an_explicit_override() {
1787 let tmp = tempfile::tempdir().unwrap();
1788 let dir = tmp.path().join("plugins");
1789 write(
1790 &dir.join("shadow"),
1791 "plugin.toml",
1792 "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"nope\"\n\
1793 command = [\"true\"]\n",
1794 );
1795 let builtin = vec!["shell".to_string()];
1796 let loaded = load(std::slice::from_ref(&dir), &["shadow".into()]);
1797 let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1798 assert!(tools.is_empty(), "a silent override must not happen");
1799 assert!(problems[0].contains("override = true"), "{problems:?}");
1800
1801 write(
1802 &dir.join("shadow"),
1803 "plugin.toml",
1804 "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"mine\"\n\
1805 override = true\ncommand = [\"true\"]\n",
1806 );
1807 let loaded = load(&[dir], &["shadow".into()]);
1808 let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1809 assert!(problems.is_empty(), "{problems:?}");
1810 assert_eq!(tools.len(), 1);
1811 }
1812
1813 #[test]
1814 fn a_tool_without_a_command_or_with_mcp_is_rejected_with_a_reason() {
1815 let tmp = tempfile::tempdir().unwrap();
1816 let dir = tmp.path().join("plugins");
1817 write(
1818 &dir.join("broken"),
1819 "plugin.toml",
1820 "name = \"broken\"\n\
1821 [[tool]]\nname = \"no_cmd\"\ndescription = \"x\"\n\
1822 [[tool]]\nname = \"via_mcp\"\ndescription = \"x\"\nkind = \"mcp\"\n\
1823 command = [\"x\"]\n",
1824 );
1825 let loaded = load(&[dir], &["broken".into()]);
1826 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
1827 assert!(tools.is_empty());
1828 assert_eq!(problems.len(), 2, "{problems:?}");
1829 assert!(problems[0].contains("no `command`"), "{problems:?}");
1830 assert!(
1831 problems[1].contains("belongs on a `[[mcp]]` section"),
1832 "{problems:?}"
1833 );
1834 }
1835
1836 const MCP_FIXTURE: &str = r#"#!/usr/bin/env python3
1839import json, sys
1840
1841def send(obj):
1842 sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
1843
1844for line in sys.stdin:
1845 if not line.strip():
1846 continue
1847 msg = json.loads(line)
1848 mid, method = msg.get("id"), msg.get("method")
1849 params = msg.get("params") or {}
1850 if method == "initialize":
1851 send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
1852 "capabilities": {"tools": {}}, "serverInfo": {"name": "fixture", "version": "0"}}})
1853 elif method == "notifications/initialized":
1854 pass
1855 elif method == "tools/list":
1856 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1857 {"name": "read_text_file", "description": "Read a file",
1858 "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}},
1859 {"name": "write_text_file", "description": "Write a file"}]}})
1860 elif method == "tools/call":
1861 send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
1862 {"type": "text", "text": "called " + str(params.get("name"))}]}})
1863 elif mid is not None:
1864 send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no"}})
1865"#;
1866
1867 fn mcp_plugin(tmp: &Path, extra: &str) -> PathBuf {
1868 let dir = tmp.join("plugins");
1869 let script = dir.join("fs").join("server.py");
1870 std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1871 std::fs::write(&script, MCP_FIXTURE).unwrap();
1872 let manifest = format!(
1873 "name = \"fs\"\n\n[[mcp]]\nname = \"files\"\ncommand = \"python3\"\n\
1874 args = [\"{}\"]\ncwd = \"plugin\"\ntimeout_secs = 15\n{extra}\n",
1875 script.display()
1876 );
1877 write(&dir.join("fs"), "plugin.toml", &manifest);
1878 dir
1879 }
1880
1881 #[test]
1882 fn mcp_off_starts_no_server_at_all() {
1883 let tmp = tempfile::tempdir().unwrap();
1884 let dir = tmp.path().join("plugins");
1885 let marker = tmp.path().join("spawned");
1887 let script = dir.join("loud").join("server.sh");
1888 std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1889 std::fs::write(&script, format!("#!/bin/sh\ntouch {}\n", marker.display())).unwrap();
1890 write(
1891 &dir.join("loud"),
1892 "plugin.toml",
1893 &format!(
1894 "name = \"loud\"\n\n[[mcp]]\nname = \"loud\"\ncommand = \"/bin/sh\"\n\
1895 args = [\"{}\"]\n",
1896 script.display()
1897 ),
1898 );
1899
1900 let on = load(std::slice::from_ref(&dir), &["loud".into()]);
1903 let (_tools, problems) = on.tools(tmp.path(), 4096, &[]);
1904 assert!(
1905 !problems.is_empty(),
1906 "a bad server is reported when MCP is on"
1907 );
1908 assert!(
1909 marker.exists(),
1910 "when MCP is on, the server process really ran"
1911 );
1912
1913 std::fs::remove_file(&marker).unwrap();
1915 let off = load(&[dir], &["loud".into()]).with_mcp(McpSettings(None));
1916 let (tools, problems) = off.tools(tmp.path(), 4096, &[]);
1917 assert!(
1918 tools.is_empty(),
1919 "no tools from a server that was never asked"
1920 );
1921 assert!(
1922 problems.is_empty(),
1923 "nothing to complain about when nothing ran: {problems:?}"
1924 );
1925 assert!(
1926 !marker.exists(),
1927 "with MCP off, no server process was spawned"
1928 );
1929
1930 assert_eq!(
1933 mcp_timeout(&crate::config::Config::default()),
1934 DEFAULT_TIMEOUT
1935 );
1936 let mut cfg = crate::config::Config::default();
1937 cfg.plugins.mcp_timeout_secs = Some(5);
1938 assert_eq!(mcp_timeout(&cfg), Duration::from_secs(5));
1939 }
1940
1941 #[test]
1942 fn an_mcp_server_contributes_its_tools_with_their_own_source_and_policies() {
1943 if std::process::Command::new("python3")
1944 .arg("--version")
1945 .output()
1946 .map(|o| !o.status.success())
1947 .unwrap_or(true)
1948 {
1949 return;
1950 }
1951 let tmp = tempfile::tempdir().unwrap();
1952 let dir = mcp_plugin(tmp.path(), "policies = { read_text_file = \"allow\" }");
1953 let loaded = load(&[dir], &["fs".into()]);
1954 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1955 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
1956 assert!(problems.is_empty(), "{problems:?}");
1957 let names: Vec<&str> = tools.iter().map(|t| t.tool.name()).collect();
1958 assert_eq!(names, ["read_text_file", "write_text_file"]);
1959 for t in &tools {
1961 assert_eq!(t.source.label(), "plugin:mcp:files", "{}", t.tool.name());
1962 }
1963 let read = tools
1965 .iter()
1966 .find(|t| t.tool.name() == "read_text_file")
1967 .unwrap();
1968 let write = tools
1969 .iter()
1970 .find(|t| t.tool.name() == "write_text_file")
1971 .unwrap();
1972 assert_eq!(read.policy, Policy::Allow);
1973 assert_eq!(write.policy, Policy::Ask);
1974 assert_eq!(
1976 read.tool.parameters()["properties"]["path"]["type"],
1977 "string"
1978 );
1979 let out = tokio::runtime::Builder::new_current_thread()
1981 .enable_all()
1982 .build()
1983 .unwrap()
1984 .block_on(read.tool.call(json!({"path": "a.txt"})))
1985 .unwrap();
1986 assert_eq!(out, "called read_text_file");
1987
1988 let (again, _) = loaded.tools(tmp.path(), 4096, &[]);
1991 assert_eq!(again.len(), 2);
1992 let out = tokio::runtime::Builder::new_current_thread()
1993 .enable_all()
1994 .build()
1995 .unwrap()
1996 .block_on(again[0].tool.call(json!({"path": "b.txt"})))
1997 .unwrap();
1998 assert_eq!(out, "called read_text_file");
1999 }
2000
2001 #[test]
2002 fn a_server_tool_that_collides_is_refused_unless_the_entry_says_override() {
2003 if std::process::Command::new("python3")
2004 .arg("--version")
2005 .output()
2006 .map(|o| !o.status.success())
2007 .unwrap_or(true)
2008 {
2009 return;
2010 }
2011 let tmp = tempfile::tempdir().unwrap();
2012 let dir = mcp_plugin(tmp.path(), "");
2013 let loaded = load(&[dir], &["fs".into()]);
2014 let builtin = vec!["read_text_file".to_string()];
2017 let (tools, problems) = loaded.tools(tmp.path(), 4096, &builtin);
2018 assert_eq!(tools.len(), 1, "the other one still loads");
2019 assert_eq!(tools[0].tool.name(), "write_text_file");
2020 assert!(
2021 problems[0].contains("collides") && problems[0].contains("override = true"),
2022 "{problems:?}"
2023 );
2024 }
2025
2026 #[test]
2027 fn a_server_that_will_not_start_is_one_problem_and_no_tools() {
2028 let tmp = tempfile::tempdir().unwrap();
2029 let dir = tmp.path().join("plugins");
2030 write(
2031 &dir.join("dead"),
2032 "plugin.toml",
2033 "name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
2034 );
2035 let loaded = load(&[dir], &["dead".into()]);
2036 assert!(loaded.problems.is_empty(), "the manifest itself is fine");
2037 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2038 assert!(tools.is_empty());
2039 assert!(
2040 problems[0].contains("could not start") && problems[0].contains("gone"),
2041 "{problems:?}"
2042 );
2043 }
2044
2045 #[test]
2046 fn inline_parameters_and_a_schema_file_both_work() {
2047 let tmp = tempfile::tempdir().unwrap();
2048 let dir = tmp.path().join("plugins");
2049 write(
2050 &dir.join("p"),
2051 "plugin.toml",
2052 "name = \"p\"\n\
2053 [[tool]]\nname = \"inline\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2054 parameters = { type = \"object\", properties = { n = { type = \"string\" } } }\n\
2055 [[tool]]\nname = \"from_file\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2056 parameters = \"tools/from_file.json\"\n",
2057 );
2058 write(
2059 &dir.join("p"),
2060 "tools/from_file.json",
2061 "{\"type\":\"object\",\"properties\":{\"n\":{\"type\":\"integer\"}}}",
2062 );
2063 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2064 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2065 assert!(problems.is_empty(), "{problems:?}");
2066 assert_eq!(
2067 tools[0].tool.parameters()["properties"]["n"]["type"],
2068 "string"
2069 );
2070 assert_eq!(
2071 tools[1].tool.parameters()["properties"]["n"]["type"],
2072 "integer"
2073 );
2074
2075 std::fs::remove_file(dir.join("p/tools/from_file.json")).unwrap();
2076 let loaded = load(&[dir], &["p".into()]);
2077 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2078 assert_eq!(tools.len(), 1);
2079 assert!(problems[0].contains("from_file.json"), "{problems:?}");
2080 }
2081
2082 #[cfg(unix)]
2083 #[tokio::test]
2084 async fn a_command_tool_gets_json_on_stdin_and_returns_stdout() {
2085 let tmp = tempfile::tempdir().unwrap();
2086 let dir = tmp.path().join("plugins");
2087 write(
2088 &dir.join("echoer"),
2089 "plugin.toml",
2090 "name = \"echoer\"\n[[tool]]\nname = \"echo_args\"\n\
2091 description = \"Echo the JSON it was given\"\n\
2092 command = [\"sh\", \"-c\", \"cat\"]\npolicy = \"allow\"\n",
2093 );
2094 let loaded = load(&[dir], &["echoer".into()]);
2095 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2096 let out = tools[0]
2097 .tool
2098 .call(json!({"path": "a.txt"}))
2099 .await
2100 .expect("tool should succeed");
2101 let sent: Value = serde_json::from_str(&out).unwrap();
2102 assert_eq!(sent["arguments"]["path"], "a.txt");
2103 assert_eq!(sent["tool"], "echo_args");
2104 }
2105
2106 #[cfg(unix)]
2107 #[tokio::test]
2108 async fn a_non_zero_exit_is_an_error_that_carries_both_streams() {
2109 let tmp = tempfile::tempdir().unwrap();
2110 let dir = tmp.path().join("plugins");
2111 write(
2112 &dir.join("fail"),
2113 "plugin.toml",
2114 "name = \"fail\"\n[[tool]]\nname = \"boom\"\ndescription = \"x\"\n\
2115 command = [\"sh\", \"-c\", \"echo out; echo bad >&2; exit 3\"]\npolicy = \"allow\"\n",
2116 );
2117 let loaded = load(&[dir], &["fail".into()]);
2118 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2119 let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2120 assert!(err.contains("exit code 3"), "{err}");
2121 assert!(err.contains("out") && err.contains("bad"), "{err}");
2122 }
2123
2124 #[cfg(unix)]
2125 #[tokio::test]
2126 async fn the_command_runs_in_the_workspace_and_only_sees_the_allowed_environment() {
2127 let tmp = tempfile::tempdir().unwrap();
2128 let (dir, ws) = (tmp.path().join("plugins"), tmp.path().join("ws"));
2129 std::fs::create_dir_all(&ws).unwrap();
2130 std::env::set_var("PLUGIN_TEST_SECRET", "leak-me");
2131 std::env::set_var("PLUGIN_TEST_ALLOWED", "ok");
2132 write(
2133 &dir.join("env"),
2134 "plugin.toml",
2135 "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2136 command = [\"sh\", \"-c\", \"pwd; echo secret=[${PLUGIN_TEST_SECRET:-}]; \
2137 echo allowed=[${PLUGIN_TEST_ALLOWED:-}]\"]\n\
2138 env = [\"PLUGIN_TEST_ALLOWED\"]\npolicy = \"allow\"\n",
2139 );
2140 let loaded = load(&[dir], &["env".into()]);
2141 let (tools, _) = loaded.tools(&ws, 4096, &[]);
2142 let out = tools[0].tool.call(json!({})).await.unwrap();
2143 let canonical = std::fs::canonicalize(&ws).unwrap();
2144 assert!(out.contains(&canonical.display().to_string()), "{out}");
2145 assert!(
2146 out.contains("secret=[]"),
2147 "the agent environment must not leak: {out}"
2148 );
2149 assert!(out.contains("allowed=[ok]"), "{out}");
2150 std::env::remove_var("PLUGIN_TEST_SECRET");
2151 std::env::remove_var("PLUGIN_TEST_ALLOWED");
2152 }
2153
2154 #[cfg(unix)]
2155 #[tokio::test]
2156 async fn a_plugin_tool_is_told_where_the_scripts_are_and_its_path_is_left_alone() {
2157 let tmp = tempfile::tempdir().unwrap();
2158 let dir = tmp.path().join("plugins");
2159 let scripts = tmp.path().join("scripts");
2160 write(
2161 &dir.join("env"),
2162 "plugin.toml",
2163 "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2164 command = [\"sh\", \"-c\", \"echo scripts=[${ECLIPSE_SCRIPTS_DIR:-}]; echo path=[$PATH]\"]\n\
2165 policy = \"allow\"\n",
2166 );
2167 let with = load(std::slice::from_ref(&dir), &["env".into()])
2168 .with_scripts_dir(Some(scripts.clone()));
2169 let (tools, _) = with.tools(tmp.path(), 4096, &[]);
2170 let out = tools[0].tool.call(json!({})).await.unwrap();
2171 assert!(
2172 out.contains(&format!("scripts=[{}]", scripts.display())),
2173 "{out}"
2174 );
2175 let path_line = out.lines().find(|l| l.starts_with("path=")).unwrap();
2176 assert!(
2177 !path_line.contains(&scripts.display().to_string()),
2178 "a plugin's PATH must not gain the scripts directory: {out}"
2179 );
2180
2181 let without = load(&[dir], &["env".into()]);
2182 let (tools, _) = without.tools(tmp.path(), 4096, &[]);
2183 let out = tools[0].tool.call(json!({})).await.unwrap();
2184 assert!(out.contains("scripts=[]"), "{out}");
2185 }
2186
2187 #[cfg(unix)]
2188 #[tokio::test]
2189 async fn a_hook_process_is_told_where_the_scripts_are_too() {
2190 let tmp = tempfile::tempdir().unwrap();
2191 let dir = tmp.path().join("plugins");
2192 write(
2193 &dir.join("guard"),
2194 "plugin.toml",
2195 "name = \"guard\"\n\
2196 [[hook]]\nevent = \"before_tool\"\n\
2197 command = [\"sh\", \"-c\", \"echo $ECLIPSE_SCRIPTS_DIR >&2; exit 2\"]\n",
2198 );
2199 let loaded = load(&[dir], &["guard".into()])
2200 .with_scripts_dir(Some(PathBuf::from("/somewhere/scripts")));
2201 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2202 match hooks.before("shell", &json!({}), None).await {
2203 Verdict::Deny(why) => assert_eq!(why, "/somewhere/scripts"),
2204 Verdict::Allow => panic!("the hook should have refused"),
2205 }
2206 }
2207
2208 #[cfg(unix)]
2209 #[tokio::test]
2210 async fn a_slow_tool_times_out() {
2211 let tmp = tempfile::tempdir().unwrap();
2212 let dir = tmp.path().join("plugins");
2213 write(
2214 &dir.join("slow"),
2215 "plugin.toml",
2216 "name = \"slow\"\n[[tool]]\nname = \"wait\"\ndescription = \"x\"\n\
2217 command = [\"sleep\", \"30\"]\ntimeout_secs = 1\npolicy = \"allow\"\n",
2218 );
2219 let loaded = load(&[dir], &["slow".into()]);
2220 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2221 let started = std::time::Instant::now();
2222 let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2223 assert!(err.contains("timed out after 1s"), "{err}");
2224 assert!(started.elapsed() < Duration::from_secs(10));
2225 }
2226
2227 #[test]
2228 fn prompt_fragments_are_read_in_order_and_a_broken_one_is_a_problem() {
2229 let tmp = tempfile::tempdir().unwrap();
2230 let dir = tmp.path().join("plugins");
2231 write(
2232 &dir.join("p"),
2233 "plugin.toml",
2234 "name = \"p\"\n\
2235 [[prompt]]\ntext = \"first\"\n\
2236 [[prompt]]\nfile = \"prompts/second.md\"\n",
2237 );
2238 write(&dir.join("p"), "prompts/second.md", "second");
2239 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2240 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2241 assert_eq!(loaded.prompts(), ["first", "second"]);
2242
2243 std::fs::remove_file(dir.join("p/prompts/second.md")).unwrap();
2244 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2245 assert_eq!(loaded.prompts(), ["first"]);
2246 assert!(
2247 loaded.problems[0].contains("prompt file"),
2248 "{:?}",
2249 loaded.problems
2250 );
2251
2252 write(
2253 &dir.join("p"),
2254 "plugin.toml",
2255 "name = \"p\"\n[[prompt]]\ntext = \"x\"\nfile = \"y\"\n",
2256 );
2257 let loaded = load(&[dir], &["p".into()]);
2258 assert!(loaded.prompts().is_empty());
2259 assert!(
2260 loaded.problems[0].contains("either `text` or `file`"),
2261 "{:?}",
2262 loaded.problems
2263 );
2264 }
2265
2266 #[test]
2270 fn a_manifest_path_that_points_outside_the_plugin_is_refused() {
2271 let tmp = tempfile::tempdir().unwrap();
2272 let dir = tmp.path().join("plugins");
2273 let secret = dir.join("id_rsa");
2275 write(&dir, "id_rsa", "-----BEGIN OPENSSH PRIVATE KEY-----\n");
2276
2277 write(
2279 &dir.join("p"),
2280 "plugin.toml",
2281 "name = \"p\"\n[[prompt]]\nfile = \"../id_rsa\"\n",
2282 );
2283 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2284 assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2285 assert!(
2286 loaded
2287 .problems
2288 .iter()
2289 .any(|p| p.contains("outside the plugin")),
2290 "{:?}",
2291 loaded.problems
2292 );
2293
2294 write(
2295 &dir.join("p"),
2296 "plugin.toml",
2297 &format!("name = \"p\"\n[[prompt]]\nfile = {secret:?}\n"),
2298 );
2299 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2300 assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2301 assert!(
2302 loaded
2303 .problems
2304 .iter()
2305 .any(|p| p.contains("outside the plugin")),
2306 "{:?}",
2307 loaded.problems
2308 );
2309
2310 write(
2312 &dir.join("p"),
2313 "plugin.toml",
2314 "name = \"p\"\n[[tool]]\nname = \"leak\"\ndescription = \"x\"\n\
2315 command = [\"echo\"]\nparameters = \"../id_rsa\"\npolicy = \"allow\"\n",
2316 );
2317 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2318 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2319 assert!(tools.is_empty(), "no tool was built from the link");
2320 assert!(
2321 problems.iter().any(|p| p.contains("outside the plugin")),
2322 "{:?}",
2323 problems
2324 );
2325 }
2326
2327 #[test]
2331 fn a_manifest_path_inside_the_plugin_is_read_and_a_directory_is_refused() {
2332 let tmp = tempfile::tempdir().unwrap();
2333 let dir = tmp.path().join("plugins");
2334 write(
2335 &dir.join("p"),
2336 "plugin.toml",
2337 "name = \"p\"\n[[prompt]]\nfile = \"prompts/first.md\"\n",
2338 );
2339 write(&dir.join("p"), "prompts/first.md", "inside");
2340 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2341 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2342 assert_eq!(loaded.prompts(), ["inside"]);
2343
2344 std::fs::create_dir_all(dir.join("p/prompts/dir.md")).unwrap();
2345 write(
2346 &dir.join("p"),
2347 "plugin.toml",
2348 "name = \"p\"\n[[prompt]]\nfile = \"prompts/dir.md\"\n",
2349 );
2350 let loaded = load(&[dir], &["p".into()]);
2351 assert!(loaded.prompts().is_empty());
2352 assert!(
2353 loaded
2354 .problems
2355 .iter()
2356 .any(|p| p.contains("not a regular file")),
2357 "{:?}",
2358 loaded.problems
2359 );
2360 }
2361
2362 #[test]
2368 fn a_plugin_loaded_for_its_profiles_is_not_enabled_and_has_no_skills_root() {
2369 let tmp = tempfile::tempdir().unwrap();
2370 let dir = tmp.path().join("plugins");
2371 write(
2372 &dir.join("wire"),
2373 "plugin.toml",
2374 "name = \"wire\"\n\
2375 [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n",
2376 );
2377 write(
2379 &dir.join("wire/skills/sneaky/SKILL.md"),
2380 "SKILL.md",
2381 "---\nname: sneaky\ndescription: not yours\n---\n\nx\n",
2382 );
2383
2384 let loaded = load(std::slice::from_ref(&dir), &[]);
2385 assert_eq!(
2386 loaded.plugins.len(),
2387 1,
2388 "loaded for its profiles: {:?}",
2389 loaded.problems
2390 );
2391 assert!(
2392 !loaded.plugins[0].enabled,
2393 "loaded is not the same as enabled"
2394 );
2395 let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2396 assert!(
2397 !roots.iter().any(|r| r.dir.ends_with("wire/skills")),
2398 "an unenabled plugin's skills are not roots: {roots:?}"
2399 );
2400
2401 let loaded = load(&[dir], &["wire".into()]);
2403 assert!(loaded.plugins[0].enabled);
2404 let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2405 assert!(roots.iter().any(|r| r.dir.ends_with("wire/skills")));
2406 }
2407
2408 #[test]
2409 fn provider_profiles_override_by_name_and_keep_order() {
2410 let tmp = tempfile::tempdir().unwrap();
2411 let dir = tmp.path().join("plugins");
2412 write(
2413 &dir.join("prov"),
2414 "plugin.toml",
2415 "name = \"prov\"\n\
2416 [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n\
2417 [provider_profile.body]\nchat_template_kwargs = { enable_thinking = false }\n\
2418 [[provider_profile]]\nname = \"acme\"\nsupports_tools = false\n",
2419 );
2420 let loaded = load(&[dir], &["prov".into()]);
2421 let profiles = loaded.provider_profiles();
2422 assert_eq!(profiles.len(), 2);
2423 assert_eq!(profiles[0].name, "llamacpp");
2424 assert!(!profiles[0].tool_choice);
2425 assert_eq!(
2426 profiles[0].body["chat_template_kwargs"]["enable_thinking"],
2427 json!(false)
2428 );
2429 assert!(!profiles[1].supports_tools);
2430 }
2431
2432 #[cfg(unix)]
2433 #[tokio::test]
2434 async fn a_before_tool_hook_can_refuse_with_a_reason() {
2435 let tmp = tempfile::tempdir().unwrap();
2436 let dir = tmp.path().join("plugins");
2437 write(
2438 &dir.join("guard"),
2439 "plugin.toml",
2440 "name = \"guard\"\n\
2441 [[hook]]\nevent = \"before_tool\"\ntool = \"shell\"\n\
2442 command = [\"sh\", \"-c\", \"echo 'no shell in this repo' >&2; exit 2\"]\n",
2443 );
2444 let loaded = load(&[dir], &["guard".into()]);
2445 assert_eq!(loaded.hooks().len(), 1);
2446 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2447 match hooks.before("shell", &json!({"command": "ls"}), None).await {
2448 Verdict::Deny(why) => assert_eq!(why, "no shell in this repo"),
2449 Verdict::Allow => panic!("the hook should have refused"),
2450 }
2451 assert!(matches!(
2452 hooks.before("read_file", &json!({}), None).await,
2453 Verdict::Allow
2454 ));
2455 }
2456
2457 #[cfg(unix)]
2458 #[tokio::test]
2459 async fn a_guard_that_cannot_run_refuses_rather_than_allowing() {
2460 let tmp = tempfile::tempdir().unwrap();
2461 let dir = tmp.path().join("plugins");
2462 write(
2463 &dir.join("broken-guard"),
2464 "plugin.toml",
2465 "name = \"broken-guard\"\n\
2466 [[hook]]\nevent = \"before_tool\"\ncommand = [\"./missing.sh\"]\ncwd = \"plugin\"\n",
2467 );
2468 let loaded = load(&[dir], &["broken-guard".into()]);
2469 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2470 match hooks.before("anything", &json!({}), None).await {
2471 Verdict::Deny(why) => assert!(why.contains("could not run"), "{why}"),
2472 Verdict::Allow => panic!("a guard that cannot run must not silently allow"),
2473 }
2474 }
2475
2476 #[cfg(unix)]
2477 #[tokio::test]
2478 async fn an_after_tool_hook_can_rewrite_the_output() {
2479 let tmp = tempfile::tempdir().unwrap();
2480 let dir = tmp.path().join("plugins");
2481 write(
2484 &dir.join("redact"),
2485 "plugin.toml",
2486 "name = \"redact\"\n\
2487 [[hook]]\nevent = \"after_tool\"\n\
2488 command = [\"sh\", \"-c\", \"printf 'the [redacted] is here'\"]\n",
2489 );
2490 let loaded = load(std::slice::from_ref(&dir), &["redact".into()]);
2491 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2492 let out = hooks
2493 .after(
2494 "read_file",
2495 &json!({}),
2496 ToolOutcome {
2497 output: "the secret is here".into(),
2498 is_error: false,
2499 malformed: false,
2500 deferred: false,
2501 },
2502 None,
2503 )
2504 .await;
2505 assert_eq!(out.output, "the [redacted] is here");
2506 assert!(!out.is_error);
2507
2508 write(
2510 &dir.join("quiet"),
2511 "plugin.toml",
2512 "name = \"quiet\"\n\
2513 [[hook]]\nevent = \"after_tool\"\ncommand = [\"true\"]\n",
2514 );
2515 let quiet = load(&[dir], &["quiet".into()]);
2516 let hooks = Hooks::new(quiet.hooks(), PathBuf::from("/tmp"), "default");
2517 let out = hooks
2518 .after(
2519 "read_file",
2520 &json!({}),
2521 ToolOutcome {
2522 output: "unchanged".into(),
2523 is_error: true,
2524 malformed: false,
2525 deferred: false,
2526 },
2527 None,
2528 )
2529 .await;
2530 assert_eq!(out.output, "unchanged");
2531 assert!(out.is_error);
2532 }
2533
2534 #[test]
2535 fn the_shipped_examples_all_load() {
2536 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/plugins");
2538 if !root.is_dir() {
2539 return;
2540 }
2541 let names: Vec<String> = discover_all(std::slice::from_ref(&root))
2542 .into_iter()
2543 .map(|(name, _)| name)
2544 .collect();
2545 assert!(!names.is_empty(), "no examples found in {}", root.display());
2546 let loaded = load(std::slice::from_ref(&root), &names);
2547 assert!(
2548 loaded.problems.is_empty(),
2549 "the shipped examples must load cleanly: {:?}",
2550 loaded.problems
2551 );
2552 let (tools, problems) = loaded.tools(&root, 4096, &[]);
2553 assert!(problems.is_empty(), "{problems:?}");
2554 assert_eq!(tools.len(), 3, "git_status, git_diff, git_log");
2555 assert_eq!(loaded.provider_profiles().len(), 1);
2556 assert_eq!(loaded.hooks().len(), 1);
2557 assert!(!loaded.prompts().is_empty());
2558 }
2559
2560 #[test]
2561 fn discover_all_lists_manifests_whether_enabled_or_not() {
2562 let tmp = tempfile::tempdir().unwrap();
2563 let dir = tmp.path().join("plugins");
2564 manifest(&dir.join("a"), "a");
2565 manifest(&dir.join("b"), "b");
2566 std::fs::create_dir_all(dir.join("not-a-plugin")).unwrap();
2567 let found = discover_all(&[dir]);
2568 assert_eq!(found.len(), 2);
2569 }
2570
2571 #[cfg(unix)]
2572 #[tokio::test]
2573 async fn a_hook_payload_names_the_tool_call_it_is_about() {
2574 let tmp = tempfile::tempdir().unwrap();
2577 let dir = tmp.path().join("plugins");
2578 write(
2579 &dir.join("echo-payload"),
2580 "plugin.toml",
2581 "name = \"echo-payload\"\n\
2582 [[hook]]\nevent = \"after_tool\"\ncommand = [\"sh\", \"-c\", \"cat\"]\n",
2583 );
2584 let loaded = load(&[dir], &["echo-payload".into()]);
2585 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2586 let outcome = || ToolOutcome {
2587 output: "x".into(),
2588 is_error: false,
2589 malformed: false,
2590 deferred: false,
2591 };
2592 let named = hooks
2593 .after("read_file", &json!({}), outcome(), Some("c7"))
2594 .await;
2595 assert!(
2596 named.output.contains("\"call_id\":\"c7\""),
2597 "a hook must be able to tell concurrent calls apart: {}",
2598 named.output
2599 );
2600 let unnamed = hooks.after("read_file", &json!({}), outcome(), None).await;
2602 assert!(
2603 unnamed.output.contains("\"call_id\":null"),
2604 "{}",
2605 unnamed.output
2606 );
2607 }
2608}
2609
2610#[cfg(test)]
2611mod size_cap_tests {
2612 use super::*;
2613
2614 fn write(dir: &Path, rel: &str, text: &str) {
2615 let p = dir.join(rel);
2616 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
2617 std::fs::write(p, text).unwrap();
2618 }
2619
2620 #[test]
2623 fn an_oversized_prompt_file_is_cut_and_says_so() {
2624 let tmp = tempfile::tempdir().unwrap();
2625 let dir = tmp.path().join("plugins");
2626 write(
2627 &dir.join("longprompt"),
2628 "plugin.toml",
2629 "name = \"longprompt\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2630 [[prompt]]\nfile = \"prompts/rules.md\"\n",
2631 );
2632 let line = "keep the answer short and cite the file. ";
2634 let body = line.repeat((MAX_MANIFEST_FILE_BYTES as usize / line.len()) + 10);
2635 write(&dir.join("longprompt"), "prompts/rules.md", &body);
2636
2637 let loaded = load(&[dir], &["longprompt".into()]);
2638 assert!(
2639 loaded
2640 .problems
2641 .iter()
2642 .any(|p| p.contains("truncated") && p.contains("rules.md")),
2643 "the truncation is reported to the human: {:?}",
2644 loaded.problems
2645 );
2646 let text = loaded.plugins[0].manifest.prompts[0]
2647 .text
2648 .as_deref()
2649 .expect("the prompt resolves");
2650 assert!(
2651 text.len() <= MAX_MANIFEST_FILE_BYTES as usize + 128,
2652 "the prompt is capped, not passed through: {} bytes",
2653 text.len()
2654 );
2655 assert!(
2656 text.ends_with("bytes)"),
2657 "and the model is told the text is incomplete: …{}",
2658 &text[text.len().saturating_sub(80)..]
2659 );
2660 assert!(
2661 text.contains(line.trim()),
2662 "the part that arrived is the real text, not a placeholder"
2663 );
2664 }
2665
2666 #[test]
2669 fn an_oversized_parameters_file_is_refused_not_truncated() {
2670 let tmp = tempfile::tempdir().unwrap();
2671 let dir = tmp.path().join("plugins");
2672 write(
2673 &dir.join("paramtool"),
2674 "plugin.toml",
2675 "name = \"paramtool\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2676 [[tool]]\nname = \"thing\"\ndescription = \"A thing\"\n\
2677 command = [\"sh\", \"-c\", \"echo hi\"]\npolicy = \"allow\"\n\
2678 parameters = \"params.json\"\n",
2679 );
2680 let filler = "x".repeat(MAX_MANIFEST_FILE_BYTES as usize + 1);
2681 write(
2682 &dir.join("paramtool"),
2683 "params.json",
2684 &format!("{{\"type\":\"object\",\"description\":\"{filler}\"}}"),
2685 );
2686
2687 let loaded = load(&[dir], &["paramtool".into()]);
2688 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2689 assert!(
2690 problems
2691 .iter()
2692 .any(|p| p.contains("limit is") && p.contains("params.json")),
2693 "the refusal names the file and both sizes: {problems:?}"
2694 );
2695 assert!(
2696 tools.is_empty(),
2697 "the tool is not loaded with parameters nobody could read"
2698 );
2699 }
2700}