1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::core::ocla::cache_types::{CacheKeyBuilder, ShellCommandKey};
6
7use crate::server::tool_trait::{
8 BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext, ToolOutput,
9 get_bool, get_int, get_str,
10};
11use crate::tool_defs::tool_def;
12
13use super::ctx_shell_background::{format_background_state, redact_shell_output_secrets};
14
15pub struct CtxShellTool;
16
17const SESSION_LOCK_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
21
22impl McpTool for CtxShellTool {
23 fn name(&self) -> &'static str {
24 "ctx_shell"
25 }
26
27 fn tool_def(&self) -> Tool {
28 tool_def(
29 "ctx_shell",
30 "WORKFLOW: preferred — auto-compresses output (build/test/log).\n\
31 raw=true for verbatim output; inline=true for moderately-sized verbatim output.\n\
32 [exit:N] on errors (lossless).\n\
33 POLICY (by design): allowlisted read-only path; ctx_execute is the trusted script path.\n\
34 A [BLOCKED] command is permanent — escalate to ctx_execute(language=\"shell\"), do not retry here.\n\
35 ANTIPATTERN: multi-line scripts, sh/bash script.sh, $var-as-command → ctx_execute.",
36 json!({
37 "type": "object",
38 "properties": {
39 "command": { "type": "string", "description": "Shell command" },
40 "raw": { "type": "boolean", "description": "Skip compression (verbatim)" },
41 "inline": { "type": "boolean", "description": "Return verbatim output inline up to archive.inline_max_bytes; larger output uses the archive/firewall" },
42 "cwd": { "type": "string", "description": "Working dir (persists across calls)" },
43 "timeout_ms": { "type": "integer", "description": "Job lifetime in ms (max 3600000) — NOT the inline wait. A command still running at the ~110s foreground cap detaches to a pollable shell_* job and keeps running up to timeout_ms. Overridden by LEAN_CTX_SHELL_TIMEOUT_MS." },
44 "env": { "type": "object", "description": "Extra env vars", "additionalProperties": { "type": "string" } },
45 "run_in_background": { "type": "boolean", "description": "Detach immediately and return a job id. The command keeps timeout_ms; poll or cancel with background_action and job_id." },
46 "background_action": { "type": "string", "enum": ["status", "cancel"], "description": "Inspect or cancel a background ctx_shell job. Evicted/expired jobs return a structured lookup error." },
47 "job_id": { "type": "string", "description": "Job id returned by run_in_background." }
48 }
49 }),
50 )
51 }
52
53 fn handle(
54 &self,
55 args: &Map<String, Value>,
56 ctx: &ToolContext,
57 ) -> Result<ToolOutput, ErrorData> {
58 if let Some(message) = shell_access_denial(ctx) {
59 return Ok(ToolOutput {
60 shell_outcome: Some(ShellOutcome::Blocked),
61 content_blocks: None,
62 ..ToolOutput::simple(message)
63 });
64 }
65
66 if let Some(action) = get_str(args, "background_action") {
67 let id = get_str(args, "job_id").ok_or_else(|| {
68 ErrorData::invalid_params("job_id is required with background_action", None)
69 })?;
70 let is_cancel = action == "cancel";
71 let state = match action.as_str() {
72 "status" => crate::server::background_shell::status(&id),
73 "cancel" => crate::server::background_shell::cancel(&id),
74 _ => {
75 return Err(ErrorData::invalid_params(
76 "background_action must be status or cancel",
77 None,
78 ));
79 }
80 };
81 let (text, outcome) = format_background_state(&id, is_cancel, state);
82 return Ok(ToolOutput {
83 shell_outcome: Some(outcome),
84 content_blocks: None,
85 ..ToolOutput::simple(text)
86 });
87 }
88 let command = get_str(args, "command")
89 .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
90 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
91
92 let config = crate::core::config::Config::load();
97 let write_allow_paths = config.shell_write_allow_paths_effective();
98 let project_root = crate::core::config::Config::find_project_root();
99 if !config.shell_allow_writes_effective()
100 && let Some(rejection) =
101 crate::tools::ctx_shell::validate_command_with_write_allow_paths(
102 &command,
103 &write_allow_paths,
104 project_root.as_deref(),
105 )
106 {
107 return Ok(ToolOutput {
110 shell_outcome: Some(ShellOutcome::Blocked),
111 content_blocks: None,
112 ..ToolOutput::simple(rejection)
113 });
114 }
115
116 if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
117 return tokio::task::block_in_place(|| {
118 handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
119 });
120 }
121
122 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&command) {
123 return Ok(ToolOutput {
124 shell_outcome: Some(ShellOutcome::Blocked),
125 content_blocks: None,
126 ..ToolOutput::simple(msg.to_string())
127 });
128 }
129
130 warn_shell_secret_paths(&command);
131
132 if let Some(read_path) = detect_bare_cat_file(&command)
136 && let Some(cache_lock) = ctx.cache.as_ref()
137 && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
138 {
139 let result = crate::tools::ctx_read::handle_with_task_resolved(
140 &mut cache,
141 &read_path,
142 "full",
143 crate::tools::CrpMode::Off,
144 None,
145 );
146 let note = format!(
147 "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
148 Use ctx_read(path=\"{read_path}\") directly next time.]"
149 );
150 let out = format!("{}{note}", result.content);
151 let sent = crate::core::tokens::count_tokens(&out);
152 return Ok(ToolOutput {
153 text: out,
154 original_tokens: sent,
155 saved_tokens: 0,
156 mode: Some("cat-redirect".to_string()),
157 path: Some(read_path),
158 changed: false,
159 shell_outcome: Some(ShellOutcome::Exit(0)),
160 content_blocks: None,
161 });
162 }
163
164 tokio::task::block_in_place(|| {
165 let session_lock = ctx
166 .session
167 .as_ref()
168 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
169
170 let explicit_cwd = get_str(args, "cwd");
171 let had_explicit_cwd = explicit_cwd.is_some();
172 let guard = crate::server::bounded_lock::read_for(
173 session_lock,
174 "ctx_shell_cwd",
175 SESSION_LOCK_BUDGET,
176 );
177 let (effective_cwd, cwd_jail_reason) =
178 resolve_effective_cwd(guard, explicit_cwd.as_deref())?;
179 let cwd_jail_reason_was_none = cwd_jail_reason.is_none();
184 let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
185 format!(
186 "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
187 )
188 });
189
190 {
191 let Some(mut session) = crate::server::bounded_lock::write_for(
192 session_lock,
193 "ctx_shell_write",
194 SESSION_LOCK_BUDGET,
195 ) else {
196 tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
197 let cmd_clone = command.clone();
198 let cwd_clone = effective_cwd.clone();
199 let extra_env: std::collections::HashMap<String, String> = args
200 .get("env")
201 .and_then(|v| v.as_object())
202 .map(|obj| {
203 obj.iter()
204 .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
205 .filter(|(k, _)| !is_dangerous_env_key(k))
206 .collect()
207 })
208 .unwrap_or_default();
209 let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
210 &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
211 );
212 let output = redact_shell_output_secrets(&raw_output);
213 let exit_suffix = match exit_code {
216 0 => String::new(),
217 124 => "\n[exit:124 — command timed out]".to_string(),
218 _ => format!("\n[exit:{exit_code}]"),
219 };
220 return Ok(ToolOutput {
221 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
222 content_blocks: None,
223 ..ToolOutput::simple(format!("{output}{exit_suffix}"))
224 });
225 };
226 if had_explicit_cwd && cwd_jail_reason_was_none {
231 session.note_explicit_cwd(&effective_cwd);
232 }
233 session.update_shell_cwd(&command);
234 let root_missing = session
235 .project_root
236 .as_deref()
237 .is_none_or(|r| r.trim().is_empty());
238 if root_missing {
239 let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
240 if let Some(root) = crate::core::protocol::detect_project_root(&effective_cwd)
241 && home.as_deref() != Some(root.as_str())
242 {
243 session.project_root = Some(root.clone());
244 crate::core::index_orchestrator::ensure_all_background(&root);
245 }
246 }
247 }
248
249 let arg_raw = get_bool(args, "raw").unwrap_or(false);
250 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
251 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
252 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
253 let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
254
255 let crp_mode = ctx.crp_mode;
256 let cmd_clone = command.clone();
257 let cwd_clone = effective_cwd;
258 let proactive_block = if raw
259 || !crate::core::profiles::active_profile()
260 .output_hints
261 .proactive_context()
262 {
263 None
264 } else {
265 crate::core::relevance_tracker::proactive_context(&format!(
266 "ctx_shell command={cmd_clone} cwd={cwd_clone}"
267 ))
268 };
269
270 let extra_env: std::collections::HashMap<String, String> = args
271 .get("env")
272 .and_then(|v| v.as_object())
273 .map(|obj| {
274 obj.iter()
275 .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
276 .filter(|(k, _)| !is_dangerous_env_key(k))
277 .collect()
278 })
279 .unwrap_or_default();
280
281 let inline = get_bool(args, "inline").unwrap_or(false);
282 let shell_cache_key = shell_cache_key(&cmd_clone, &cwd_clone, &extra_env);
283 if !raw
284 && !inline
285 && crate::core::config::Config::load()
286 .cache
287 .shell_cache_enabled
288 && let Some(key) = shell_cache_key.as_ref()
289 && let Some(cached) = crate::core::ocla::shell_cache_allowlist::SHELL_RESULT_CACHE
290 .get(&key.cache_key())
291 .map(|r| r.clone())
292 && let Ok(value) = serde_json::from_str::<Value>(&cached)
293 && let (Some(text), Some(exit_code)) = (
294 value.get("text").and_then(Value::as_str),
295 value.get("exit_code").and_then(Value::as_i64),
296 )
297 {
298 return Ok(ToolOutput {
299 text: text.to_string(),
300 original_tokens: crate::core::tokens::count_tokens(text),
301 saved_tokens: 0,
302 mode: Some("cross-agent-cache".to_string()),
303 path: None,
304 changed: false,
305 shell_outcome: Some(ShellOutcome::Exit(exit_code as i32)),
306 content_blocks: None,
307 });
308 }
309
310 if let Some(ref key) = shell_cache_key {
312 let ck = key.cache_key();
313 let validator = key.validator();
314 if let Some(entry) =
315 crate::core::ocla::cache_delivery::check(&ck, &validator, "ctx_shell")
316 {
317 let stub = crate::core::ocla::cache_delivery::stub(&entry, "shell command");
318 return Ok(ToolOutput {
319 text: stub,
320 original_tokens: entry.token_count as usize,
321 saved_tokens: entry.token_count as usize,
322 mode: Some("cross-agent-cache".to_string()),
323 path: None,
324 changed: false,
325 shell_outcome: None,
326 content_blocks: None,
327 });
328 }
329 }
330
331 let auto_background = should_auto_background(&cmd_clone, timeout_ms);
332 if get_bool(args, "run_in_background").unwrap_or(false) || auto_background {
333 let job_id = crate::server::background_shell::start(
334 cmd_clone, cwd_clone, extra_env, timeout_ms,
335 );
336 let mode = if auto_background {
337 "auto-background"
338 } else {
339 "background"
340 };
341 return Ok(ToolOutput {
342 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
343 state: BackgroundJobState::Running,
344 exit_code: None,
345 job_id: job_id.clone(),
346 archive_id: None,
347 archive_truncated: None,
348 captured_chars: None,
349 archived_chars: None,
350 summary: format!("{mode} job started"),
351 is_error: false,
352 display: None,
353 })),
354 content_blocks: None,
355 ..ToolOutput::simple(format!(
356 "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
357 ))
358 });
359 }
360
361 let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
372 let progress_sender = ctx.progress_sender.clone();
373 let progress_label: String = cmd_clone.chars().take(60).collect();
374 let cap_secs = soft_cap.as_secs_f64();
375 let on_tick = |elapsed: std::time::Duration| {
376 #[allow(clippy::unwrap_or_default)]
377 if let Some(ref ps) = progress_sender
378 && let Some(sender) = ps
379 .lock()
380 .unwrap_or_else(std::sync::PoisonError::into_inner)
381 .as_ref()
382 {
383 sender.send(
384 elapsed.as_secs_f64(),
385 Some(cap_secs),
386 Some(format!(
387 "ctx_shell: {}s elapsed — {progress_label}",
388 elapsed.as_secs()
389 )),
390 );
391 }
392 };
393 let (raw_output, exit_code) =
394 match crate::server::background_shell::run_foreground_or_detach(
395 cmd_clone.clone(),
396 cwd_clone.clone(),
397 extra_env.clone(),
398 timeout_ms,
399 soft_cap,
400 Some(&on_tick),
401 ) {
402 crate::server::background_shell::ForegroundResult::Finished {
403 output,
404 exit_code,
405 } => (output, exit_code),
406 crate::server::background_shell::ForegroundResult::Detached { job_id } => {
407 return Ok(ToolOutput {
408 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
409 state: BackgroundJobState::Running,
410 exit_code: None,
411 job_id: job_id.clone(),
412 archive_id: None,
413 archive_truncated: None,
414 captured_chars: None,
415 archived_chars: None,
416 summary: "auto-detached job is still running".to_string(),
417 is_error: false,
418 display: None,
419 })),
420 content_blocks: None,
421 ..ToolOutput::simple(format!(
425 "[auto-background:{job_id} still running — passed the {}s foreground cap, not an error; output is kept and delivered by ctx_shell(background_action=\"status\", job_id=\"{job_id}\"), or background_action=\"cancel\" to stop it]",
426 soft_cap.as_secs()
427 ))
428 });
429 }
430 };
431
432 crate::core::diagnostics_store::record_from_shell(&cmd_clone, &raw_output, exit_code);
434
435 let output = redact_shell_output_secrets(&raw_output);
436
437 let (result_out, original, saved, tee_hint) = if raw || inline {
438 let tokens = crate::core::tokens::count_tokens(&output);
439 (output, tokens, 0, String::new())
440 } else {
441 let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
442 let result =
443 crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
444 let original = crate::core::tokens::count_tokens(&output);
445 let sent = crate::core::tokens::count_tokens(&result);
446 let saved = original.saturating_sub(sent);
447
448 let cfg = crate::core::config::Config::load();
449 let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
452 let tee_hint = if crate::shell::tee_policy::should_tee(
453 &cfg.tee_mode,
454 exit_code,
455 output.trim().is_empty() || timeout_notice_only,
456 crate::shell::tee_policy::output_was_elided(&output, &result),
457 original,
458 sent,
459 ) {
460 crate::shell::save_tee(&cmd_clone, &output)
461 .map(|p| {
462 if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
463 {
464 let pct = crate::shell::tee_policy::savings_pct(original, sent);
465 format!(
468 "\n[compressed {pct:.0}%: full output at {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\") for a slice]"
469 )
470 } else {
471 format!("\n[full output: {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\")]")
472 }
473 })
474 .unwrap_or_default()
475 } else {
476 String::new()
477 };
478
479 (result, original, saved, tee_hint)
480 };
481
482 let mode = if bypass {
483 Some("bypass".to_string())
484 } else if raw {
485 Some("raw".to_string())
486 } else {
487 None
488 };
489
490 let shell_mismatch = if cfg!(windows) && !raw {
491 shell_mismatch_hint(&command, &result_out)
492 } else {
493 String::new()
494 };
495
496 let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
497 let exit_suffix = match exit_code {
501 0 => String::new(),
502 124 => "\n[exit:124 — command timed out]".to_string(),
503 _ => format!("\n[exit:{exit_code}]"),
504 };
505 let nudge = if raw { "" } else { search_tool_nudge(&command) };
506 let final_out = format!(
507 "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
508 );
509 let final_out = if let Some(block) = proactive_block {
510 format!("{final_out}{block}")
511 } else {
512 final_out
513 };
514
515 if !raw
516 && !inline
517 && crate::core::config::Config::load()
518 .cache
519 .shell_cache_enabled
520 && let Some(key) = shell_cache_key
521 {
522 let cached = json!({ "text": final_out, "exit_code": exit_code }).to_string();
523 crate::core::ocla::shell_cache_allowlist::SHELL_RESULT_CACHE
524 .insert(key.cache_key(), cached);
525 crate::core::ocla::cache_delivery::record(
527 key.cache_key(),
528 crate::core::ocla::cache_types::DeliveryKind::ShellCommand,
529 key.validator(),
530 None,
531 &final_out,
532 "ctx_shell",
533 );
534 }
535
536 Ok(ToolOutput {
537 text: final_out,
538 original_tokens: original,
539 saved_tokens: saved,
540 mode,
541 path: None,
542 changed: false,
543 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
544 content_blocks: None,
545 })
546 })
547 }
548}
549
550fn shell_cache_key(
551 command: &str,
552 cwd: &str,
553 env: &std::collections::HashMap<String, String>,
554) -> Option<ShellCommandKey> {
555 if !crate::core::ocla::shell_cache_allowlist::is_cacheable_command(command) {
556 return None;
557 }
558 let mut env_pairs = env.iter().collect::<Vec<_>>();
559 env_pairs.sort_unstable_by(|left, right| left.0.cmp(right.0));
560 let mut canonical_env = String::new();
561 for (name, value) in env_pairs {
562 canonical_env.push_str(name);
563 canonical_env.push('=');
564 canonical_env.push_str(value);
565 canonical_env.push('\n');
566 }
567 Some(ShellCommandKey {
568 command_normalized: crate::core::ocla::shell_cache_allowlist::normalize_command(command),
569 cwd: if std::path::Path::new(cwd).is_absolute() {
570 "$PROJECT_ROOT".to_string()
571 } else {
572 cwd.to_string()
573 },
574 env_hash: blake3::hash(canonical_env.as_bytes()).to_hex().to_string(),
575 })
576}
577
578fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
581 if let Some(role) = ctx.client_role.as_deref()
582 && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
583 {
584 return Some(format!(
585 "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
586 ));
587 }
588
589 if ctx.shell_access == Some(false) {
590 return Some(
591 "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
592 .to_string(),
593 );
594 }
595
596 None
597}
598
599fn resolve_effective_cwd(
600 session: Option<tokio::sync::OwnedRwLockReadGuard<crate::core::session::SessionState>>,
601 explicit_cwd: Option<&str>,
602) -> Result<(String, Option<String>), ErrorData> {
603 match session {
604 Some(session) => Ok(session.effective_cwd_checked(explicit_cwd)),
605 None => Err(ErrorData::internal_error(
606 "session lock timeout — cannot validate working directory",
607 None,
608 )),
609 }
610}
611
612#[allow(clippy::fn_params_excessive_bools)]
613fn resolve_shell_raw_flags(
614 arg_raw: bool,
615 arg_bypass: bool,
616 _env_disabled: bool,
617 env_raw: bool,
618) -> (bool, bool) {
619 let bypass = arg_bypass || env_raw;
620 let raw = arg_raw || bypass;
621 (raw, bypass)
622}
623
624fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
631 exit_code == 124
632 && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
633}
634
635fn search_tool_nudge(command: &str) -> &'static str {
636 let cmd = command.trim();
637 let first_word = cmd.split_whitespace().next().unwrap_or("");
638 if !cmd.contains('|') {
639 match first_word {
640 "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
641 return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
642 }
643 "find" => {
644 return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
645 }
646 "ls" | "exa" | "eza" => {
647 return "\n[hint: use ctx_tree for structured directory listing]";
648 }
649 _ => {}
650 }
651 }
652 ""
653}
654
655fn shell_mismatch_hint(command: &str, output: &str) -> String {
656 let shell = crate::shell::shell_name();
657 let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
658 let has_error = output.contains("is not recognized")
659 || output.contains("not found")
660 || output.contains("command not found");
661
662 if !has_error {
663 return String::new();
664 }
665
666 let powershell_cmds = [
667 "Get-Content",
668 "Select-Object",
669 "Get-ChildItem",
670 "Set-Location",
671 "Where-Object",
672 "ForEach-Object",
673 "Select-String",
674 "Invoke-Expression",
675 "Write-Output",
676 ];
677 let uses_powershell = powershell_cmds
678 .iter()
679 .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
680
681 if is_posix && uses_powershell {
682 format!(
683 "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
684 )
685 } else {
686 String::new()
687 }
688}
689
690fn is_dangerous_env_key(key: &str) -> bool {
691 const BLOCKED: &[&str] = &[
692 "LD_PRELOAD",
694 "LD_LIBRARY_PATH",
695 "DYLD_INSERT_LIBRARIES",
696 "DYLD_LIBRARY_PATH",
697 "DYLD_FRAMEWORK_PATH",
698 "BASH_ENV",
700 "ENV",
701 "PROMPT_COMMAND",
702 "SHELL",
703 "IFS",
704 "CDPATH",
705 "PATH",
707 "GIT_EXEC_PATH",
708 "GIT_SSH",
709 "GIT_SSH_COMMAND",
710 "HOME",
712 "USER",
713 "LOGNAME",
714 "XDG_CONFIG_HOME",
715 "XDG_DATA_HOME",
716 "XDG_STATE_HOME",
717 "XDG_CACHE_HOME",
718 "PYTHONPATH",
720 "PYTHONSTARTUP",
721 "PYTHONHOME",
722 "NODE_PATH",
723 "NODE_OPTIONS",
724 "RUBYOPT",
725 "RUBYLIB",
726 "GEM_PATH",
727 "GEM_HOME",
728 "PERL5LIB",
729 "PERL5OPT",
730 "CLASSPATH",
731 "JAVA_HOME",
732 "CARGO_HOME",
733 "RUSTUP_HOME",
734 "GOPATH",
735 "GOROOT",
736 ];
737 let upper = key.to_uppercase();
738 if BLOCKED.contains(&upper.as_str()) {
739 return true;
740 }
741 if upper.starts_with("LD_") && upper.ends_with("_PATH") {
742 return true;
743 }
744 if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
746 return true;
747 }
748 false
749}
750
751fn warn_shell_secret_paths(command: &str) {
754 const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
755 let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
756 for seg in &segments {
757 let trimmed = seg.trim();
758 let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
759 if tokens.is_empty() {
760 continue;
761 }
762 let base = tokens[0]
763 .rsplit('/')
764 .next()
765 .unwrap_or(&tokens[0])
766 .to_string();
767 if !READ_CMDS.contains(&base.as_str()) {
768 continue;
769 }
770 for tok in &tokens[1..] {
771 if tok.starts_with('-') {
772 continue;
773 }
774 let path = std::path::Path::new(tok.as_str());
775 if crate::core::io_boundary::is_secret_like(path).is_some() {
776 tracing::warn!(
777 "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
778 );
779 }
780 }
781 }
782}
783
784fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
789 timeout_ms.is_some_and(|timeout| timeout >= 300_000)
790 && command
791 .lines()
792 .any(|line| line.trim_start().starts_with("cargo test"))
793}
794
795fn foreground_soft_cap_ms() -> u64 {
800 std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
801 .ok()
802 .and_then(|v| v.parse().ok())
803 .filter(|&ms| ms > 0)
804 .unwrap_or(110_000)
805}
806
807fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
809 match base {
810 "python" | "python2" | "python3" => Some("python"),
811 "node" => Some("javascript"),
812 "ruby" => Some("ruby"),
813 _ => None,
814 }
815}
816
817fn is_env_assignment_token(token: &str) -> bool {
818 let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
819 unquoted.contains('=')
820 && !unquoted.starts_with('-')
821 && !unquoted.starts_with('/')
822 && !unquoted.starts_with('.')
823}
824
825fn prelude_has_compound_operator(prelude: &str) -> bool {
827 let bytes = prelude.as_bytes();
828 let len = bytes.len();
829 let mut i = 0;
830 let mut in_single = false;
831 let mut in_double = false;
832 while i < len {
833 let ch = bytes[i];
834 if in_single {
835 if ch == b'\'' {
836 in_single = false;
837 }
838 i += 1;
839 continue;
840 }
841 if in_double {
842 if ch == b'\\' && i + 1 < len {
843 i += 2;
844 } else {
845 if ch == b'"' {
846 in_double = false;
847 }
848 i += 1;
849 }
850 continue;
851 }
852 match ch {
853 b'\'' => {
854 in_single = true;
855 i += 1;
856 }
857 b'"' => {
858 in_double = true;
859 i += 1;
860 }
861 b';' | b'|' | b'&' | b'(' | b'{' => return true,
862 _ => i += 1,
863 }
864 }
865 false
866}
867
868fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
872 if !command.contains("<<") {
873 return None;
874 }
875
876 let lines: Vec<&str> = command.lines().collect();
877 if lines.is_empty() {
878 return None;
879 }
880
881 let first_line = lines[0];
882 let delims = crate::core::shell_allowlist::heredoc_delims(first_line, false);
883 if delims.len() != 1 {
884 return None;
885 }
886 let delim = delims[0].clone();
887
888 let heredoc_pos = find_heredoc_operator(first_line)?;
889 let prelude = first_line[..heredoc_pos].trim();
890 if prelude_has_compound_operator(prelude) {
891 return None;
892 }
893
894 let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
895
896 if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
897 return None;
898 }
899
900 let mut body = String::new();
901 let mut remainder_start: Option<usize> = None;
902 for (idx, line) in lines.iter().enumerate().skip(1) {
903 if line.trim_start_matches('\t').trim() == delim {
904 remainder_start = Some(idx + 1);
905 break;
906 }
907 if !body.is_empty() {
908 body.push('\n');
909 }
910 body.push_str(line);
911 }
912 let remainder_start = remainder_start?;
913 let remainder = if remainder_start < lines.len() {
914 let rest = lines[remainder_start..].join("\n");
915 let rest = rest.trim();
916 if rest.is_empty() {
917 None
918 } else {
919 Some(rest.to_string())
920 }
921 } else {
922 None
923 };
924
925 Some((language, body, remainder))
926}
927
928fn find_heredoc_operator(line: &str) -> Option<usize> {
929 let bytes = line.as_bytes();
930 let len = bytes.len();
931 let mut i = 0;
932 let mut in_single = false;
933 let mut in_double = false;
934 while i < len {
935 let ch = bytes[i];
936 if in_single {
937 if ch == b'\'' {
938 in_single = false;
939 }
940 i += 1;
941 continue;
942 }
943 if in_double {
944 if ch == b'\\' && i + 1 < len {
945 i += 2;
946 } else {
947 if ch == b'"' {
948 in_double = false;
949 }
950 i += 1;
951 }
952 continue;
953 }
954 match ch {
955 b'\'' => {
956 in_single = true;
957 i += 1;
958 }
959 b'"' => {
960 in_double = true;
961 i += 1;
962 }
963 b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
964 if i + 2 < len && bytes[i + 2] == b'<' {
965 i += 3;
966 continue;
967 }
968 return Some(i);
969 }
970 _ => i += 1,
971 }
972 }
973 None
974}
975
976fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
977 let bytes = line.as_bytes();
978 let mut i = heredoc_pos + 2;
979 if i < bytes.len() && bytes[i] == b'-' {
980 i += 1;
981 }
982 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
983 i += 1;
984 }
985 let Some((_, _, next)) = crate::core::shell_allowlist::read_heredoc_delim(bytes, i) else {
986 return true;
987 };
988 !line[next..].trim().is_empty()
989}
990
991fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
992 let tokens = crate::core::shell_allowlist::shell_tokenize(prelude.trim());
993 let mut idx = 0;
994 while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
995 idx += 1;
996 }
997 if idx >= tokens.len() {
998 return None;
999 }
1000 let base = tokens[idx]
1001 .rsplit('/')
1002 .next()
1003 .unwrap_or(tokens[idx].as_str());
1004 let language = interpreter_to_execute_language(base)?;
1005 idx += 1;
1006 match tokens.get(idx) {
1007 None => Some(language),
1008 Some(dash) if dash == "-" => {
1009 if tokens.len() == idx + 1 {
1010 Some(language)
1011 } else {
1012 None
1013 }
1014 }
1015 Some(_) => None,
1016 }
1017}
1018
1019fn handle_interpreter_heredoc_reroute(
1020 args: &Map<String, Value>,
1021 ctx: &ToolContext,
1022 language: &str,
1023 code: &str,
1024 remainder: Option<String>,
1025) -> Result<ToolOutput, ErrorData> {
1026 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1027 let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1028
1029 let (exec_text, exec_outcome) =
1030 crate::tools::ctx_execute::handle(language, code, None, timeout_secs);
1031 let reroute_note = format!(
1032 "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1033 );
1034 let exec_text = crate::core::redaction::redact_text_if_enabled(&exec_text);
1035
1036 let Some(rest_cmd) = remainder else {
1037 return Ok(ToolOutput {
1038 text: format!("{exec_text}{reroute_note}"),
1039 original_tokens: crate::core::tokens::count_tokens(&exec_text),
1040 saved_tokens: 0,
1041 mode: Some("heredoc-reroute".to_string()),
1042 path: None,
1043 changed: false,
1044 shell_outcome: Some(exec_outcome),
1045 content_blocks: None,
1046 });
1047 };
1048
1049 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&rest_cmd) {
1050 let blocked =
1051 format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1052 return Ok(ToolOutput {
1053 shell_outcome: Some(ShellOutcome::Blocked),
1054 content_blocks: None,
1055 ..ToolOutput::simple(blocked)
1056 });
1057 }
1058
1059 let session_lock = ctx
1060 .session
1061 .as_ref()
1062 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1063 let explicit_cwd = get_str(args, "cwd");
1064 let guard =
1065 crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1066 let (effective_cwd, _) = resolve_effective_cwd(guard, explicit_cwd.as_deref())?;
1067
1068 let extra_env: std::collections::HashMap<String, String> = args
1069 .get("env")
1070 .and_then(|v| v.as_object())
1071 .map(|obj| {
1072 obj.iter()
1073 .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
1074 .filter(|(k, _)| !is_dangerous_env_key(k))
1075 .collect()
1076 })
1077 .unwrap_or_default();
1078
1079 let (shell_raw, shell_exit) = crate::server::execute::execute_command_with_env(
1080 &rest_cmd,
1081 &effective_cwd,
1082 &extra_env,
1083 timeout_ms,
1084 );
1085 let shell_output = redact_shell_output_secrets(&shell_raw);
1086 let arg_raw = get_bool(args, "raw").unwrap_or(false);
1087 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1088 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1089 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1090 let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1091
1092 let shell_text = if raw {
1093 shell_output
1094 } else {
1095 crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1096 };
1097 let shell_text = crate::core::redaction::redact_text_if_enabled(&shell_text);
1098 let exit_suffix = match shell_exit {
1099 0 => String::new(),
1100 124 => "\n[exit:124 — command timed out]".to_string(),
1101 _ => format!("\n[exit:{shell_exit}]"),
1102 };
1103
1104 let combined = format!(
1105 "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1106 );
1107 let token_count = crate::core::tokens::count_tokens(&combined);
1108 Ok(ToolOutput {
1109 text: combined,
1110 original_tokens: token_count,
1111 saved_tokens: 0,
1112 mode: Some("heredoc-reroute".to_string()),
1113 path: None,
1114 changed: false,
1115 shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1116 content_blocks: None,
1117 })
1118}
1119
1120fn detect_bare_cat_file(command: &str) -> Option<String> {
1122 let trimmed = command.trim();
1123 let rest = trimmed.strip_prefix("cat ")?;
1124 let rest = rest.trim();
1125 if rest.is_empty()
1126 || rest.contains('|')
1127 || rest.contains('>')
1128 || rest.contains('<')
1129 || rest.contains(';')
1130 || rest.contains('&')
1131 || rest.contains('$')
1132 || rest.starts_with('-')
1133 {
1134 return None;
1135 }
1136 let parts: Vec<&str> = rest.split_whitespace().collect();
1137 if parts.len() != 1 {
1138 return None;
1139 }
1140 let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1141 if file_path.is_empty() {
1142 return None;
1143 }
1144 Some(file_path.to_string())
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149 use super::{
1150 CtxShellTool, detect_heredoc_reroute, format_background_state, is_timeout_notice_only,
1151 resolve_effective_cwd, shell_access_denial, should_auto_background,
1152 };
1153 use crate::server::background_shell::JobState;
1154 use crate::server::tool_trait::{
1155 BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext,
1156 };
1157
1158 fn background(outcome: ShellOutcome) -> BackgroundShellOutcome {
1159 let ShellOutcome::Background(outcome) = outcome else {
1160 panic!("expected a background outcome");
1161 };
1162 outcome
1163 }
1164
1165 #[test]
1168 fn cancel_is_acknowledged_and_never_reports_a_failure() {
1169 let running = JobState::Running {
1170 output: String::new(),
1171 };
1172 let (text, outcome) = format_background_state("shell_x", true, Some(running.clone()));
1173 let outcome = background(outcome);
1174 assert!(!outcome.is_error);
1175 assert_eq!(outcome.state, BackgroundJobState::Running);
1176 assert_eq!(outcome.exit_code, None);
1177 assert!(text.is_empty());
1178 assert!(
1179 outcome
1180 .display
1181 .as_ref()
1182 .is_some_and(|display| display.header.contains("cancel requested"))
1183 );
1184
1185 let (text, outcome) = format_background_state("shell_x", false, Some(running));
1187 let outcome = background(outcome);
1188 assert!(!outcome.is_error);
1189 assert_eq!(outcome.state, BackgroundJobState::Running);
1190 assert!(text.is_empty());
1191 assert!(
1192 outcome
1193 .display
1194 .as_ref()
1195 .is_some_and(|display| display.header == "[background:shell_x running]")
1196 );
1197
1198 let (text, outcome) = format_background_state(
1201 "shell_x",
1202 true,
1203 Some(JobState::Cancelled {
1204 output: "[cancelled: command stopped on request]".to_string(),
1205 }),
1206 );
1207 let outcome = background(outcome);
1208 assert!(!outcome.is_error);
1209 assert_eq!(outcome.state, BackgroundJobState::Cancelled);
1210 assert_eq!(outcome.exit_code, Some(130));
1211 assert!(text.contains("[cancelled: command stopped on request]"));
1212 assert!(
1213 outcome
1214 .display
1215 .as_ref()
1216 .and_then(|display| display.footer.as_deref())
1217 .is_some_and(|footer| footer == "[cancelled: shell_x, exit 130]")
1218 );
1219
1220 let finished = JobState::Completed {
1222 output: "boom".to_string(),
1223 exit_code: 1,
1224 };
1225 let cancelled_finished =
1226 background(format_background_state("shell_x", true, Some(finished.clone())).1);
1227 assert!(!cancelled_finished.is_error);
1228 assert_eq!(cancelled_finished.state, BackgroundJobState::Failed);
1229 assert_eq!(cancelled_finished.exit_code, Some(1));
1230
1231 let polled_finished =
1232 background(format_background_state("shell_x", false, Some(finished)).1);
1233 assert!(polled_finished.is_error);
1234 assert_eq!(polled_finished.state, BackgroundJobState::Failed);
1235 assert_eq!(polled_finished.exit_code, Some(1));
1236
1237 let missing_cancel = format_background_state("shell_x", true, None).1;
1238 assert!(!missing_cancel.is_error());
1239 assert_eq!(missing_cancel, ShellOutcome::Exit(0));
1240
1241 let missing_status = format_background_state("shell_x", false, None).1;
1242 assert!(missing_status.is_error());
1243 assert!(matches!(
1244 missing_status,
1245 ShellOutcome::BackgroundLookupError(_)
1246 ));
1247 }
1248
1249 #[test]
1250 fn long_cargo_test_is_auto_backgrounded() {
1251 assert!(should_auto_background(
1252 "cargo test --lib a\ncargo test --lib b",
1253 Some(3_600_000)
1254 ));
1255 assert!(should_auto_background("cargo test --lib a", Some(300_000)));
1256 assert!(!should_auto_background("cargo test --lib a", Some(299_999)));
1257 }
1258
1259 #[test]
1260 fn timeout_notice_without_child_output_is_not_recoverable() {
1261 assert!(is_timeout_notice_only(
1262 "ERROR: command timed out after 200ms",
1263 124
1264 ));
1265 assert!(is_timeout_notice_only(
1266 " ERROR: command timed out after 200ms\n",
1267 124
1268 ));
1269 assert!(!is_timeout_notice_only(
1270 "useful output\nERROR: command timed out after 200ms",
1271 124
1272 ));
1273 assert!(!is_timeout_notice_only(
1274 "ERROR: command timed out after 200ms",
1275 1
1276 ));
1277 assert!(is_timeout_notice_only(
1281 "ERROR: command timed out after 200ms without new output\n\
1282 [still running at timeout: sleep 300]",
1283 124
1284 ));
1285 assert!(!is_timeout_notice_only(
1286 "useful output\nERROR: command timed out after 200ms\n\
1287 [still running at timeout: sleep 300]",
1288 124
1289 ));
1290 assert!(!is_timeout_notice_only("some tool output", 124));
1292 }
1293
1294 #[test]
1295 fn unavailable_session_lock_rejects_explicit_cwd() {
1296 let error = resolve_effective_cwd(None, Some("/tmp/unvalidated"))
1297 .expect_err("an unavailable session lock must reject an unvalidated cwd");
1298 assert!(
1299 error.message.contains("cannot validate working directory"),
1300 "{error:?}"
1301 );
1302 }
1303
1304 #[test]
1305 fn untrusted_and_readonly_clients_cannot_run_shell_commands() {
1306 for role in ["untrusted", "readonly"] {
1307 let ctx = ToolContext {
1308 client_role: Some(role.to_string()),
1309 ..ToolContext::default()
1310 };
1311 let output = CtxShellTool
1312 .handle(&serde_json::Map::new(), &ctx)
1313 .expect("role denial must be a tool result");
1314
1315 assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
1316 assert!(
1317 output.text.contains("SHELL ACCESS DENIED"),
1318 "{role}: {}",
1319 output.text
1320 );
1321 assert!(output.text.contains(role), "{role}: {}", output.text);
1322 }
1323 }
1324
1325 #[test]
1326 fn absent_shell_context_preserves_default_access() {
1327 assert!(shell_access_denial(&ToolContext::default()).is_none());
1328 }
1329
1330 #[test]
1331 fn explicitly_disabled_shell_access_blocks_the_request() {
1332 let ctx = ToolContext {
1333 shell_access: Some(false),
1334 ..ToolContext::default()
1335 };
1336 let output = CtxShellTool
1337 .handle(&serde_json::Map::new(), &ctx)
1338 .expect("shell-access denial must be a tool result");
1339
1340 assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
1341 assert!(output.text.contains("shell_access=true"), "{}", output.text);
1342 }
1343
1344 #[test]
1345 fn detect_heredoc_reroute_python_quoted() {
1346 let cmd = "python3 - <<'PY'\nprint(1)\nPY";
1347 let (lang, code, rest) = detect_heredoc_reroute(cmd).expect("must detect python heredoc");
1348 assert_eq!(lang, "python");
1349 assert_eq!(code, "print(1)");
1350 assert!(rest.is_none());
1351 }
1352
1353 #[test]
1354 fn detect_heredoc_reroute_python_with_remainder() {
1355 let cmd = "python3 <<'PY'\nprint(1)\nPY\nnode --test file.js";
1356 let (lang, code, rest) = detect_heredoc_reroute(cmd).expect("must detect split heredoc");
1357 assert_eq!(lang, "python");
1358 assert_eq!(code, "print(1)");
1359 assert_eq!(rest.as_deref(), Some("node --test file.js"));
1360 }
1361
1362 #[test]
1363 fn detect_heredoc_reroute_unquoted_and_tab_stripped() {
1364 let unquoted = "ruby <<EOF\nputs 1\nEOF";
1365 let (lang, code, rest) = detect_heredoc_reroute(unquoted).unwrap();
1366 assert_eq!(lang, "ruby");
1367 assert_eq!(code, "puts 1");
1368 assert!(rest.is_none());
1369
1370 let tabbed = "python3 <<-\tSCRIPT\n\tprint('ok')\nSCRIPT";
1371 let (lang, code, rest) = detect_heredoc_reroute(tabbed).unwrap();
1372 assert_eq!(lang, "python");
1373 assert_eq!(code, "\tprint('ok')");
1374 assert!(rest.is_none());
1375 }
1376
1377 #[test]
1378 fn detect_heredoc_reroute_rejects_compound_prefix() {
1379 assert!(detect_heredoc_reroute("echo hi; python3 <<'PY'\nx\nPY").is_none());
1380 assert!(detect_heredoc_reroute("python3 -c 'print(1)'").is_none());
1381 assert!(detect_heredoc_reroute("python3 <<'PY' | cat\nx\nPY").is_none());
1382 }
1383}