返回 CodeWhale
tools_mcp.rs
根目录 / crates / tui / src / tui / setup / tools_mcp.rs
1 //! Tools / MCP / skills / plugins setup inventory (#3407).
2 //!
3 //! Read-only discovery surface for the setup wizard. Classifies each surface as
4 //! `healthy` / `needs_config` / `off`, redacts secrets, and never spawns MCP
5 //! servers, installs skills, or runs plugins. Side-effectful bootstrap stays
6 //! behind explicit CLI/TUI commands listed in the on-ramp.
7
8 use std::path::{Path, PathBuf};
9
10 use crate::tui::app::App;
11 use crate::tui::hotbar::actions::HotbarActionCategory;
12 use codewhale_engine::mcp::{
13 McpCommandAvailability, McpManagerSnapshot, McpServerSnapshot, static_mcp_command_availability,
14 };
15 use codewhale_localization::{Locale, MessageId, tr};
16 use codewhale_mcp::config::{McpConfig, McpServerConfig};
17 use codewhale_runtime::config::Config;
18 use codewhale_util::utils::display_path;
19
20 /// Per-surface readiness vocabulary shared with setup summaries and doctor-like
21 /// copy. These never block first-run; they only describe optional power tools.
22 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
23 pub(super) enum InventoryStatus {
24 /// Configured and statically sound (or live-connected when a snapshot exists).
25 Healthy,
26 /// Present but incomplete/broken — needs user action outside first-run.
27 NeedsConfig,
28 /// Disabled or not configured. Friendly empty state, not an error.
29 Off,
30 }
31
32 impl InventoryStatus {
33 pub(super) fn as_str(self) -> &'static str {
34 match self {
35 Self::Healthy => "healthy",
36 Self::NeedsConfig => "needs_config",
37 Self::Off => "off",
38 }
39 }
40
41 fn rank(self) -> u8 {
42 match self {
43 Self::Off => 0,
44 Self::Healthy => 1,
45 Self::NeedsConfig => 2,
46 }
47 }
48
49 fn worse(self, other: Self) -> Self {
50 if other.rank() > self.rank() {
51 other
52 } else {
53 self
54 }
55 }
56 }
57
58 #[derive(Debug, Clone, PartialEq, Eq)]
59 struct InventoryRow {
60 status: InventoryStatus,
61 detail: String,
62 }
63
64 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
65 enum McpInventoryScope {
66 Configuration,
67 Protocol,
68 }
69
70 #[derive(Debug, Clone, PartialEq, Eq)]
71 struct McpInventoryRow {
72 status: InventoryStatus,
73 detail: String,
74 scope: McpInventoryScope,
75 }
76
77 impl McpInventoryRow {
78 fn status_label(&self) -> &'static str {
79 match (self.status, self.scope) {
80 (InventoryStatus::Healthy, McpInventoryScope::Configuration) => "configured",
81 (InventoryStatus::Healthy, McpInventoryScope::Protocol) => "protocol_ready",
82 (status, _) => status.as_str(),
83 }
84 }
85 }
86
87 #[derive(Debug, Clone, PartialEq, Eq)]
88 pub(super) struct SetupToolsMcpFacts {
89 pub(super) servers_result: String,
90 pub(super) skills_result: String,
91 pub(super) tools_result: String,
92 pub(super) plugins_result: String,
93 pub(super) hotbar_result: String,
94 /// DeepSeek Harness (dsh) integration state; read-only probe.
95 pub(super) dsh_result: String,
96 pub(super) result: String,
97 pub(super) overall_status: InventoryStatus,
98 pub(super) needs_action: bool,
99 pub(super) mcp_path_display: String,
100 pub(super) skills_path_display: String,
101 pub(super) plugins_path_display: String,
102 }
103
104 impl Default for SetupToolsMcpFacts {
105 fn default() -> Self {
106 Self {
107 servers_result: "MCP config not loaded".to_string(),
108 skills_result: "skills dir not loaded".to_string(),
109 tools_result: "tools dir not loaded".to_string(),
110 plugins_result: "plugins dir not loaded".to_string(),
111 hotbar_result: "hotbar source metadata not loaded".to_string(),
112 dsh_result: "DeepSeek Harness not probed".to_string(),
113 result: "tools/MCP not loaded".to_string(),
114 overall_status: InventoryStatus::Off,
115 needs_action: false,
116 mcp_path_display: String::new(),
117 skills_path_display: String::new(),
118 plugins_path_display: String::new(),
119 }
120 }
121 }
122
123 pub(super) struct ToolsMcpProbeInput {
124 pub(super) workspace: PathBuf,
125 mcp_config_path: PathBuf,
126 mcp_snapshot: Option<McpManagerSnapshot>,
127 pub(super) plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>,
128 skills_dir: PathBuf,
129 discovered_skills: usize,
130 hotbar: InventoryRow,
131 pub(super) config: Config,
132 pub(super) codewhale_home: PathBuf,
133 }
134
135 impl ToolsMcpProbeInput {
136 /// Snapshot in-memory `App`/`Config` fields with no filesystem IO so the
137 /// directory scans can run on Tokio's blocking pool.
138 pub(super) fn from_app_config(app: &App, config: &Config, codewhale_home: PathBuf) -> Self {
139 Self {
140 workspace: app.workspace.clone(),
141 mcp_config_path: app.mcp_config_path.clone(),
142 mcp_snapshot: app.mcp_snapshot.clone(),
143 plugin_registry: std::sync::Arc::clone(&app.plugin_registry),
144 skills_dir: app.skills_dir.clone(),
145 discovered_skills: app.cached_skills.len(),
146 hotbar: hotbar_source_inventory(app),
147 config: config.clone(),
148 codewhale_home,
149 }
150 }
151 }
152
153 impl SetupToolsMcpFacts {
154 #[cfg(test)]
155 pub(super) fn from_app_config(app: &App, config: &Config, codewhale_home: &Path) -> Self {
156 let input = ToolsMcpProbeInput::from_app_config(app, config, codewhale_home.to_path_buf());
157 Self::from_probe_input(&input)
158 }
159
160 pub(super) fn from_probe_input(input: &ToolsMcpProbeInput) -> Self {
161 let project_mcp_path = codewhale_engine::mcp::workspace_mcp_config_path(&input.workspace);
162 let mcp = mcp_inventory(input, &project_mcp_path);
163 let skills = skills_inventory(&input.skills_dir, input.discovered_skills);
164 let tools_dir = input.codewhale_home.join("tools");
165 let tools = tools_dir_inventory(&tools_dir);
166 let plugins = plugins_inventory(input);
167 let hotbar = &input.hotbar;
168
169 let overall = mcp
170 .status
171 .worse(skills.status)
172 .worse(tools.status)
173 .worse(plugins.status);
174 // Only configured-but-broken surfaces need action. Empty/off is fine.
175 let needs_action = matches!(mcp.status, InventoryStatus::NeedsConfig)
176 || matches!(skills.status, InventoryStatus::NeedsConfig)
177 || matches!(tools.status, InventoryStatus::NeedsConfig)
178 || matches!(plugins.status, InventoryStatus::NeedsConfig);
179
180 let mcp_path_display = display_path(&input.mcp_config_path);
181 let skills_path_display = display_path(&input.skills_dir);
182 let plugins_path_display = display_path(&plugins_dir_for(&input.codewhale_home));
183
184 let servers_result = format!("{} — {}", mcp.status_label(), mcp.detail);
185 let skills_result = format!("{} — {}", skills.status.as_str(), skills.detail);
186 let tools_result = format!("{} — {}", tools.status.as_str(), tools.detail);
187 let plugins_result = format!("{} — {}", plugins.status.as_str(), plugins.detail);
188 let hotbar_result = format!("{} — {}", hotbar.status.as_str(), hotbar.detail);
189 let dsh_result = dsh_integration_result(&input.config, &input.workspace);
190
191 let result = format!(
192 "mcp={}, skills={}, tools={}, plugins={}, hotbar_sources={}, overall={}, mode=read_only_safe_probe",
193 mcp.status_label(),
194 skills.status.as_str(),
195 tools.status.as_str(),
196 plugins.status.as_str(),
197 hotbar.detail,
198 overall.as_str(),
199 );
200
201 Self {
202 servers_result,
203 skills_result,
204 tools_result,
205 plugins_result,
206 hotbar_result,
207 dsh_result,
208 result,
209 overall_status: overall,
210 needs_action,
211 mcp_path_display,
212 skills_path_display,
213 plugins_path_display,
214 }
215 }
216 }
217
218 /// Side-effect-free DeepSeek Harness state for the on-ramp card. Detection
219 /// only runs `dsh --version`/`--help` and reads `$DSH_HOME` inventory; it
220 /// never writes or reads a credential value.
221 fn dsh_integration_result(config: &Config, workspace: &Path) -> String {
222 use crate::integrations::dsh;
223 let paths = match dsh::DshPaths::from_process() {
224 Ok(paths) => paths,
225 Err(error) => return format!("unavailable — {error}"),
226 };
227 let detection = dsh::detect::detect(&dsh::DetectEnv::from_process(), &dsh::ProcessRunner);
228 let identity = dsh::codewhale_route_identity(config, workspace);
229 match dsh::compute_status(
230 &paths,
231 detection,
232 identity,
233 false,
234 dsh::bundle_availability_now(),
235 ) {
236 Ok(report) => dsh::status_line(&report),
237 Err(error) => format!("unavailable — {error}"),
238 }
239 }
240
241 pub(super) fn on_ramp_text(locale: Locale, facts: &SetupToolsMcpFacts) -> String {
242 let base = tr(locale, MessageId::SetupToolsMcpOnRampText);
243 let dsh_row =
244 tr(locale, MessageId::SetupToolsMcpDshRow).replace("{dsh_result}", &facts.dsh_result);
245 let base = format!("{base}\n\n{dsh_row}");
246 base.replace("{mcp_result}", &facts.servers_result)
247 .replace("{skills_result}", &facts.skills_result)
248 .replace("{tools_result}", &facts.tools_result)
249 .replace("{plugins_result}", &facts.plugins_result)
250 .replace("{hotbar_result}", &facts.hotbar_result)
251 .replace("{mcp_path}", &facts.mcp_path_display)
252 .replace("{skills_path}", &facts.skills_path_display)
253 .replace("{plugins_path}", &facts.plugins_path_display)
254 }
255
256 fn mcp_inventory(input: &ToolsMcpProbeInput, project_mcp_path: &Path) -> McpInventoryRow {
257 if let Some(snapshot) = input.mcp_snapshot.as_ref() {
258 return mcp_snapshot_inventory(snapshot, &input.mcp_config_path, project_mcp_path);
259 }
260
261 match codewhale_engine::mcp::load_config_with_workspace_and_plugins(
262 &input.mcp_config_path,
263 &input.workspace,
264 input.plugin_registry.as_ref(),
265 ) {
266 Ok(cfg) => mcp_config_inventory(&input.mcp_config_path, project_mcp_path, &cfg),
267 Err(_) => McpInventoryRow {
268 status: InventoryStatus::NeedsConfig,
269 detail: format!(
270 "config unreadable at {} (and project {}); open /mcp or run `codewhale doctor` — secrets not shown",
271 display_path(&input.mcp_config_path),
272 display_path(project_mcp_path)
273 ),
274 scope: McpInventoryScope::Configuration,
275 },
276 }
277 }
278
279 fn mcp_path_presence(global: &Path, project: &Path) -> String {
280 let global_state = if global.exists() {
281 "global present"
282 } else {
283 "global missing"
284 };
285 let project_state = if project.exists() {
286 "project present"
287 } else {
288 "project missing"
289 };
290 format!(
291 "{global_state} at {}; {project_state} at {}",
292 display_path(global),
293 display_path(project)
294 )
295 }
296
297 fn mcp_snapshot_inventory(
298 snapshot: &McpManagerSnapshot,
299 global_path: &Path,
300 project_path: &Path,
301 ) -> McpInventoryRow {
302 let total = snapshot.servers.len();
303 let paths = mcp_path_presence(global_path, project_path);
304 if total == 0 {
305 return McpInventoryRow {
306 status: InventoryStatus::Off,
307 detail: format!(
308 "nothing configured yet ({paths}); optional — use /mcp or `codewhale mcp init` later"
309 ),
310 scope: McpInventoryScope::Protocol,
311 };
312 }
313
314 let mut protocol_ready = 0usize;
315 let mut needs_config = 0usize;
316 let mut off = 0usize;
317 let mut names_ok: Vec<&str> = Vec::new();
318 let mut names_bad: Vec<&str> = Vec::new();
319 let mut names_off: Vec<&str> = Vec::new();
320
321 for server in &snapshot.servers {
322 match classify_snapshot_server(server) {
323 InventoryStatus::Healthy => {
324 protocol_ready += 1;
325 if names_ok.len() < 4 {
326 names_ok.push(server.name.as_str());
327 }
328 }
329 InventoryStatus::NeedsConfig => {
330 needs_config += 1;
331 if names_bad.len() < 4 {
332 names_bad.push(server.name.as_str());
333 }
334 }
335 InventoryStatus::Off => {
336 off += 1;
337 if names_off.len() < 4 {
338 names_off.push(server.name.as_str());
339 }
340 }
341 }
342 }
343
344 let status = if needs_config > 0 {
345 InventoryStatus::NeedsConfig
346 } else if protocol_ready > 0 {
347 InventoryStatus::Healthy
348 } else {
349 InventoryStatus::Off
350 };
351
352 let mut detail = format!(
353 "{total} configured ({protocol_ready} protocol_ready, {needs_config} needs_config, {off} off; {paths}); backend/tool health not checked"
354 );
355 if !names_ok.is_empty() {
356 detail.push_str(&format!("; protocol_ready: {}", names_ok.join(", ")));
357 }
358 if !names_bad.is_empty() {
359 detail.push_str(&format!("; needs_config: {}", names_bad.join(", ")));
360 }
361 if !names_off.is_empty() {
362 detail.push_str(&format!("; off: {}", names_off.join(", ")));
363 }
364 if snapshot.reload_required {
365 detail.push_str("; /mcp reload required for live tool list");
366 }
367 detail.push_str("; /mcp for details (commands/tokens never shown here)");
368 McpInventoryRow {
369 status,
370 detail,
371 scope: McpInventoryScope::Protocol,
372 }
373 }
374
375 fn classify_snapshot_server(server: &McpServerSnapshot) -> InventoryStatus {
376 if !server.enabled {
377 return InventoryStatus::Off;
378 }
379 if server.connected {
380 return InventoryStatus::Healthy;
381 }
382 match server.error.as_deref() {
383 None => InventoryStatus::Healthy,
384 Some("disabled") => InventoryStatus::Off,
385 Some(_) => InventoryStatus::NeedsConfig,
386 }
387 }
388
389 fn mcp_config_inventory(global: &Path, project: &Path, cfg: &McpConfig) -> McpInventoryRow {
390 let total = cfg.servers.len();
391 let paths = mcp_path_presence(global, project);
392 if total == 0 {
393 return McpInventoryRow {
394 status: InventoryStatus::Off,
395 detail: format!(
396 "nothing configured yet ({paths}); optional — use /mcp or `codewhale mcp init` later"
397 ),
398 scope: McpInventoryScope::Configuration,
399 };
400 }
401
402 let mut configured = 0usize;
403 let mut needs_config = 0usize;
404 let mut off = 0usize;
405 let mut names_ok: Vec<&str> = Vec::new();
406 let mut names_bad: Vec<&str> = Vec::new();
407 let mut names_off: Vec<&str> = Vec::new();
408
409 for (name, server) in &cfg.servers {
410 match classify_config_server(server) {
411 InventoryStatus::Healthy => {
412 configured += 1;
413 if names_ok.len() < 4 {
414 names_ok.push(name.as_str());
415 }
416 }
417 InventoryStatus::NeedsConfig => {
418 needs_config += 1;
419 if names_bad.len() < 4 {
420 names_bad.push(name.as_str());
421 }
422 }
423 InventoryStatus::Off => {
424 off += 1;
425 if names_off.len() < 4 {
426 names_off.push(name.as_str());
427 }
428 }
429 }
430 }
431
432 let status = if needs_config > 0 {
433 InventoryStatus::NeedsConfig
434 } else if configured > 0 {
435 InventoryStatus::Healthy
436 } else {
437 InventoryStatus::Off
438 };
439
440 let mut detail = format!(
441 "{total} configured ({configured} configuration valid, {needs_config} needs_config, {off} off; {paths}); live health not checked — servers not started"
442 );
443 if !names_ok.is_empty() {
444 detail.push_str(&format!("; configuration valid: {}", names_ok.join(", ")));
445 }
446 if !names_bad.is_empty() {
447 detail.push_str(&format!("; needs_config: {}", names_bad.join(", ")));
448 }
449 if !names_off.is_empty() {
450 detail.push_str(&format!("; off: {}", names_off.join(", ")));
451 }
452 detail.push_str("; /mcp or `codewhale doctor` for full checks");
453 McpInventoryRow {
454 status,
455 detail,
456 scope: McpInventoryScope::Configuration,
457 }
458 }
459
460 /// Safe static probe aligned with `doctor_check_mcp_server` without spawning.
461 fn classify_config_server(server: &McpServerConfig) -> InventoryStatus {
462 if !server.is_enabled() {
463 return InventoryStatus::Off;
464 }
465 if server.command.is_none() && server.url.is_none() {
466 return InventoryStatus::NeedsConfig;
467 }
468 if matches!(
469 static_mcp_command_availability(server),
470 Ok(McpCommandAvailability::Missing) | Ok(McpCommandAvailability::NotChecked) | Err(_)
471 ) {
472 return InventoryStatus::NeedsConfig;
473 }
474 // Env-backed bearer tokens: missing env is needs_config when URL-based.
475 if server.url.is_some()
476 && let Some(env_var) = server.bearer_token_env_var.as_deref()
477 && !env_var.is_empty()
478 && !codewhale_engine::mcp::mcp_secret_available(
479 server,
480 env_var,
481 &codewhale_runtime::credentials::context::ProcessAuthContext,
482 )
483 {
484 return InventoryStatus::NeedsConfig;
485 }
486 InventoryStatus::Healthy
487 }
488
489 fn skills_inventory(skills_dir: &Path, discovered: usize) -> InventoryRow {
490 let path = display_path(skills_dir);
491 let dir_exists = skills_dir.exists();
492 let dir_is_dir = skills_dir.is_dir();
493
494 if !dir_exists {
495 return InventoryRow {
496 status: InventoryStatus::Off,
497 detail: format!(
498 "nothing configured yet (missing at {path}); optional — /skills or `codewhale setup --skills`"
499 ),
500 };
501 }
502 if !dir_is_dir {
503 return InventoryRow {
504 status: InventoryStatus::NeedsConfig,
505 detail: format!("skills path exists but is not a directory at {path}"),
506 };
507 }
508
509 // Count on-disk SKILL.md entries without executing anything.
510 let on_disk = count_skill_dirs(skills_dir);
511 if discovered == 0 && on_disk == 0 {
512 return InventoryRow {
513 status: InventoryStatus::Off,
514 detail: format!(
515 "dir present at {path} with 0 skills; optional — install later via /skills install"
516 ),
517 };
518 }
519
520 InventoryRow {
521 status: InventoryStatus::Healthy,
522 detail: format!(
523 "{discovered} discovered (hotbar skill sources), {on_disk} on disk at {path}; /skills lists names and trust"
524 ),
525 }
526 }
527
528 fn tools_dir_inventory(tools_dir: &Path) -> InventoryRow {
529 let path = display_path(tools_dir);
530 if !tools_dir.exists() {
531 return InventoryRow {
532 status: InventoryStatus::Off,
533 detail: format!(
534 "nothing configured yet (missing at {path}); optional — `codewhale setup --tools`"
535 ),
536 };
537 }
538 if !tools_dir.is_dir() {
539 return InventoryRow {
540 status: InventoryStatus::NeedsConfig,
541 detail: format!("tools path exists but is not a directory at {path}"),
542 };
543 }
544 let script_plugins = codewhale_engine::tools::plugin::scan_plugin_dir(tools_dir).len();
545 let entries = count_dir_entries(tools_dir);
546 if entries == 0 {
547 return InventoryRow {
548 status: InventoryStatus::Off,
549 detail: format!("empty tools dir at {path}; optional"),
550 };
551 }
552 InventoryRow {
553 status: InventoryStatus::Healthy,
554 detail: format!(
555 "{entries} entries, {script_plugins} script-plugin tools at {path}; not executed during setup"
556 ),
557 }
558 }
559
560 fn plugins_inventory(input: &ToolsMcpProbeInput) -> InventoryRow {
561 let plugins_dir = plugins_dir_for(&input.codewhale_home);
562 let path = display_path(&plugins_dir);
563
564 // Manifest-based plugins (plugin.toml) are owned by this App's immutable,
565 // workspace-scoped registry snapshot. Never consult process-global state:
566 // concurrent sessions may be rooted in different workspaces.
567 let list = input.plugin_registry.list();
568 let manifest_total = list.len();
569 let manifest_active = list.iter().filter(|plugin| plugin.active()).count();
570 let active_commands = list
571 .iter()
572 .filter(|plugin| {
573 plugin.component_active(
574 codewhale_plugins::activation::PluginActivationCapability::Commands,
575 )
576 })
577 .map(|plugin| plugin.inventory.commands)
578 .sum::<usize>();
579 let active_agents = list
580 .iter()
581 .filter(|plugin| {
582 plugin
583 .component_active(codewhale_plugins::activation::PluginActivationCapability::Agents)
584 })
585 .map(|plugin| plugin.inventory.agents)
586 .sum::<usize>();
587 let active_hooks = list
588 .iter()
589 .filter(|plugin| {
590 plugin
591 .component_active(codewhale_plugins::activation::PluginActivationCapability::Hooks)
592 })
593 .map(|plugin| plugin.inventory.hooks)
594 .sum::<usize>();
595
596 // Script plugins under [tools].plugin_dir (distinct from slash commands;
597 // Hotbar Plugin source remains deferred/exploratory).
598 let script_dir = input
599 .config
600 .tools
601 .as_ref()
602 .and_then(|tools| tools.plugin_dir.as_ref())
603 .map(PathBuf::from)
604 .filter(|p| p.as_path() != plugins_dir.as_path());
605 let script_count = script_dir
606 .as_ref()
607 .filter(|p| p.is_dir())
608 .map(|p| codewhale_engine::tools::plugin::scan_plugin_dir(p).len())
609 .unwrap_or(0);
610
611 if !plugins_dir.exists() && manifest_total == 0 && script_count == 0 {
612 return InventoryRow {
613 status: InventoryStatus::Off,
614 detail: format!(
615 "nothing configured yet (missing at {path}); optional — use /plugin to add or review plugins"
616 ),
617 };
618 }
619
620 if plugins_dir.exists() && !plugins_dir.is_dir() {
621 return InventoryRow {
622 status: InventoryStatus::NeedsConfig,
623 detail: format!("plugins path exists but is not a directory at {path}"),
624 };
625 }
626
627 if manifest_total == 0 && script_count == 0 {
628 return InventoryRow {
629 status: InventoryStatus::Off,
630 detail: format!("dir present at {path} with 0 plugins; use /plugin to add one"),
631 };
632 }
633
634 let inactive = manifest_total.saturating_sub(manifest_active);
635 InventoryRow {
636 status: InventoryStatus::Healthy,
637 detail: format!(
638 "{manifest_total} bundles ({manifest_active} trusted+active, {inactive} inactive); active adapters: {active_commands} commands, {active_agents} agents, {active_hooks} hooks; {script_count} legacy script tools; use /plugin to review trust and enablement"
639 ),
640 }
641 }
642
643 fn plugins_dir_for(codewhale_home: &Path) -> PathBuf {
644 codewhale_home.join("plugins")
645 }
646
647 fn hotbar_source_inventory(app: &App) -> InventoryRow {
648 // Reuse the same Hotbar action registry the setup Hotbar step and command
649 // palette already share — do not re-discover MCP/skills here.
650 let mut mcp = 0usize;
651 let mut skill = 0usize;
652 let mut plugin = 0usize;
653 let mut slash = 0usize;
654 for action in app.hotbar_actions.iter() {
655 match action.category() {
656 c if c == HotbarActionCategory::Mcp.as_str() => mcp += 1,
657 c if c == HotbarActionCategory::Skill.as_str() => skill += 1,
658 c if c == HotbarActionCategory::Plugin.as_str() => plugin += 1,
659 c if c == HotbarActionCategory::Slash.as_str() => slash += 1,
660 _ => {}
661 }
662 }
663 // Plugin source is deferred by design (#3399) — zero dispatchable plugin
664 // actions is healthy, not a failure.
665 let status = if mcp > 0 || skill > 0 {
666 InventoryStatus::Healthy
667 } else {
668 InventoryStatus::Off
669 };
670 InventoryRow {
671 status,
672 detail: format!(
673 "shared adapters: mcp_actions={mcp}, skill_actions={skill}, plugin_actions={plugin} (deferred), slash_actions={slash}"
674 ),
675 }
676 }
677
678 fn count_dir_entries(dir: &Path) -> usize {
679 std::fs::read_dir(dir)
680 .map(|entries| {
681 entries
682 .filter_map(Result::ok)
683 .filter(|entry| entry.file_name().to_string_lossy() != ".DS_Store")
684 .count()
685 })
686 .unwrap_or(0)
687 }
688
689 fn count_skill_dirs(dir: &Path) -> usize {
690 std::fs::read_dir(dir)
691 .map(|entries| {
692 entries
693 .filter_map(Result::ok)
694 .filter(|entry| entry.path().join("SKILL.md").is_file())
695 .count()
696 })
697 .unwrap_or(0)
698 }
699
700 #[cfg(test)]
701 mod tests {
702 use super::*;
703 use crate::tui::app::TuiOptions;
704 use crate::tui::hotbar::actions::HotbarActionRegistry;
705 use codewhale_engine::mcp::{McpDiscoveredItem, McpManagerSnapshot, McpServerSnapshot};
706 use codewhale_localization::Locale;
707 use codewhale_runtime::config::Config;
708 use tempfile::TempDir;
709
710 fn test_app(
711 workspace: &Path,
712 config_path: Option<PathBuf>,
713 mcp_config_path: PathBuf,
714 skills_dir: PathBuf,
715 ) -> App {
716 let options = TuiOptions {
717 config_path,
718 skills_dir: skills_dir.clone(),
719 memory_path: workspace.join("memory.md"),
720 mcp_config_path,
721 ..crate::tui::test_support::test_tui_options(workspace)
722 };
723 let mut app = App::new(options, &Config::default());
724 app.ui_locale = Locale::En;
725 // App::new re-resolves skills via global/workspace discovery; pin the
726 // hermetic test path and empty cache so host ~/.agents/skills cannot
727 // leak into inventory assertions.
728 app.skills_dir = skills_dir;
729 app.cached_skills.clear();
730 app.hotbar_actions = HotbarActionRegistry::with_builtins();
731 app
732 }
733
734 fn write_path_only_command(dir: &Path) -> String {
735 let command = "codewhale-setup-mcp-path-only-test";
736 #[cfg(windows)]
737 let file_name = format!("{command}.exe");
738 #[cfg(not(windows))]
739 let file_name = command.to_string();
740 let path = dir.join(file_name);
741 std::fs::write(&path, b"test executable").expect("write path-only command");
742 #[cfg(unix)]
743 {
744 use std::os::unix::fs::PermissionsExt;
745
746 let mut permissions = std::fs::metadata(&path)
747 .expect("path-only command metadata")
748 .permissions();
749 permissions.set_mode(0o755);
750 std::fs::set_permissions(&path, permissions)
751 .expect("make path-only command executable");
752 }
753 command.to_string()
754 }
755
756 fn path_server(command: &str, path: &Path) -> McpServerConfig {
757 serde_json::from_value(serde_json::json!({
758 "command": command,
759 "env": {"PATH": path},
760 }))
761 .expect("stdio server config")
762 }
763
764 #[test]
765 fn empty_inventory_is_off_not_error() {
766 let tmp = TempDir::new().expect("tempdir");
767 let home = tmp.path().join("home");
768 std::fs::create_dir_all(&home).expect("home");
769 let app = test_app(
770 tmp.path(),
771 None,
772 tmp.path().join("mcp.json"),
773 tmp.path().join("skills"),
774 );
775
776 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
777
778 assert!(
779 facts.servers_result.contains("off"),
780 "empty MCP should be off: {}",
781 facts.servers_result
782 );
783 assert!(
784 facts.skills_result.contains("off"),
785 "missing skills dir should be off: {}",
786 facts.skills_result
787 );
788 assert!(
789 facts.plugins_result.contains("off"),
790 "missing plugins should be off: {}",
791 facts.plugins_result
792 );
793 assert!(
794 !facts.needs_action,
795 "empty optional inventory must not block"
796 );
797 assert_eq!(facts.overall_status, InventoryStatus::Off);
798 assert!(facts.result.contains("mode=read_only_safe_probe"));
799 assert!(facts.servers_result.contains("/mcp") || facts.servers_result.contains("optional"));
800 }
801
802 #[test]
803 fn configured_mcp_is_not_reported_as_live_healthy() {
804 let tmp = TempDir::new().expect("tempdir");
805 let home = tmp.path().join("cw-home");
806 std::fs::create_dir_all(&home).expect("home");
807 let mcp_path = tmp.path().join("mcp.json");
808 let executable = std::env::current_exe().expect("current test executable");
809 let mcp_config = serde_json::json!({
810 "servers": {
811 "docs": {
812 "command": executable,
813 "args": ["-y", "secret-mcp-package"],
814 "env": {"API_KEY": "sk-mcp-secret-token"},
815 "headers": {"Authorization": "Bearer sk-header-secret"}
816 }
817 }
818 });
819 std::fs::write(
820 &mcp_path,
821 serde_json::to_vec(&mcp_config).expect("serialize mcp config"),
822 )
823 .expect("write mcp");
824
825 let skills_dir = tmp.path().join("skills");
826 std::fs::create_dir_all(skills_dir.join("alpha")).expect("skill dir");
827 std::fs::write(
828 skills_dir.join("alpha").join("SKILL.md"),
829 "---\nname: alpha\ndescription: hides sk-skill-secret\n---\nbody\n",
830 )
831 .expect("skill");
832
833 let plugins_dir = home.join("plugins");
834 std::fs::create_dir_all(plugins_dir.join("demo")).expect("plugin");
835 std::fs::write(
836 plugins_dir.join("demo").join("plugin.toml"),
837 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\ndescription = \"hides sk-plugin-secret\"\n",
838 )
839 .expect("manifest");
840
841 let mut app = test_app(tmp.path(), None, mcp_path, skills_dir);
842 let discovery_config = codewhale_plugins::discovery::DiscoveryConfig {
843 workspace: tmp.path().to_path_buf(),
844 user_plugins_dir: plugins_dir,
845 workspace_plugins_dir: tmp.path().join("workspace-plugins-unused"),
846 builtin_plugin_dirs: Vec::new(),
847 state_path: home.join("plugins/state.json"),
848 };
849 let discovery = codewhale_plugins::PluginDiscoveryContext::from_config_and_environment(
850 &discovery_config,
851 codewhale_plugins::HostEnvironment::default(),
852 );
853 app.plugin_registry = discovery.registry_for_workspace(tmp.path());
854 // Simulate the same skill registration Hotbar uses at startup.
855 app.cached_skills = vec![("alpha".into(), "alpha skill".into())];
856 app.hotbar_actions = HotbarActionRegistry::with_builtins();
857 app.hotbar_actions.register_skills(&app.cached_skills);
858
859 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
860
861 assert!(
862 facts.servers_result.starts_with("configured"),
863 "configured MCP should report configuration evidence: {}",
864 facts.servers_result
865 );
866 assert!(facts.servers_result.contains("live health not checked"));
867 assert!(!facts.servers_result.contains("healthy"));
868 assert!(facts.servers_result.contains("docs"));
869 assert!(
870 facts.skills_result.contains("healthy"),
871 "installed skills: {}",
872 facts.skills_result
873 );
874 assert!(
875 facts.plugins_result.contains("healthy"),
876 "manifest plugins: {}",
877 facts.plugins_result
878 );
879 assert!(facts.hotbar_result.contains("skill_actions=1"));
880 assert!(!facts.needs_action);
881
882 // Redaction: never leak tokens, env values, or full command args.
883 let blob = format!(
884 "{} {} {} {} {}",
885 facts.servers_result,
886 facts.skills_result,
887 facts.plugins_result,
888 facts.hotbar_result,
889 facts.result
890 );
891 assert!(!blob.contains("sk-mcp-secret-token"));
892 assert!(!blob.contains("sk-header-secret"));
893 assert!(!blob.contains("sk-skill-secret"));
894 assert!(!blob.contains("sk-plugin-secret"));
895 assert!(!blob.contains("secret-mcp-package"));
896 assert!(!blob.contains("API_KEY"));
897 assert!(!blob.contains("Bearer"));
898 }
899
900 #[test]
901 fn setup_resolves_server_path_while_doctor_stays_structural() {
902 let temp = TempDir::new().expect("tempdir");
903 let command = write_path_only_command(temp.path());
904 let mut server = path_server(&command, temp.path());
905
906 assert_eq!(classify_config_server(&server), InventoryStatus::Healthy);
907 assert!(matches!(
908 crate::doctor_check_mcp_server(&server),
909 crate::McpServerDoctorStatus::Ok(_)
910 ));
911 assert_eq!(
912 crate::doctor_mcp_command_status(&server),
913 crate::McpCommandAvailability::NotChecked
914 );
915
916 server.command = Some("codewhale-setup-mcp-command-that-does-not-exist".to_string());
917 assert_eq!(
918 classify_config_server(&server),
919 InventoryStatus::NeedsConfig
920 );
921 assert!(matches!(
922 crate::doctor_check_mcp_server(&server),
923 crate::McpServerDoctorStatus::Ok(_)
924 ));
925 assert_eq!(
926 crate::doctor_mcp_command_status(&server),
927 crate::McpCommandAvailability::NotChecked
928 );
929 }
930
931 #[test]
932 fn failed_mcp_reports_needs_config() {
933 let tmp = TempDir::new().expect("tempdir");
934 let home = tmp.path().join("home");
935 std::fs::create_dir_all(&home).expect("home");
936 let mcp_path = tmp.path().join("mcp.json");
937 std::fs::write(
938 &mcp_path,
939 r#"{
940 "servers": {
941 "broken": {
942 "command": "/definitely/missing/mcp-server-binary",
943 "args": ["--token", "sk-should-not-leak"]
944 },
945 "off-server": {
946 "command": "npx",
947 "enabled": false
948 }
949 }
950 }"#,
951 )
952 .expect("write mcp");
953
954 let app = test_app(
955 tmp.path(),
956 None,
957 mcp_path,
958 tmp.path().join("skills-missing"),
959 );
960 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
961
962 assert!(
963 facts.servers_result.contains("needs_config"),
964 "broken absolute command should needs_config: {}",
965 facts.servers_result
966 );
967 assert!(facts.servers_result.contains("broken"));
968 assert!(facts.servers_result.contains("off"));
969 assert!(facts.needs_action);
970 assert!(!facts.servers_result.contains("sk-should-not-leak"));
971 assert!(!facts.result.contains("sk-should-not-leak"));
972 }
973
974 #[test]
975 fn live_snapshot_failed_server_is_needs_config() {
976 let tmp = TempDir::new().expect("tempdir");
977 let home = tmp.path().join("home");
978 std::fs::create_dir_all(&home).expect("home");
979 let mut app = test_app(
980 tmp.path(),
981 None,
982 tmp.path().join("mcp.json"),
983 tmp.path().join("skills"),
984 );
985 app.mcp_snapshot = Some(McpManagerSnapshot {
986 config_path: tmp.path().join("mcp.json"),
987 config_exists: true,
988 reload_required: false,
989 servers: vec![
990 McpServerSnapshot {
991 name: "ok".into(),
992 enabled: true,
993 required: false,
994 transport: "stdio".into(),
995 command_or_url: "npx secret-should-not-appear".into(),
996 connect_timeout: 10,
997 execute_timeout: 10,
998 read_timeout: 10,
999 connected: true,
1000 error: None,
1001 auth_required: false,
1002 capability_metadata:
1003 codewhale_engine::mcp::McpServerCapabilityMetadata::LegacyFallback,
1004 tools: vec![McpDiscoveredItem {
1005 name: "tool_a".into(),
1006 model_name: "mcp_ok_tool_a".into(),
1007 description: Some("desc".into()),
1008 }],
1009 resources: Vec::new(),
1010 prompts: Vec::new(),
1011 },
1012 McpServerSnapshot {
1013 name: "bad".into(),
1014 enabled: true,
1015 required: false,
1016 transport: "stdio".into(),
1017 command_or_url: "run --token sk-live-secret".into(),
1018 connect_timeout: 10,
1019 execute_timeout: 10,
1020 read_timeout: 10,
1021 connected: false,
1022 error: Some("spawn failed: connection refused".into()),
1023 auth_required: false,
1024 capability_metadata:
1025 codewhale_engine::mcp::McpServerCapabilityMetadata::NotObserved,
1026 tools: Vec::new(),
1027 resources: Vec::new(),
1028 prompts: Vec::new(),
1029 },
1030 ],
1031 });
1032
1033 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
1034 assert!(facts.servers_result.contains("needs_config"));
1035 assert!(facts.servers_result.contains("bad"));
1036 assert!(facts.servers_result.contains("ok"));
1037 assert!(facts.servers_result.contains("protocol_ready"));
1038 assert!(
1039 facts
1040 .servers_result
1041 .contains("backend/tool health not checked")
1042 );
1043 assert!(facts.needs_action);
1044 assert!(!facts.servers_result.contains("sk-live-secret"));
1045 assert!(!facts.servers_result.contains("secret-should-not-appear"));
1046 // Error detail text may mention connection refused but not secrets.
1047 assert!(!facts.servers_result.contains("spawn failed"));
1048 }
1049
1050 #[test]
1051 fn missing_skills_dir_is_off_not_needs_config() {
1052 let tmp = TempDir::new().expect("tempdir");
1053 let home = tmp.path().join("home");
1054 std::fs::create_dir_all(&home).expect("home");
1055 let missing = tmp.path().join("no-such-skills");
1056 let app = test_app(tmp.path(), None, tmp.path().join("mcp.json"), missing);
1057 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
1058 assert!(facts.skills_result.starts_with("off"));
1059 assert!(!facts.skills_result.contains("needs_config"));
1060 }
1061
1062 #[test]
1063 fn skills_path_not_directory_is_needs_config() {
1064 let tmp = TempDir::new().expect("tempdir");
1065 let home = tmp.path().join("home");
1066 std::fs::create_dir_all(&home).expect("home");
1067 let skills_file = tmp.path().join("skills-as-file");
1068 std::fs::write(&skills_file, "not a dir").expect("file");
1069 let app = test_app(tmp.path(), None, tmp.path().join("mcp.json"), skills_file);
1070 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
1071 assert!(facts.skills_result.contains("needs_config"));
1072 assert!(facts.needs_action);
1073 }
1074
1075 #[test]
1076 fn plugin_unavailable_is_off_with_actionable_hint() {
1077 let tmp = TempDir::new().expect("tempdir");
1078 let home = tmp.path().join("home");
1079 std::fs::create_dir_all(&home).expect("home");
1080 // No plugins dir under home.
1081 let app = test_app(
1082 tmp.path(),
1083 None,
1084 tmp.path().join("mcp.json"),
1085 tmp.path().join("skills"),
1086 );
1087 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
1088 assert!(
1089 facts.plugins_result.contains("off"),
1090 "{}",
1091 facts.plugins_result
1092 );
1093 assert!(
1094 facts.plugins_result.contains("optional")
1095 || facts.plugins_result.contains("setup --plugins")
1096 || facts.plugins_result.contains("deferred"),
1097 "actionable empty-plugin copy: {}",
1098 facts.plugins_result
1099 );
1100 }
1101
1102 #[test]
1103 fn on_ramp_text_mentions_safe_commands_and_redacts() {
1104 let facts = SetupToolsMcpFacts {
1105 servers_result: "off — nothing configured".into(),
1106 skills_result: "off — missing".into(),
1107 tools_result: "off — missing".into(),
1108 plugins_result: "off — missing".into(),
1109 hotbar_result: "off — shared adapters: mcp_actions=0".into(),
1110 dsh_result: "detected — dsh 0.1.0-rc.6, not connected".into(),
1111 result: "overall=off".into(),
1112 overall_status: InventoryStatus::Off,
1113 needs_action: false,
1114 mcp_path_display: "~/.codewhale/mcp.json".into(),
1115 skills_path_display: "~/.codewhale/skills".into(),
1116 plugins_path_display: "~/.codewhale/plugins".into(),
1117 };
1118 let text = on_ramp_text(Locale::En, &facts);
1119 assert!(text.contains("codewhale mcp init") || text.contains("/mcp"));
1120 assert!(text.contains("/skills") || text.contains("setup --skills"));
1121 assert!(text.contains("does not") || text.contains("never") || text.contains("not run"));
1122 assert!(text.contains("~/.codewhale/mcp.json"));
1123 assert!(!text.contains("sk-"));
1124 }
1125
1126 #[test]
1127 fn redacted_result_summary_omits_paths_with_home_secrets() {
1128 // result summary uses status tokens only — no raw env secrets.
1129 let tmp = TempDir::new().expect("tempdir");
1130 let home = tmp.path().join("home");
1131 std::fs::create_dir_all(&home).expect("home");
1132 let mcp_path = tmp.path().join("mcp.json");
1133 std::fs::write(
1134 &mcp_path,
1135 r#"{"servers":{"s":{"command":"npx","env":{"TOKEN":"sk-result-secret"}}}}"#,
1136 )
1137 .expect("mcp");
1138 let app = test_app(tmp.path(), None, mcp_path, tmp.path().join("skills"));
1139 let facts = SetupToolsMcpFacts::from_app_config(&app, &Config::default(), &home);
1140 assert!(!facts.result.contains("sk-result-secret"));
1141 assert!(facts.result.contains("mcp="));
1142 assert!(facts.result.contains("mode=read_only_safe_probe"));
1143 }
1144
1145 #[tokio::test(flavor = "current_thread")]
1146 async fn tools_mcp_probe_runs_on_blocking_pool_off_runtime_thread() {
1147 let tmp = TempDir::new().expect("tempdir");
1148 let home = tmp.path().join("home");
1149 let tools_dir = home.join("tools");
1150 std::fs::create_dir_all(&tools_dir).expect("tools dir");
1151 std::fs::write(tools_dir.join("helper.sh"), "#!/bin/sh\necho ok\n").expect("tool file");
1152
1153 let skills_dir = tmp.path().join("skills");
1154 std::fs::create_dir_all(skills_dir.join("alpha")).expect("skill dir");
1155 std::fs::write(
1156 skills_dir.join("alpha").join("SKILL.md"),
1157 "---\nname: alpha\n---\nbody\n",
1158 )
1159 .expect("skill file");
1160
1161 let app = test_app(tmp.path(), None, tmp.path().join("mcp.json"), skills_dir);
1162 let config = Config::default();
1163 let sync_facts = SetupToolsMcpFacts::from_app_config(&app, &config, &home);
1164
1165 let runtime_thread = std::thread::current().id();
1166 let input = ToolsMcpProbeInput::from_app_config(&app, &config, home);
1167 let (probe_thread, async_facts) = tokio::task::spawn_blocking(move || {
1168 (
1169 std::thread::current().id(),
1170 SetupToolsMcpFacts::from_probe_input(&input),
1171 )
1172 })
1173 .await
1174 .expect("blocking probe task");
1175
1176 assert_ne!(
1177 probe_thread, runtime_thread,
1178 "directory scans must execute on the blocking pool, not the Tokio worker thread"
1179 );
1180 assert_eq!(async_facts, sync_facts);
1181 assert!(async_facts.tools_result.contains("1 entries"));
1182 assert!(async_facts.skills_result.contains("1 on disk"));
1183 }
1184 }
1185
1185 lines RUST