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 match tokio::time::timeout(timeout, run).await {
1256 Err(_) => Err(format!("timed out after {}s", timeout.as_secs())),
1257 Ok(((out, out_cut), (err, _), status)) => {
1258 let status = status.map_err(|e| format!("failed to wait: {e}"))?;
1259 Ok(Output {
1260 stdout: out,
1261 stderr: err,
1262 code: status.code(),
1263 stdout_cut: out_cut,
1264 })
1265 }
1266 }
1267}
1268
1269struct CommandTool {
1271 name: String,
1272 description: String,
1273 parameters: Value,
1274 command: Vec<String>,
1275 plugin: String,
1276 plugin_dir: PathBuf,
1277 workspace: PathBuf,
1278 cwd: Cwd,
1279 timeout: Duration,
1280 env: Vec<String>,
1281 max_bytes: usize,
1282 scripts_dir: Option<PathBuf>,
1283}
1284
1285#[async_trait]
1286impl Tool for CommandTool {
1287 fn name(&self) -> &str {
1288 &self.name
1289 }
1290 fn description(&self) -> &str {
1291 &self.description
1292 }
1293 fn parameters(&self) -> Value {
1294 self.parameters.clone()
1295 }
1296 fn describe_call(&self, args: &Value) -> String {
1297 format!("run {}({args}) from plugin {}", self.name, self.plugin)
1298 }
1299 async fn call(&self, args: Value) -> Result<String, ToolError> {
1300 let cwd = match self.cwd {
1301 Cwd::Workspace => self.workspace.clone(),
1302 Cwd::Plugin => self.plugin_dir.clone(),
1303 };
1304 let payload = json!({
1305 "tool": self.name,
1306 "arguments": args,
1307 "plugin": self.plugin,
1308 "workspace": self.workspace.display().to_string(),
1309 });
1310 let out = run_command(
1311 &self.command,
1312 &cwd,
1313 self.timeout,
1314 Context {
1315 plugin_dir: &self.plugin_dir,
1316 workspace: &self.workspace,
1317 extra_env: &self.env,
1318 scripts_dir: self.scripts_dir.as_deref(),
1319 max_bytes: self.max_bytes,
1320 },
1321 payload,
1322 )
1323 .await
1324 .map_err(ToolError::Failed)?;
1325 let truncated = if out.stdout_cut { "\n[truncated]" } else { "" };
1326 let stdout = out.stdout.trim_end_matches('\n');
1327 if out.code == Some(0) {
1328 return Ok(format!("{stdout}{truncated}"));
1329 }
1330 let code = out
1331 .code
1332 .map(|c| c.to_string())
1333 .unwrap_or_else(|| "signal".into());
1334 Err(ToolError::Failed(format!(
1335 "exit code {code}\nstdout:\n{stdout}{truncated}\nstderr:\n{}",
1336 out.stderr.trim_end_matches('\n')
1337 )))
1338 }
1339}
1340
1341pub struct Hook {
1343 event: Event,
1344 tool: Option<String>,
1345 command: Vec<String>,
1346 timeout: Duration,
1347 cwd: Cwd,
1348 env: Vec<String>,
1349 plugin_dir: PathBuf,
1350 plugin: String,
1351 max_bytes: usize,
1352 scripts_dir: Option<PathBuf>,
1353}
1354
1355impl Hook {
1356 fn matches(&self, tool: &str) -> bool {
1357 match &self.tool {
1358 None => true,
1359 Some(p) if p == "*" => true,
1360 Some(p) => p == tool,
1361 }
1362 }
1363}
1364
1365pub enum Verdict {
1367 Allow,
1368 Deny(String),
1370}
1371
1372#[derive(Default, Clone)]
1374pub struct Hooks {
1375 hooks: Vec<Arc<Hook>>,
1376 workspace: PathBuf,
1377 profile: String,
1378}
1379
1380impl Hooks {
1381 pub fn new(hooks: Vec<Arc<Hook>>, workspace: PathBuf, profile: impl Into<String>) -> Self {
1382 Self {
1383 hooks,
1384 workspace,
1385 profile: profile.into(),
1386 }
1387 }
1388
1389 pub async fn before(&self, tool: &str, arguments: &Value, call_id: Option<&str>) -> Verdict {
1397 for hook in self.hooks.iter().filter(|h| h.event == Event::BeforeTool) {
1398 if !hook.matches(tool) {
1399 continue;
1400 }
1401 let payload = json!({
1402 "event": "before_tool",
1403 "tool": tool,
1404 "arguments": arguments,
1405 "call_id": call_id,
1406 "plugin": hook.plugin,
1407 "workspace": self.workspace.display().to_string(),
1408 "profile": self.profile,
1409 });
1410 let out = self.run(hook, payload).await;
1411 match out {
1412 Ok(o) if o.code == Some(0) => continue,
1413 Ok(o) => {
1414 let reason = if !o.stderr.trim().is_empty() {
1415 o.stderr.trim().to_string()
1416 } else if !o.stdout.trim().is_empty() {
1417 o.stdout.trim().to_string()
1418 } else {
1419 format!("refused by plugin `{}`", hook.plugin)
1420 };
1421 return Verdict::Deny(reason);
1422 }
1423 Err(why) => {
1424 return Verdict::Deny(format!(
1425 "refused: the `{}` guard for this tool could not run ({why})",
1426 hook.plugin
1427 ))
1428 }
1429 }
1430 }
1431 Verdict::Allow
1432 }
1433
1434 pub async fn after(
1438 &self,
1439 tool: &str,
1440 arguments: &Value,
1441 outcome: ToolOutcome,
1442 call_id: Option<&str>,
1443 ) -> ToolOutcome {
1444 let mut outcome = outcome;
1445 for hook in self.hooks.iter().filter(|h| h.event == Event::AfterTool) {
1446 if !hook.matches(tool) {
1447 continue;
1448 }
1449 let payload = json!({
1450 "event": "after_tool",
1451 "tool": tool,
1452 "arguments": arguments,
1453 "output": outcome.output.clone(),
1454 "is_error": outcome.is_error,
1455 "call_id": call_id,
1456 "plugin": hook.plugin,
1457 "workspace": self.workspace.display().to_string(),
1458 "profile": self.profile,
1459 });
1460 if let Ok(o) = self.run(hook, payload).await {
1461 if o.code == Some(0) && !o.stdout.trim().is_empty() {
1462 outcome.output = o.stdout.trim_end_matches('\n').to_string();
1463 }
1464 }
1465 }
1466 outcome
1467 }
1468
1469 async fn run(&self, hook: &Hook, payload: Value) -> Result<Output, String> {
1470 let cwd = match hook.cwd {
1471 Cwd::Workspace => self.workspace.clone(),
1472 Cwd::Plugin => hook.plugin_dir.clone(),
1473 };
1474 run_command(
1475 &hook.command,
1476 &cwd,
1477 hook.timeout,
1478 Context {
1479 plugin_dir: &hook.plugin_dir,
1480 workspace: &self.workspace,
1481 extra_env: &hook.env,
1482 scripts_dir: hook.scripts_dir.as_deref(),
1483 max_bytes: hook.max_bytes,
1484 },
1485 payload,
1486 )
1487 .await
1488 }
1489}
1490
1491pub fn discover_all(dirs: &[PathBuf]) -> Vec<(String, PathBuf)> {
1494 let mut out: Vec<(String, PathBuf)> = Vec::new();
1495 for dir in dirs {
1496 let Ok(entries) = std::fs::read_dir(dir) else {
1497 continue;
1498 };
1499 let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
1500 paths.sort();
1501 for path in paths {
1502 if path.join(MANIFEST).is_file() {
1503 let name = path
1504 .file_name()
1505 .map(|n| n.to_string_lossy().to_string())
1506 .unwrap_or_default();
1507 if !out.iter().any(|(n, _)| n == &name) {
1508 out.push((name, path));
1509 }
1510 }
1511 }
1512 }
1513 out
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518 use super::*;
1519
1520 #[test]
1523 fn an_mcp_listing_line_does_not_print_the_credentials_in_its_url() {
1524 let spec: mcp::Spec = toml::from_str(
1525 "name = \"gh\"\ntransport = \"http\"\nurl = \"https://user:pw@example.test/mcp?token=abc\"\n",
1526 )
1527 .unwrap();
1528 let line = describe_command(&spec);
1529 assert!(!line.contains("pw"), "{line}");
1530 assert!(!line.contains("abc"), "{line}");
1531 assert!(
1532 line.contains("example.test/mcp"),
1533 "the endpoint is still recognisable: {line}"
1534 );
1535
1536 let plain: mcp::Spec = toml::from_str(
1537 "name = \"plain\"\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n",
1538 )
1539 .unwrap();
1540 assert_eq!(
1541 describe_command(&plain),
1542 "http https://example.test/mcp",
1543 "nothing to hide, nothing changed"
1544 );
1545 }
1546
1547 fn write(dir: &Path, rel: &str, text: &str) {
1548 let p = dir.join(rel);
1549 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1550 std::fs::write(p, text).unwrap();
1551 }
1552
1553 fn manifest(dir: &Path, name: &str) {
1554 write(
1555 dir,
1556 "plugin.toml",
1557 &format!(
1558 "name = \"{name}\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1559 [[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
1560 command = [\"sh\", \"-c\", \"echo hello $ECLIPSE_ARGS\"]\n\
1561 policy = \"allow\"\n"
1562 ),
1563 );
1564 }
1565
1566 #[test]
1571 fn a_listing_says_where_a_token_env_resolves() {
1572 let tmp = tempfile::tempdir().unwrap();
1573 let kept = format!("ECLIPSE_TEST_LIST_{}", "TOKEN");
1576 let absent = format!("{kept}_UNSET");
1577 std::env::remove_var(&kept);
1578 std::env::remove_var(&absent);
1579 let mut cfg = crate::config::parse_text(&format!(
1580 "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
1581 url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{kept}\"\ndisabled = true\n\n\
1582 [[mcp]]\nname = \"dead\"\ntransport = \"http\"\n\
1583 url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{absent}\"\ndisabled = true\n"
1584 ))
1585 .unwrap();
1586 cfg.dotenv.values.insert(kept.clone(), "kept".to_string());
1588
1589 let loaded = load(&[], &[]).with_config_mcp(&cfg);
1590 let (rows, _) = loaded.mcp_report(tmp.path());
1591 let row = |name: &str| {
1592 rows.iter()
1593 .find(|r| r.name == name)
1594 .unwrap_or_else(|| panic!("{name} is not listed: {rows:?}"))
1595 };
1596 assert_eq!(row("ha").token_env.as_deref(), Some(kept.as_str()));
1597 assert_eq!(row("ha").token, crate::mcp::TokenSource::Dotenv);
1598 assert_eq!(row("ha").token.as_str(), ".env");
1599 assert_eq!(row("dead").token, crate::mcp::TokenSource::Unset);
1600 assert_eq!(row("dead").token.as_str(), "unset");
1601 }
1602
1603 #[test]
1606 fn a_config_server_shadows_a_manifest_server_of_the_same_name() {
1607 let tmp = tempfile::tempdir().unwrap();
1608 let dir = tmp.path().join("plugins");
1609 write(
1610 &dir.join("pack"),
1611 "plugin.toml",
1612 r#"name = "pack"
1613version = "0.1.0"
1614
1615[[mcp]]
1616name = "notes"
1617command = "true"
1618policy = "allow"
1619"#,
1620 );
1621 let cfg =
1625 crate::config::parse_text("[[mcp]]\nname = \"notes\"\ncommand = \"false\"\n").unwrap();
1626 let loaded = load(&[dir], &["pack".into()]).with_config_mcp(&cfg);
1627 let (servers, problems) = loaded.servers(tmp.path());
1628 assert_eq!(servers.len(), 1, "one server, not two");
1629 assert_eq!(servers[0].source.label(), "config:mcp:notes");
1630 assert_eq!(servers[0].spec.command, "false", "the config's command");
1631 assert!(
1632 problems.iter().any(|p| p.contains("which wins")),
1633 "the shadowed entry is said out loud: {problems:?}"
1634 );
1635
1636 let alone = load(&[tmp.path().join("plugins")], &["pack".into()]);
1638 let (servers, problems) = alone.servers(tmp.path());
1639 assert_eq!(servers[0].source.label(), "plugin:mcp:notes");
1640 assert!(problems.is_empty(), "{problems:?}");
1641 }
1642
1643 #[test]
1644 fn loads_an_enabled_plugin_and_its_tool() {
1645 let tmp = tempfile::tempdir().unwrap();
1646 let dir = tmp.path().join("plugins");
1647 manifest(&dir.join("greeter"), "greeter");
1648 let loaded = load(&[dir], &["greeter".into()]);
1649 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1650 assert_eq!(loaded.plugins.len(), 1);
1651 assert_eq!(loaded.plugins[0].name, "greeter");
1652 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
1653 assert!(problems.is_empty(), "{problems:?}");
1654 assert_eq!(tools.len(), 1);
1655 assert_eq!(tools[0].tool.name(), "greet");
1656 assert_eq!(tools[0].policy, Policy::Allow);
1657 }
1658
1659 #[cfg(unix)]
1664 #[tokio::test]
1665 async fn a_payload_too_big_for_the_environment_still_reaches_the_plugin() {
1666 let tmp = tempfile::tempdir().unwrap();
1667 let dir = tmp.path().join("plugins").join("sizer");
1668 write(&dir, "size.sh", "#!/bin/sh\nprintf 'args=%s bytes=%s stdin=%s\\n' \"${ECLIPSE_ARGS:+set}\" \"${ECLIPSE_ARGS_BYTES:-none}\" \"$(wc -c)\"\n");
1669 write(
1670 &dir,
1671 "plugin.toml",
1672 "name = \"sizer\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1673 [[tool]]\nname = \"size\"\ndescription = \"Report what it was given\"\n\
1674 command = [\"sh\", \"size.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\n",
1675 );
1676 let loaded = load(&[tmp.path().join("plugins")], &["sizer".into()]);
1677 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1678 let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1679 assert!(problems.is_empty(), "{problems:?}");
1680
1681 let big = "x".repeat(200 * 1024);
1682 let out = tools[0]
1683 .tool
1684 .call(json!({"body": big}))
1685 .await
1686 .expect("a large payload must not stop the plugin from starting");
1687 assert!(
1688 !out.contains("args=set"),
1689 "the copy does not go into the environment: {out}"
1690 );
1691 assert!(
1692 !out.contains("bytes=none"),
1693 "the size does, so a plugin can tell empty from too big: {out}"
1694 );
1695 assert!(
1696 !out.contains("stdin=0"),
1697 "and the payload itself arrives on stdin: {out}"
1698 );
1699 }
1700
1701 #[cfg(unix)]
1705 #[tokio::test]
1706 async fn a_plugin_that_never_reads_its_input_still_times_out() {
1707 let tmp = tempfile::tempdir().unwrap();
1708 let dir = tmp.path().join("plugins").join("deaf");
1709 write(&dir, "deaf.sh", "#!/bin/sh\nsleep 20\n");
1710 write(
1711 &dir,
1712 "plugin.toml",
1713 "name = \"deaf\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1714 [[tool]]\nname = \"deaf\"\ndescription = \"Never reads its input\"\n\
1715 command = [\"sh\", \"deaf.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\ntimeout_secs = 1\n",
1716 );
1717 let loaded = load(&[tmp.path().join("plugins")], &["deaf".into()]);
1718 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1719 let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1720 assert!(problems.is_empty(), "{problems:?}");
1721
1722 let big = "x".repeat(200 * 1024);
1723 let call = tokio::time::timeout(
1724 Duration::from_secs(8),
1725 tools[0].tool.call(json!({"body": big})),
1726 )
1727 .await
1728 .expect("a full pipe must not hold the call");
1729 let err = call.expect_err("it never answered");
1730 assert!(err.to_string().contains("timed out"), "{err}");
1731 }
1732
1733 #[test]
1734 fn a_plugin_that_is_not_enabled_is_ignored_without_noise() {
1735 let tmp = tempfile::tempdir().unwrap();
1736 let dir = tmp.path().join("plugins");
1737 manifest(&dir.join("greeter"), "greeter");
1738 let loaded = load(&[dir], &[]);
1739 assert!(loaded.plugins.is_empty());
1740 assert!(loaded.problems.is_empty());
1741 }
1742
1743 #[test]
1744 fn enabling_a_missing_plugin_is_reported() {
1745 let tmp = tempfile::tempdir().unwrap();
1746 let loaded = load(&[tmp.path().join("plugins")], &["nope".into()]);
1747 assert!(
1748 loaded.problems[0].contains("enabled but was not found"),
1749 "{:?}",
1750 loaded.problems
1751 );
1752 }
1753
1754 #[test]
1755 fn a_name_that_does_not_match_the_directory_is_rejected() {
1756 let tmp = tempfile::tempdir().unwrap();
1757 let dir = tmp.path().join("plugins");
1758 manifest(&dir.join("greeter"), "someone-else");
1759 let loaded = load(&[dir], &["greeter".into()]);
1760 assert!(loaded.plugins.is_empty());
1761 assert!(
1762 loaded.problems[0].contains("does not match"),
1763 "{:?}",
1764 loaded.problems
1765 );
1766 }
1767
1768 #[test]
1769 fn a_newer_api_is_refused() {
1770 let tmp = tempfile::tempdir().unwrap();
1771 let dir = tmp.path().join("plugins");
1772 write(
1773 &dir.join("future"),
1774 "plugin.toml",
1775 "name = \"future\"\napi = 99\n",
1776 );
1777 let loaded = load(&[dir], &["future".into()]);
1778 assert!(
1779 loaded.problems[0].contains("needs plugin api 99"),
1780 "{:?}",
1781 loaded.problems
1782 );
1783 }
1784
1785 #[test]
1786 fn unknown_manifest_keys_are_errors_not_silence() {
1787 let tmp = tempfile::tempdir().unwrap();
1788 let dir = tmp.path().join("plugins");
1789 write(
1790 &dir.join("typo"),
1791 "plugin.toml",
1792 "name = \"typo\"\n[tool]\nname = \"x\"\nemabled = true\n",
1793 );
1794 let loaded = load(&[dir], &["typo".into()]);
1795 assert!(loaded.plugins.is_empty());
1796 assert!(!loaded.problems.is_empty());
1797 }
1798
1799 #[test]
1800 fn a_profile_copy_shadows_the_shared_copy() {
1801 let tmp = tempfile::tempdir().unwrap();
1802 let (shared, profile) = (
1803 tmp.path().join("plugins"),
1804 tmp.path().join("profile-plugins"),
1805 );
1806 for (root, marker) in [(&shared, "shared"), (&profile, "profile")] {
1807 write(
1808 &root.join("greeter"),
1809 "plugin.toml",
1810 &format!("name = \"greeter\"\ndescription = \"{marker}\"\n"),
1811 );
1812 }
1813 let loaded = load(&[profile, shared], &["greeter".into()]);
1814 assert_eq!(loaded.plugins.len(), 1);
1815 assert_eq!(loaded.plugins[0].description, "profile");
1816 }
1817
1818 #[test]
1819 fn replacing_a_tool_needs_an_explicit_override() {
1820 let tmp = tempfile::tempdir().unwrap();
1821 let dir = tmp.path().join("plugins");
1822 write(
1823 &dir.join("shadow"),
1824 "plugin.toml",
1825 "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"nope\"\n\
1826 command = [\"true\"]\n",
1827 );
1828 let builtin = vec!["shell".to_string()];
1829 let loaded = load(std::slice::from_ref(&dir), &["shadow".into()]);
1830 let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1831 assert!(tools.is_empty(), "a silent override must not happen");
1832 assert!(problems[0].contains("override = true"), "{problems:?}");
1833
1834 write(
1835 &dir.join("shadow"),
1836 "plugin.toml",
1837 "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"mine\"\n\
1838 override = true\ncommand = [\"true\"]\n",
1839 );
1840 let loaded = load(&[dir], &["shadow".into()]);
1841 let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1842 assert!(problems.is_empty(), "{problems:?}");
1843 assert_eq!(tools.len(), 1);
1844 }
1845
1846 #[test]
1847 fn a_tool_without_a_command_or_with_mcp_is_rejected_with_a_reason() {
1848 let tmp = tempfile::tempdir().unwrap();
1849 let dir = tmp.path().join("plugins");
1850 write(
1851 &dir.join("broken"),
1852 "plugin.toml",
1853 "name = \"broken\"\n\
1854 [[tool]]\nname = \"no_cmd\"\ndescription = \"x\"\n\
1855 [[tool]]\nname = \"via_mcp\"\ndescription = \"x\"\nkind = \"mcp\"\n\
1856 command = [\"x\"]\n",
1857 );
1858 let loaded = load(&[dir], &["broken".into()]);
1859 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
1860 assert!(tools.is_empty());
1861 assert_eq!(problems.len(), 2, "{problems:?}");
1862 assert!(problems[0].contains("no `command`"), "{problems:?}");
1863 assert!(
1864 problems[1].contains("belongs on a `[[mcp]]` section"),
1865 "{problems:?}"
1866 );
1867 }
1868
1869 const MCP_FIXTURE: &str = r#"#!/usr/bin/env python3
1872import json, sys
1873
1874def send(obj):
1875 sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
1876
1877for line in sys.stdin:
1878 if not line.strip():
1879 continue
1880 msg = json.loads(line)
1881 mid, method = msg.get("id"), msg.get("method")
1882 params = msg.get("params") or {}
1883 if method == "initialize":
1884 send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
1885 "capabilities": {"tools": {}}, "serverInfo": {"name": "fixture", "version": "0"}}})
1886 elif method == "notifications/initialized":
1887 pass
1888 elif method == "tools/list":
1889 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1890 {"name": "read_text_file", "description": "Read a file",
1891 "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}},
1892 {"name": "write_text_file", "description": "Write a file"}]}})
1893 elif method == "tools/call":
1894 send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
1895 {"type": "text", "text": "called " + str(params.get("name"))}]}})
1896 elif mid is not None:
1897 send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no"}})
1898"#;
1899
1900 fn mcp_plugin(tmp: &Path, extra: &str) -> PathBuf {
1901 let dir = tmp.join("plugins");
1902 let script = dir.join("fs").join("server.py");
1903 std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1904 std::fs::write(&script, MCP_FIXTURE).unwrap();
1905 let manifest = format!(
1906 "name = \"fs\"\n\n[[mcp]]\nname = \"files\"\ncommand = \"python3\"\n\
1907 args = [\"{}\"]\ncwd = \"plugin\"\ntimeout_secs = 15\n{extra}\n",
1908 script.display()
1909 );
1910 write(&dir.join("fs"), "plugin.toml", &manifest);
1911 dir
1912 }
1913
1914 #[test]
1915 fn mcp_off_starts_no_server_at_all() {
1916 let tmp = tempfile::tempdir().unwrap();
1917 let dir = tmp.path().join("plugins");
1918 let marker = tmp.path().join("spawned");
1920 let script = dir.join("loud").join("server.sh");
1921 std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1922 std::fs::write(&script, format!("#!/bin/sh\ntouch {}\n", marker.display())).unwrap();
1923 write(
1924 &dir.join("loud"),
1925 "plugin.toml",
1926 &format!(
1927 "name = \"loud\"\n\n[[mcp]]\nname = \"loud\"\ncommand = \"/bin/sh\"\n\
1928 args = [\"{}\"]\n",
1929 script.display()
1930 ),
1931 );
1932
1933 let on = load(std::slice::from_ref(&dir), &["loud".into()]);
1936 let (_tools, problems) = on.tools(tmp.path(), 4096, &[]);
1937 assert!(
1938 !problems.is_empty(),
1939 "a bad server is reported when MCP is on"
1940 );
1941 assert!(
1942 marker.exists(),
1943 "when MCP is on, the server process really ran"
1944 );
1945
1946 std::fs::remove_file(&marker).unwrap();
1948 let off = load(&[dir], &["loud".into()]).with_mcp(McpSettings(None));
1949 let (tools, problems) = off.tools(tmp.path(), 4096, &[]);
1950 assert!(
1951 tools.is_empty(),
1952 "no tools from a server that was never asked"
1953 );
1954 assert!(
1955 problems.is_empty(),
1956 "nothing to complain about when nothing ran: {problems:?}"
1957 );
1958 assert!(
1959 !marker.exists(),
1960 "with MCP off, no server process was spawned"
1961 );
1962
1963 assert_eq!(
1966 mcp_timeout(&crate::config::Config::default()),
1967 DEFAULT_TIMEOUT
1968 );
1969 let mut cfg = crate::config::Config::default();
1970 cfg.plugins.mcp_timeout_secs = Some(5);
1971 assert_eq!(mcp_timeout(&cfg), Duration::from_secs(5));
1972 }
1973
1974 #[test]
1975 fn an_mcp_server_contributes_its_tools_with_their_own_source_and_policies() {
1976 if std::process::Command::new("python3")
1977 .arg("--version")
1978 .output()
1979 .map(|o| !o.status.success())
1980 .unwrap_or(true)
1981 {
1982 return;
1983 }
1984 let tmp = tempfile::tempdir().unwrap();
1985 let dir = mcp_plugin(tmp.path(), "policies = { read_text_file = \"allow\" }");
1986 let loaded = load(&[dir], &["fs".into()]);
1987 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1988 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
1989 assert!(problems.is_empty(), "{problems:?}");
1990 let names: Vec<&str> = tools.iter().map(|t| t.tool.name()).collect();
1991 assert_eq!(names, ["read_text_file", "write_text_file"]);
1992 for t in &tools {
1994 assert_eq!(t.source.label(), "plugin:mcp:files", "{}", t.tool.name());
1995 }
1996 let read = tools
1998 .iter()
1999 .find(|t| t.tool.name() == "read_text_file")
2000 .unwrap();
2001 let write = tools
2002 .iter()
2003 .find(|t| t.tool.name() == "write_text_file")
2004 .unwrap();
2005 assert_eq!(read.policy, Policy::Allow);
2006 assert_eq!(write.policy, Policy::Ask);
2007 assert_eq!(
2009 read.tool.parameters()["properties"]["path"]["type"],
2010 "string"
2011 );
2012 let out = tokio::runtime::Builder::new_current_thread()
2014 .enable_all()
2015 .build()
2016 .unwrap()
2017 .block_on(read.tool.call(json!({"path": "a.txt"})))
2018 .unwrap();
2019 assert_eq!(out, "called read_text_file");
2020
2021 let (again, _) = loaded.tools(tmp.path(), 4096, &[]);
2024 assert_eq!(again.len(), 2);
2025 let out = tokio::runtime::Builder::new_current_thread()
2026 .enable_all()
2027 .build()
2028 .unwrap()
2029 .block_on(again[0].tool.call(json!({"path": "b.txt"})))
2030 .unwrap();
2031 assert_eq!(out, "called read_text_file");
2032 }
2033
2034 #[test]
2035 fn a_server_tool_that_collides_is_refused_unless_the_entry_says_override() {
2036 if std::process::Command::new("python3")
2037 .arg("--version")
2038 .output()
2039 .map(|o| !o.status.success())
2040 .unwrap_or(true)
2041 {
2042 return;
2043 }
2044 let tmp = tempfile::tempdir().unwrap();
2045 let dir = mcp_plugin(tmp.path(), "");
2046 let loaded = load(&[dir], &["fs".into()]);
2047 let builtin = vec!["read_text_file".to_string()];
2050 let (tools, problems) = loaded.tools(tmp.path(), 4096, &builtin);
2051 assert_eq!(tools.len(), 1, "the other one still loads");
2052 assert_eq!(tools[0].tool.name(), "write_text_file");
2053 assert!(
2054 problems[0].contains("collides") && problems[0].contains("override = true"),
2055 "{problems:?}"
2056 );
2057 }
2058
2059 #[test]
2060 fn a_server_that_will_not_start_is_one_problem_and_no_tools() {
2061 let tmp = tempfile::tempdir().unwrap();
2062 let dir = tmp.path().join("plugins");
2063 write(
2064 &dir.join("dead"),
2065 "plugin.toml",
2066 "name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
2067 );
2068 let loaded = load(&[dir], &["dead".into()]);
2069 assert!(loaded.problems.is_empty(), "the manifest itself is fine");
2070 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2071 assert!(tools.is_empty());
2072 assert!(
2073 problems[0].contains("could not start") && problems[0].contains("gone"),
2074 "{problems:?}"
2075 );
2076 }
2077
2078 #[test]
2079 fn inline_parameters_and_a_schema_file_both_work() {
2080 let tmp = tempfile::tempdir().unwrap();
2081 let dir = tmp.path().join("plugins");
2082 write(
2083 &dir.join("p"),
2084 "plugin.toml",
2085 "name = \"p\"\n\
2086 [[tool]]\nname = \"inline\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2087 parameters = { type = \"object\", properties = { n = { type = \"string\" } } }\n\
2088 [[tool]]\nname = \"from_file\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2089 parameters = \"tools/from_file.json\"\n",
2090 );
2091 write(
2092 &dir.join("p"),
2093 "tools/from_file.json",
2094 "{\"type\":\"object\",\"properties\":{\"n\":{\"type\":\"integer\"}}}",
2095 );
2096 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2097 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2098 assert!(problems.is_empty(), "{problems:?}");
2099 assert_eq!(
2100 tools[0].tool.parameters()["properties"]["n"]["type"],
2101 "string"
2102 );
2103 assert_eq!(
2104 tools[1].tool.parameters()["properties"]["n"]["type"],
2105 "integer"
2106 );
2107
2108 std::fs::remove_file(dir.join("p/tools/from_file.json")).unwrap();
2109 let loaded = load(&[dir], &["p".into()]);
2110 let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2111 assert_eq!(tools.len(), 1);
2112 assert!(problems[0].contains("from_file.json"), "{problems:?}");
2113 }
2114
2115 #[cfg(unix)]
2116 #[tokio::test]
2117 async fn a_command_tool_gets_json_on_stdin_and_returns_stdout() {
2118 let tmp = tempfile::tempdir().unwrap();
2119 let dir = tmp.path().join("plugins");
2120 write(
2121 &dir.join("echoer"),
2122 "plugin.toml",
2123 "name = \"echoer\"\n[[tool]]\nname = \"echo_args\"\n\
2124 description = \"Echo the JSON it was given\"\n\
2125 command = [\"sh\", \"-c\", \"cat\"]\npolicy = \"allow\"\n",
2126 );
2127 let loaded = load(&[dir], &["echoer".into()]);
2128 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2129 let out = tools[0]
2130 .tool
2131 .call(json!({"path": "a.txt"}))
2132 .await
2133 .expect("tool should succeed");
2134 let sent: Value = serde_json::from_str(&out).unwrap();
2135 assert_eq!(sent["arguments"]["path"], "a.txt");
2136 assert_eq!(sent["tool"], "echo_args");
2137 }
2138
2139 #[cfg(unix)]
2140 #[tokio::test]
2141 async fn a_non_zero_exit_is_an_error_that_carries_both_streams() {
2142 let tmp = tempfile::tempdir().unwrap();
2143 let dir = tmp.path().join("plugins");
2144 write(
2145 &dir.join("fail"),
2146 "plugin.toml",
2147 "name = \"fail\"\n[[tool]]\nname = \"boom\"\ndescription = \"x\"\n\
2148 command = [\"sh\", \"-c\", \"echo out; echo bad >&2; exit 3\"]\npolicy = \"allow\"\n",
2149 );
2150 let loaded = load(&[dir], &["fail".into()]);
2151 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2152 let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2153 assert!(err.contains("exit code 3"), "{err}");
2154 assert!(err.contains("out") && err.contains("bad"), "{err}");
2155 }
2156
2157 #[cfg(unix)]
2158 #[tokio::test]
2159 async fn the_command_runs_in_the_workspace_and_only_sees_the_allowed_environment() {
2160 let tmp = tempfile::tempdir().unwrap();
2161 let (dir, ws) = (tmp.path().join("plugins"), tmp.path().join("ws"));
2162 std::fs::create_dir_all(&ws).unwrap();
2163 std::env::set_var("PLUGIN_TEST_SECRET", "leak-me");
2164 std::env::set_var("PLUGIN_TEST_ALLOWED", "ok");
2165 write(
2166 &dir.join("env"),
2167 "plugin.toml",
2168 "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2169 command = [\"sh\", \"-c\", \"pwd; echo secret=[${PLUGIN_TEST_SECRET:-}]; \
2170 echo allowed=[${PLUGIN_TEST_ALLOWED:-}]\"]\n\
2171 env = [\"PLUGIN_TEST_ALLOWED\"]\npolicy = \"allow\"\n",
2172 );
2173 let loaded = load(&[dir], &["env".into()]);
2174 let (tools, _) = loaded.tools(&ws, 4096, &[]);
2175 let out = tools[0].tool.call(json!({})).await.unwrap();
2176 let canonical = std::fs::canonicalize(&ws).unwrap();
2177 assert!(out.contains(&canonical.display().to_string()), "{out}");
2178 assert!(
2179 out.contains("secret=[]"),
2180 "the agent environment must not leak: {out}"
2181 );
2182 assert!(out.contains("allowed=[ok]"), "{out}");
2183 std::env::remove_var("PLUGIN_TEST_SECRET");
2184 std::env::remove_var("PLUGIN_TEST_ALLOWED");
2185 }
2186
2187 #[cfg(unix)]
2188 #[tokio::test]
2189 async fn a_plugin_tool_is_told_where_the_scripts_are_and_its_path_is_left_alone() {
2190 let tmp = tempfile::tempdir().unwrap();
2191 let dir = tmp.path().join("plugins");
2192 let scripts = tmp.path().join("scripts");
2193 write(
2194 &dir.join("env"),
2195 "plugin.toml",
2196 "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2197 command = [\"sh\", \"-c\", \"echo scripts=[${ECLIPSE_SCRIPTS_DIR:-}]; echo path=[$PATH]\"]\n\
2198 policy = \"allow\"\n",
2199 );
2200 let with = load(std::slice::from_ref(&dir), &["env".into()])
2201 .with_scripts_dir(Some(scripts.clone()));
2202 let (tools, _) = with.tools(tmp.path(), 4096, &[]);
2203 let out = tools[0].tool.call(json!({})).await.unwrap();
2204 assert!(
2205 out.contains(&format!("scripts=[{}]", scripts.display())),
2206 "{out}"
2207 );
2208 let path_line = out.lines().find(|l| l.starts_with("path=")).unwrap();
2209 assert!(
2210 !path_line.contains(&scripts.display().to_string()),
2211 "a plugin's PATH must not gain the scripts directory: {out}"
2212 );
2213
2214 let without = load(&[dir], &["env".into()]);
2215 let (tools, _) = without.tools(tmp.path(), 4096, &[]);
2216 let out = tools[0].tool.call(json!({})).await.unwrap();
2217 assert!(out.contains("scripts=[]"), "{out}");
2218 }
2219
2220 #[cfg(unix)]
2221 #[tokio::test]
2222 async fn a_hook_process_is_told_where_the_scripts_are_too() {
2223 let tmp = tempfile::tempdir().unwrap();
2224 let dir = tmp.path().join("plugins");
2225 write(
2226 &dir.join("guard"),
2227 "plugin.toml",
2228 "name = \"guard\"\n\
2229 [[hook]]\nevent = \"before_tool\"\n\
2230 command = [\"sh\", \"-c\", \"echo $ECLIPSE_SCRIPTS_DIR >&2; exit 2\"]\n",
2231 );
2232 let loaded = load(&[dir], &["guard".into()])
2233 .with_scripts_dir(Some(PathBuf::from("/somewhere/scripts")));
2234 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2235 match hooks.before("shell", &json!({}), None).await {
2236 Verdict::Deny(why) => assert_eq!(why, "/somewhere/scripts"),
2237 Verdict::Allow => panic!("the hook should have refused"),
2238 }
2239 }
2240
2241 #[cfg(unix)]
2242 #[tokio::test]
2243 async fn a_slow_tool_times_out() {
2244 let tmp = tempfile::tempdir().unwrap();
2245 let dir = tmp.path().join("plugins");
2246 write(
2247 &dir.join("slow"),
2248 "plugin.toml",
2249 "name = \"slow\"\n[[tool]]\nname = \"wait\"\ndescription = \"x\"\n\
2250 command = [\"sleep\", \"30\"]\ntimeout_secs = 1\npolicy = \"allow\"\n",
2251 );
2252 let loaded = load(&[dir], &["slow".into()]);
2253 let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2254 let started = std::time::Instant::now();
2255 let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2256 assert!(err.contains("timed out after 1s"), "{err}");
2257 assert!(started.elapsed() < Duration::from_secs(10));
2258 }
2259
2260 #[test]
2261 fn prompt_fragments_are_read_in_order_and_a_broken_one_is_a_problem() {
2262 let tmp = tempfile::tempdir().unwrap();
2263 let dir = tmp.path().join("plugins");
2264 write(
2265 &dir.join("p"),
2266 "plugin.toml",
2267 "name = \"p\"\n\
2268 [[prompt]]\ntext = \"first\"\n\
2269 [[prompt]]\nfile = \"prompts/second.md\"\n",
2270 );
2271 write(&dir.join("p"), "prompts/second.md", "second");
2272 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2273 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2274 assert_eq!(loaded.prompts(), ["first", "second"]);
2275
2276 std::fs::remove_file(dir.join("p/prompts/second.md")).unwrap();
2277 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2278 assert_eq!(loaded.prompts(), ["first"]);
2279 assert!(
2280 loaded.problems[0].contains("prompt file"),
2281 "{:?}",
2282 loaded.problems
2283 );
2284
2285 write(
2286 &dir.join("p"),
2287 "plugin.toml",
2288 "name = \"p\"\n[[prompt]]\ntext = \"x\"\nfile = \"y\"\n",
2289 );
2290 let loaded = load(&[dir], &["p".into()]);
2291 assert!(loaded.prompts().is_empty());
2292 assert!(
2293 loaded.problems[0].contains("either `text` or `file`"),
2294 "{:?}",
2295 loaded.problems
2296 );
2297 }
2298
2299 #[test]
2303 fn a_manifest_path_that_points_outside_the_plugin_is_refused() {
2304 let tmp = tempfile::tempdir().unwrap();
2305 let dir = tmp.path().join("plugins");
2306 let secret = dir.join("id_rsa");
2308 write(&dir, "id_rsa", "-----BEGIN OPENSSH PRIVATE KEY-----\n");
2309
2310 write(
2312 &dir.join("p"),
2313 "plugin.toml",
2314 "name = \"p\"\n[[prompt]]\nfile = \"../id_rsa\"\n",
2315 );
2316 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2317 assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2318 assert!(
2319 loaded
2320 .problems
2321 .iter()
2322 .any(|p| p.contains("outside the plugin")),
2323 "{:?}",
2324 loaded.problems
2325 );
2326
2327 write(
2328 &dir.join("p"),
2329 "plugin.toml",
2330 &format!("name = \"p\"\n[[prompt]]\nfile = {secret:?}\n"),
2331 );
2332 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2333 assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2334 assert!(
2335 loaded
2336 .problems
2337 .iter()
2338 .any(|p| p.contains("outside the plugin")),
2339 "{:?}",
2340 loaded.problems
2341 );
2342
2343 write(
2345 &dir.join("p"),
2346 "plugin.toml",
2347 "name = \"p\"\n[[tool]]\nname = \"leak\"\ndescription = \"x\"\n\
2348 command = [\"echo\"]\nparameters = \"../id_rsa\"\npolicy = \"allow\"\n",
2349 );
2350 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2351 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2352 assert!(tools.is_empty(), "no tool was built from the link");
2353 assert!(
2354 problems.iter().any(|p| p.contains("outside the plugin")),
2355 "{:?}",
2356 problems
2357 );
2358 }
2359
2360 #[test]
2364 fn a_manifest_path_inside_the_plugin_is_read_and_a_directory_is_refused() {
2365 let tmp = tempfile::tempdir().unwrap();
2366 let dir = tmp.path().join("plugins");
2367 write(
2368 &dir.join("p"),
2369 "plugin.toml",
2370 "name = \"p\"\n[[prompt]]\nfile = \"prompts/first.md\"\n",
2371 );
2372 write(&dir.join("p"), "prompts/first.md", "inside");
2373 let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2374 assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2375 assert_eq!(loaded.prompts(), ["inside"]);
2376
2377 std::fs::create_dir_all(dir.join("p/prompts/dir.md")).unwrap();
2378 write(
2379 &dir.join("p"),
2380 "plugin.toml",
2381 "name = \"p\"\n[[prompt]]\nfile = \"prompts/dir.md\"\n",
2382 );
2383 let loaded = load(&[dir], &["p".into()]);
2384 assert!(loaded.prompts().is_empty());
2385 assert!(
2386 loaded
2387 .problems
2388 .iter()
2389 .any(|p| p.contains("not a regular file")),
2390 "{:?}",
2391 loaded.problems
2392 );
2393 }
2394
2395 #[test]
2401 fn a_plugin_loaded_for_its_profiles_is_not_enabled_and_has_no_skills_root() {
2402 let tmp = tempfile::tempdir().unwrap();
2403 let dir = tmp.path().join("plugins");
2404 write(
2405 &dir.join("wire"),
2406 "plugin.toml",
2407 "name = \"wire\"\n\
2408 [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n",
2409 );
2410 write(
2412 &dir.join("wire/skills/sneaky/SKILL.md"),
2413 "SKILL.md",
2414 "---\nname: sneaky\ndescription: not yours\n---\n\nx\n",
2415 );
2416
2417 let loaded = load(std::slice::from_ref(&dir), &[]);
2418 assert_eq!(
2419 loaded.plugins.len(),
2420 1,
2421 "loaded for its profiles: {:?}",
2422 loaded.problems
2423 );
2424 assert!(
2425 !loaded.plugins[0].enabled,
2426 "loaded is not the same as enabled"
2427 );
2428 let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2429 assert!(
2430 !roots.iter().any(|r| r.dir.ends_with("wire/skills")),
2431 "an unenabled plugin's skills are not roots: {roots:?}"
2432 );
2433
2434 let loaded = load(&[dir], &["wire".into()]);
2436 assert!(loaded.plugins[0].enabled);
2437 let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2438 assert!(roots.iter().any(|r| r.dir.ends_with("wire/skills")));
2439 }
2440
2441 #[test]
2442 fn provider_profiles_override_by_name_and_keep_order() {
2443 let tmp = tempfile::tempdir().unwrap();
2444 let dir = tmp.path().join("plugins");
2445 write(
2446 &dir.join("prov"),
2447 "plugin.toml",
2448 "name = \"prov\"\n\
2449 [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n\
2450 [provider_profile.body]\nchat_template_kwargs = { enable_thinking = false }\n\
2451 [[provider_profile]]\nname = \"acme\"\nsupports_tools = false\n",
2452 );
2453 let loaded = load(&[dir], &["prov".into()]);
2454 let profiles = loaded.provider_profiles();
2455 assert_eq!(profiles.len(), 2);
2456 assert_eq!(profiles[0].name, "llamacpp");
2457 assert!(!profiles[0].tool_choice);
2458 assert_eq!(
2459 profiles[0].body["chat_template_kwargs"]["enable_thinking"],
2460 json!(false)
2461 );
2462 assert!(!profiles[1].supports_tools);
2463 }
2464
2465 #[cfg(unix)]
2466 #[tokio::test]
2467 async fn a_before_tool_hook_can_refuse_with_a_reason() {
2468 let tmp = tempfile::tempdir().unwrap();
2469 let dir = tmp.path().join("plugins");
2470 write(
2471 &dir.join("guard"),
2472 "plugin.toml",
2473 "name = \"guard\"\n\
2474 [[hook]]\nevent = \"before_tool\"\ntool = \"shell\"\n\
2475 command = [\"sh\", \"-c\", \"echo 'no shell in this repo' >&2; exit 2\"]\n",
2476 );
2477 let loaded = load(&[dir], &["guard".into()]);
2478 assert_eq!(loaded.hooks().len(), 1);
2479 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2480 match hooks.before("shell", &json!({"command": "ls"}), None).await {
2481 Verdict::Deny(why) => assert_eq!(why, "no shell in this repo"),
2482 Verdict::Allow => panic!("the hook should have refused"),
2483 }
2484 assert!(matches!(
2485 hooks.before("read_file", &json!({}), None).await,
2486 Verdict::Allow
2487 ));
2488 }
2489
2490 #[cfg(unix)]
2491 #[tokio::test]
2492 async fn a_guard_that_cannot_run_refuses_rather_than_allowing() {
2493 let tmp = tempfile::tempdir().unwrap();
2494 let dir = tmp.path().join("plugins");
2495 write(
2496 &dir.join("broken-guard"),
2497 "plugin.toml",
2498 "name = \"broken-guard\"\n\
2499 [[hook]]\nevent = \"before_tool\"\ncommand = [\"./missing.sh\"]\ncwd = \"plugin\"\n",
2500 );
2501 let loaded = load(&[dir], &["broken-guard".into()]);
2502 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2503 match hooks.before("anything", &json!({}), None).await {
2504 Verdict::Deny(why) => assert!(why.contains("could not run"), "{why}"),
2505 Verdict::Allow => panic!("a guard that cannot run must not silently allow"),
2506 }
2507 }
2508
2509 #[cfg(unix)]
2510 #[tokio::test]
2511 async fn an_after_tool_hook_can_rewrite_the_output() {
2512 let tmp = tempfile::tempdir().unwrap();
2513 let dir = tmp.path().join("plugins");
2514 write(
2517 &dir.join("redact"),
2518 "plugin.toml",
2519 "name = \"redact\"\n\
2520 [[hook]]\nevent = \"after_tool\"\n\
2521 command = [\"sh\", \"-c\", \"printf 'the [redacted] is here'\"]\n",
2522 );
2523 let loaded = load(std::slice::from_ref(&dir), &["redact".into()]);
2524 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2525 let out = hooks
2526 .after(
2527 "read_file",
2528 &json!({}),
2529 ToolOutcome {
2530 output: "the secret is here".into(),
2531 is_error: false,
2532 malformed: false,
2533 deferred: false,
2534 },
2535 None,
2536 )
2537 .await;
2538 assert_eq!(out.output, "the [redacted] is here");
2539 assert!(!out.is_error);
2540
2541 write(
2543 &dir.join("quiet"),
2544 "plugin.toml",
2545 "name = \"quiet\"\n\
2546 [[hook]]\nevent = \"after_tool\"\ncommand = [\"true\"]\n",
2547 );
2548 let quiet = load(&[dir], &["quiet".into()]);
2549 let hooks = Hooks::new(quiet.hooks(), PathBuf::from("/tmp"), "default");
2550 let out = hooks
2551 .after(
2552 "read_file",
2553 &json!({}),
2554 ToolOutcome {
2555 output: "unchanged".into(),
2556 is_error: true,
2557 malformed: false,
2558 deferred: false,
2559 },
2560 None,
2561 )
2562 .await;
2563 assert_eq!(out.output, "unchanged");
2564 assert!(out.is_error);
2565 }
2566
2567 #[test]
2568 fn the_shipped_examples_all_load() {
2569 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/plugins");
2571 if !root.is_dir() {
2572 return;
2573 }
2574 let names: Vec<String> = discover_all(std::slice::from_ref(&root))
2575 .into_iter()
2576 .map(|(name, _)| name)
2577 .collect();
2578 assert!(!names.is_empty(), "no examples found in {}", root.display());
2579 let loaded = load(std::slice::from_ref(&root), &names);
2580 assert!(
2581 loaded.problems.is_empty(),
2582 "the shipped examples must load cleanly: {:?}",
2583 loaded.problems
2584 );
2585 let (tools, problems) = loaded.tools(&root, 4096, &[]);
2586 assert!(problems.is_empty(), "{problems:?}");
2587 assert_eq!(tools.len(), 3, "git_status, git_diff, git_log");
2588 assert_eq!(loaded.provider_profiles().len(), 1);
2589 assert_eq!(loaded.hooks().len(), 1);
2590 assert!(!loaded.prompts().is_empty());
2591 }
2592
2593 #[test]
2594 fn discover_all_lists_manifests_whether_enabled_or_not() {
2595 let tmp = tempfile::tempdir().unwrap();
2596 let dir = tmp.path().join("plugins");
2597 manifest(&dir.join("a"), "a");
2598 manifest(&dir.join("b"), "b");
2599 std::fs::create_dir_all(dir.join("not-a-plugin")).unwrap();
2600 let found = discover_all(&[dir]);
2601 assert_eq!(found.len(), 2);
2602 }
2603
2604 #[cfg(unix)]
2605 #[tokio::test]
2606 async fn a_hook_payload_names_the_tool_call_it_is_about() {
2607 let tmp = tempfile::tempdir().unwrap();
2610 let dir = tmp.path().join("plugins");
2611 write(
2612 &dir.join("echo-payload"),
2613 "plugin.toml",
2614 "name = \"echo-payload\"\n\
2615 [[hook]]\nevent = \"after_tool\"\ncommand = [\"sh\", \"-c\", \"cat\"]\n",
2616 );
2617 let loaded = load(&[dir], &["echo-payload".into()]);
2618 let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2619 let outcome = || ToolOutcome {
2620 output: "x".into(),
2621 is_error: false,
2622 malformed: false,
2623 deferred: false,
2624 };
2625 let named = hooks
2626 .after("read_file", &json!({}), outcome(), Some("c7"))
2627 .await;
2628 assert!(
2629 named.output.contains("\"call_id\":\"c7\""),
2630 "a hook must be able to tell concurrent calls apart: {}",
2631 named.output
2632 );
2633 let unnamed = hooks.after("read_file", &json!({}), outcome(), None).await;
2635 assert!(
2636 unnamed.output.contains("\"call_id\":null"),
2637 "{}",
2638 unnamed.output
2639 );
2640 }
2641}
2642
2643#[cfg(test)]
2644mod size_cap_tests {
2645 use super::*;
2646
2647 fn write(dir: &Path, rel: &str, text: &str) {
2648 let p = dir.join(rel);
2649 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
2650 std::fs::write(p, text).unwrap();
2651 }
2652
2653 #[test]
2656 fn an_oversized_prompt_file_is_cut_and_says_so() {
2657 let tmp = tempfile::tempdir().unwrap();
2658 let dir = tmp.path().join("plugins");
2659 write(
2660 &dir.join("longprompt"),
2661 "plugin.toml",
2662 "name = \"longprompt\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2663 [[prompt]]\nfile = \"prompts/rules.md\"\n",
2664 );
2665 let line = "keep the answer short and cite the file. ";
2667 let body = line.repeat((MAX_MANIFEST_FILE_BYTES as usize / line.len()) + 10);
2668 write(&dir.join("longprompt"), "prompts/rules.md", &body);
2669
2670 let loaded = load(&[dir], &["longprompt".into()]);
2671 assert!(
2672 loaded
2673 .problems
2674 .iter()
2675 .any(|p| p.contains("truncated") && p.contains("rules.md")),
2676 "the truncation is reported to the human: {:?}",
2677 loaded.problems
2678 );
2679 let text = loaded.plugins[0].manifest.prompts[0]
2680 .text
2681 .as_deref()
2682 .expect("the prompt resolves");
2683 assert!(
2684 text.len() <= MAX_MANIFEST_FILE_BYTES as usize + 128,
2685 "the prompt is capped, not passed through: {} bytes",
2686 text.len()
2687 );
2688 assert!(
2689 text.ends_with("bytes)"),
2690 "and the model is told the text is incomplete: …{}",
2691 &text[text.len().saturating_sub(80)..]
2692 );
2693 assert!(
2694 text.contains(line.trim()),
2695 "the part that arrived is the real text, not a placeholder"
2696 );
2697 }
2698
2699 #[test]
2702 fn an_oversized_parameters_file_is_refused_not_truncated() {
2703 let tmp = tempfile::tempdir().unwrap();
2704 let dir = tmp.path().join("plugins");
2705 write(
2706 &dir.join("paramtool"),
2707 "plugin.toml",
2708 "name = \"paramtool\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2709 [[tool]]\nname = \"thing\"\ndescription = \"A thing\"\n\
2710 command = [\"sh\", \"-c\", \"echo hi\"]\npolicy = \"allow\"\n\
2711 parameters = \"params.json\"\n",
2712 );
2713 let filler = "x".repeat(MAX_MANIFEST_FILE_BYTES as usize + 1);
2714 write(
2715 &dir.join("paramtool"),
2716 "params.json",
2717 &format!("{{\"type\":\"object\",\"description\":\"{filler}\"}}"),
2718 );
2719
2720 let loaded = load(&[dir], &["paramtool".into()]);
2721 let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2722 assert!(
2723 problems
2724 .iter()
2725 .any(|p| p.contains("limit is") && p.contains("params.json")),
2726 "the refusal names the file and both sizes: {problems:?}"
2727 );
2728 assert!(
2729 tools.is_empty(),
2730 "the tool is not loaded with parameters nobody could read"
2731 );
2732 }
2733}