Skip to main content

lean_ctx/tools/registered/
ctx_shell.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6    McpTool, ShellOutcome, ToolContext, ToolOutput, get_bool, get_str,
7};
8use crate::tool_defs::tool_def;
9
10pub struct CtxShellTool;
11
12impl McpTool for CtxShellTool {
13    fn name(&self) -> &'static str {
14        "ctx_shell"
15    }
16
17    fn tool_def(&self) -> Tool {
18        tool_def(
19            "ctx_shell",
20            "WORKFLOW: preferred — auto-compresses output (build/test/log).\n\
21             raw=true for verbatim output.\n\
22             [exit:N] on errors (lossless).\n\
23             ANTIPATTERN: multi-line scripts → ctx_execute.",
24            json!({
25                "type": "object",
26                "properties": {
27                    "command": { "type": "string", "description": "Shell command" },
28                    "raw": { "type": "boolean", "description": "Skip compression (verbatim)" },
29                    "cwd": { "type": "string", "description": "Working dir (persists across calls)" },
30                    "env": { "type": "object", "description": "Extra env vars", "additionalProperties": { "type": "string" } }
31                },
32                "required": ["command"]
33            }),
34        )
35    }
36
37    fn handle(
38        &self,
39        args: &Map<String, Value>,
40        ctx: &ToolContext,
41    ) -> Result<ToolOutput, ErrorData> {
42        let command = get_str(args, "command")
43            .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
44
45        // The write-doctrine check (no `>`, `tee`, heredoc-to-file, curl -o, …)
46        // is an MCP-payload-safety convention, not a security boundary, so it is
47        // opt-out via `shell_allow_writes` (#523). The real command gating
48        // (`check_shell_allowlist`, below) is NOT affected by this flag.
49        if !crate::core::config::Config::load().shell_allow_writes_effective()
50            && let Some(rejection) = crate::tools::ctx_shell::validate_command(&command)
51        {
52            // The command never ran — report as a tool error so MCP clients
53            // (guards, retry logic) can detect it programmatically (#389).
54            return Ok(ToolOutput {
55                shell_outcome: Some(ShellOutcome::Blocked),
56                ..ToolOutput::simple(rejection)
57            });
58        }
59
60        if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&command) {
61            return Ok(ToolOutput {
62                shell_outcome: Some(ShellOutcome::Blocked),
63                ..ToolOutput::simple(msg)
64            });
65        }
66
67        warn_shell_secret_paths(&command);
68
69        tokio::task::block_in_place(|| {
70            let session_lock = ctx
71                .session
72                .as_ref()
73                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
74
75            let explicit_cwd = get_str(args, "cwd");
76            let effective_cwd = {
77                let guard = crate::server::bounded_lock::read(session_lock, "ctx_shell_cwd");
78                match guard {
79                    Some(session) => session.effective_cwd(explicit_cwd.as_deref()),
80                    None => explicit_cwd.unwrap_or_else(|| ".".to_string()),
81                }
82            };
83
84            {
85                let Some(mut session) =
86                    crate::server::bounded_lock::write(session_lock, "ctx_shell_write")
87                else {
88                    tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
89                    let cmd_clone = command.clone();
90                    let cwd_clone = effective_cwd.clone();
91                    let extra_env: std::collections::HashMap<String, String> = args
92                        .get("env")
93                        .and_then(|v| v.as_object())
94                        .map(|obj| {
95                            obj.iter()
96                                .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
97                                .filter(|(k, _)| !is_dangerous_env_key(k))
98                                .collect()
99                        })
100                        .unwrap_or_default();
101                    let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
102                        &cmd_clone, &cwd_clone, &extra_env,
103                    );
104                    let output = redact_shell_output_secrets(&raw_output);
105                    // Keep failure reporting consistent on this degraded path:
106                    // same [exit:N] footer and the same structured outcome (#389).
107                    let exit_suffix = if exit_code != 0 {
108                        format!("\n[exit:{exit_code}]")
109                    } else {
110                        String::new()
111                    };
112                    return Ok(ToolOutput {
113                        shell_outcome: Some(ShellOutcome::Exit(exit_code)),
114                        ..ToolOutput::simple(format!("{output}{exit_suffix}"))
115                    });
116                };
117                session.update_shell_cwd(&command);
118                let root_missing = session
119                    .project_root
120                    .as_deref()
121                    .is_none_or(|r| r.trim().is_empty());
122                if root_missing {
123                    let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
124                    if let Some(root) = crate::core::protocol::detect_project_root(&effective_cwd)
125                        && home.as_deref() != Some(root.as_str())
126                    {
127                        session.project_root = Some(root.clone());
128                        crate::core::index_orchestrator::ensure_all_background(&root);
129                    }
130                }
131            }
132
133            let arg_raw = get_bool(args, "raw").unwrap_or(false);
134            let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
135            let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
136            let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
137            let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
138
139            let crp_mode = ctx.crp_mode;
140            let cmd_clone = command.clone();
141            let cwd_clone = effective_cwd;
142
143            let extra_env: std::collections::HashMap<String, String> = args
144                .get("env")
145                .and_then(|v| v.as_object())
146                .map(|obj| {
147                    obj.iter()
148                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
149                        .filter(|(k, _)| !is_dangerous_env_key(k))
150                        .collect()
151                })
152                .unwrap_or_default();
153
154            let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
155                &cmd_clone, &cwd_clone, &extra_env,
156            );
157
158            // Structured diagnostics (#499) — same hook as the CLI path.
159            crate::core::diagnostics_store::record_from_shell(&cmd_clone, &raw_output, exit_code);
160
161            let output = redact_shell_output_secrets(&raw_output);
162
163            let (result_out, original, saved, tee_hint) = if raw {
164                let tokens = crate::core::tokens::count_tokens(&output);
165                (output, tokens, 0, String::new())
166            } else {
167                let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
168                let result =
169                    crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
170                let original = crate::core::tokens::count_tokens(&output);
171                let sent = crate::core::tokens::count_tokens(&result);
172                let saved = original.saturating_sub(sent);
173
174                let cfg = crate::core::config::Config::load();
175                // Shared tee policy (#811): identical decision to the CLI path —
176                // `Failures` keys off the real exit code, not a substring match.
177                let tee_hint = if crate::shell::tee_policy::should_tee(
178                    &cfg.tee_mode,
179                    exit_code,
180                    output.trim().is_empty(),
181                    original,
182                    sent,
183                ) {
184                    crate::shell::save_tee(&cmd_clone, &output)
185                        .map(|p| {
186                            if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
187                            {
188                                let pct = crate::shell::tee_policy::savings_pct(original, sent);
189                                format!("\n[compressed {pct:.0}%: full output at {p} if needed]")
190                            } else {
191                                format!("\n[full output: {p}]")
192                            }
193                        })
194                        .unwrap_or_default()
195                } else {
196                    String::new()
197                };
198
199                (result, original, saved, tee_hint)
200            };
201
202            let mode = if bypass {
203                Some("bypass".to_string())
204            } else if raw {
205                Some("raw".to_string())
206            } else {
207                None
208            };
209
210            let shell_mismatch = if cfg!(windows) && !raw {
211                shell_mismatch_hint(&command, &result_out)
212            } else {
213                String::new()
214            };
215
216            let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
217            let exit_suffix = if exit_code != 0 {
218                format!("\n[exit:{exit_code}]")
219            } else {
220                String::new()
221            };
222            let final_out = format!("{result_out}{tee_hint}{shell_mismatch}{exit_suffix}");
223
224            Ok(ToolOutput {
225                text: final_out,
226                original_tokens: original,
227                saved_tokens: saved,
228                mode,
229                path: None,
230                changed: false,
231                shell_outcome: Some(ShellOutcome::Exit(exit_code)),
232            })
233        })
234    }
235}
236
237#[allow(clippy::fn_params_excessive_bools)]
238fn resolve_shell_raw_flags(
239    arg_raw: bool,
240    arg_bypass: bool,
241    env_disabled: bool,
242    env_raw: bool,
243) -> (bool, bool) {
244    let bypass = arg_bypass || env_raw;
245    let raw = arg_raw || bypass || env_disabled;
246    (raw, bypass)
247}
248
249fn shell_mismatch_hint(command: &str, output: &str) -> String {
250    let shell = crate::shell::shell_name();
251    let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
252    let has_error = output.contains("is not recognized")
253        || output.contains("not found")
254        || output.contains("command not found");
255
256    if !has_error {
257        return String::new();
258    }
259
260    let powershell_cmds = [
261        "Get-Content",
262        "Select-Object",
263        "Get-ChildItem",
264        "Set-Location",
265        "Where-Object",
266        "ForEach-Object",
267        "Select-String",
268        "Invoke-Expression",
269        "Write-Output",
270    ];
271    let uses_powershell = powershell_cmds
272        .iter()
273        .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
274
275    if is_posix && uses_powershell {
276        format!(
277            "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
278        )
279    } else {
280        String::new()
281    }
282}
283
284fn is_dangerous_env_key(key: &str) -> bool {
285    const BLOCKED: &[&str] = &[
286        // Dynamic linker injection
287        "LD_PRELOAD",
288        "LD_LIBRARY_PATH",
289        "DYLD_INSERT_LIBRARIES",
290        "DYLD_LIBRARY_PATH",
291        "DYLD_FRAMEWORK_PATH",
292        // Shell re-entry / startup injection
293        "BASH_ENV",
294        "ENV",
295        "PROMPT_COMMAND",
296        "SHELL",
297        "IFS",
298        "CDPATH",
299        // Binary resolution hijacking
300        "PATH",
301        "GIT_EXEC_PATH",
302        "GIT_SSH",
303        "GIT_SSH_COMMAND",
304        // Identity / home directory manipulation
305        "HOME",
306        "USER",
307        "LOGNAME",
308        "XDG_CONFIG_HOME",
309        "XDG_DATA_HOME",
310        "XDG_STATE_HOME",
311        "XDG_CACHE_HOME",
312        // Language runtime search path hijacking
313        "PYTHONPATH",
314        "PYTHONSTARTUP",
315        "PYTHONHOME",
316        "NODE_PATH",
317        "NODE_OPTIONS",
318        "RUBYOPT",
319        "RUBYLIB",
320        "GEM_PATH",
321        "GEM_HOME",
322        "PERL5LIB",
323        "PERL5OPT",
324        "CLASSPATH",
325        "JAVA_HOME",
326        "CARGO_HOME",
327        "RUSTUP_HOME",
328        "GOPATH",
329        "GOROOT",
330    ];
331    let upper = key.to_uppercase();
332    if BLOCKED.contains(&upper.as_str()) {
333        return true;
334    }
335    if upper.starts_with("LD_") && upper.ends_with("_PATH") {
336        return true;
337    }
338    // Block all lean-ctx config overrides from env
339    if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
340        return true;
341    }
342    false
343}
344
345/// Warn when shell reads secret-like paths via cat/head/tail/less/more.
346/// WARN-ONLY: command still executes, this is purely observational.
347fn warn_shell_secret_paths(command: &str) {
348    const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
349    let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
350    for seg in &segments {
351        let trimmed = seg.trim();
352        let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
353        if tokens.is_empty() {
354            continue;
355        }
356        let base = tokens[0]
357            .rsplit('/')
358            .next()
359            .unwrap_or(&tokens[0])
360            .to_string();
361        if !READ_CMDS.contains(&base.as_str()) {
362            continue;
363        }
364        for tok in &tokens[1..] {
365            if tok.starts_with('-') {
366                continue;
367            }
368            let path = std::path::Path::new(tok.as_str());
369            if crate::core::io_boundary::is_secret_like(path).is_some() {
370                tracing::warn!(
371                    "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
372                );
373            }
374        }
375    }
376}
377
378fn redact_shell_output_secrets(output: &str) -> String {
379    let cfg = crate::core::config::Config::load();
380    if !cfg.secret_detection.enabled {
381        return output.to_string();
382    }
383    let (redacted, matches) =
384        crate::core::secret_detection::scan_and_redact(output, &cfg.secret_detection);
385    if !matches.is_empty() {
386        let names: Vec<&str> = matches.iter().map(|m| m.pattern_name).collect();
387        tracing::warn!(
388            "[SHELL SECRET REDACTION] {} secret(s) redacted from shell output: {}",
389            matches.len(),
390            names.join(", ")
391        );
392    }
393    redacted
394}