Skip to main content

lean_ctx/tools/
ctx_execute.rs

1use crate::core::sandbox::{self, SandboxResult};
2use crate::core::tokens::count_tokens;
3use crate::server::tool_trait::ShellOutcome;
4
5/// The grant key of an approval to run `language` code in `ctx_execute`. It
6/// cannot match a program a `ctx_shell` grant names (no `:` in those).
7pub(crate) fn approval_key(language: &str) -> String {
8    format!("ctx_execute:{language}")
9}
10
11/// The canonical languages among `languages` that run only with the user's
12/// approval (GHSA-rxv5-4c3x-g4q6): every runtime but shell, which follows the
13/// shell allowlist instead. None while `shell_security` is not `enforce`
14/// (nothing is refused then, as in `ctx_shell`) and none the user allowed
15/// for good in `execute_allowed_languages`. In first-seen order, deduplicated.
16pub(crate) fn languages_needing_approval<'a>(
17    languages: impl IntoIterator<Item = &'a str>,
18) -> Vec<&'static str> {
19    use crate::core::shell_allowlist::ShellSecurity;
20    if ShellSecurity::resolve() != ShellSecurity::Enforce {
21        return Vec::new();
22    }
23    let allowed = crate::core::config::Config::load().execute_allowed_languages;
24    let mut needed = Vec::new();
25    for language in languages {
26        let Some(canonical) = sandbox::canonical_language(language) else {
27            continue;
28        };
29        if canonical != "shell"
30            && !needed.contains(&canonical)
31            && !allowed
32                .iter()
33                .any(|a| sandbox::canonical_language(a) == Some(canonical))
34        {
35            needed.push(canonical);
36        }
37    }
38    needed
39}
40
41/// Refuses code in a language that needs approval and has none in this
42/// dispatch (`server::shell_approval`), before anything runs.
43pub(crate) fn refuse_unapproved<'a>(
44    languages: impl IntoIterator<Item = &'a str>,
45) -> Result<(), String> {
46    let grant = crate::server::shell_approval::current_grant();
47    let missing: Vec<&str> = languages_needing_approval(languages)
48        .into_iter()
49        .filter(|language| !grant.contains(&approval_key(language)))
50        .collect();
51    if missing.is_empty() {
52        return Ok(());
53    }
54    let list = missing.join(", ");
55    let entries = missing
56        .iter()
57        .map(|l| format!("\"{l}\""))
58        .collect::<Vec<_>>()
59        .join(", ");
60    Err(format!(
61        "[BLOCKED] ctx_execute runs {list} code only after the user approves it, and it was \
62         not approved (the client cannot show approval prompts, approval is off, or another \
63         prompt is open). Ask the user; they can allow it for good with \
64         execute_allowed_languages = [{entries}] in the global lean-ctx config."
65    ))
66}
67
68/// Executes a code snippet in a sandboxed environment.
69/// Returns the formatted output plus the structured outcome so the MCP layer
70/// can set `isError`/`structuredContent` on failures (GitHub #389).
71pub fn handle(
72    language: &str,
73    code: &str,
74    intent: Option<&str>,
75    timeout: Option<u64>,
76) -> (String, ShellOutcome) {
77    handle_in(language, code, intent, timeout, None)
78}
79
80/// Same as [`handle`], but runs the snippet in `cwd` (GH #1666).
81///
82/// `ctx_shell` reroutes an interpreter heredoc here and has already resolved a
83/// working directory for the rest of the same call; passing it on is what keeps
84/// both halves of that call in one directory.
85pub fn handle_in(
86    language: &str,
87    code: &str,
88    intent: Option<&str>,
89    timeout: Option<u64>,
90    cwd: Option<&std::path::Path>,
91) -> (String, ShellOutcome) {
92    let checked = if sandbox::is_shell_language(language) {
93        crate::core::shell_allowlist::check_shell_allowlist(code)
94    } else {
95        crate::core::shell_allowlist::refuse_redaction_marker(code)
96    };
97    if let Err(message) = checked {
98        return (message.to_string(), ShellOutcome::Blocked);
99    }
100    let result = sandbox::execute_in(language, code, timeout, cwd);
101    (
102        format_result(&result, intent),
103        ShellOutcome::Exit(result.exit_code),
104    )
105}
106
107/// Summarize admitted file content as data, without executing it or creating
108/// a plaintext temporary copy. Source rules run before statistics or previews.
109pub fn handle_file(
110    path: &str,
111    intent: Option<&str>,
112    project_root: Option<&str>,
113) -> (String, ShellOutcome) {
114    let root = match project_root {
115        Some(root) => std::path::PathBuf::from(root),
116        None => match std::env::current_dir() {
117            Ok(root) => root,
118            Err(_) => return ("Source project unavailable".into(), ShellOutcome::Blocked),
119        },
120    };
121    let result =
122        crate::core::policy::runtime::with_project_source_view(&root.to_string_lossy(), || {
123            handle_file_in_view(path, intent, &root)
124        });
125    match result {
126        Ok((text, outcome, authority)) => {
127            if let Some(authority) = authority {
128                authority.publish();
129            }
130            (text, outcome)
131        }
132        Err(_) => (
133            "File processing withheld: source authority changed or could not be verified.".into(),
134            ShellOutcome::Blocked,
135        ),
136    }
137}
138
139fn handle_file_in_view(
140    path: &str,
141    intent: Option<&str>,
142    root: &std::path::Path,
143) -> (
144    String,
145    ShellOutcome,
146    Option<crate::core::archive::authority::ArchiveAuthority>,
147) {
148    let mut remaining = crate::core::limits::max_read_bytes();
149    let read = match crate::tools::ctx_read::read_file_for_tool_rooted_with_path(
150        path,
151        &root.to_string_lossy(),
152        "ctx_execute",
153        &mut remaining,
154    ) {
155        Ok(content) => content,
156        Err(error) => {
157            return (
158                format!("File processing refused: {error}"),
159                ShellOutcome::Blocked,
160                None,
161            );
162        }
163    };
164    let authority = crate::core::archive::authority::ArchiveAuthority::file(
165        root,
166        &read.canonical_path,
167        "ctx_execute",
168        &read.content,
169    );
170    (
171        summarize_file_content(&read.content, intent),
172        ShellOutcome::Exit(0),
173        authority,
174    )
175}
176
177fn summarize_file_content(content: &str, intent: Option<&str>) -> String {
178    let lines = content.lines();
179    let count = lines.clone().count();
180    let mut output = format!(
181        "Admitted text: {count} lines, {} bytes, {} words (after decoding and filtering)\n",
182        content.len(),
183        content.split_whitespace().count(),
184    );
185    if let Some(intent) = intent {
186        output.push_str(&format!("Intent: {}\n", sanitize_intent(intent)));
187    }
188    // At most six lines of 1024 Unicode characters each; do not collect the
189    // entire source into a second line buffer just to produce a preview.
190    let append = |output: &mut String, line: &str| {
191        if let Some((end, _)) = line.char_indices().nth(1024) {
192            output.push_str(&line[..end]);
193            output.push_str(" [line truncated]");
194        } else {
195            output.push_str(line);
196        }
197        output.push('\n');
198    };
199    if count <= 6 {
200        for line in lines {
201            append(&mut output, line);
202        }
203    } else {
204        for line in lines.clone().take(3) {
205            append(&mut output, line);
206        }
207        output.push_str(&format!("... {} middle lines omitted ...\n", count - 6));
208        let tail: Vec<_> = lines.rev().take(3).collect();
209        for line in tail.into_iter().rev() {
210            append(&mut output, line);
211        }
212    }
213    output
214}
215
216/// Executes multiple (language, code) pairs in parallel and returns aggregated
217/// results. The outcome carries the first non-zero exit code (0 when all
218/// tasks succeeded), so one failing task marks the whole batch as failed.
219pub fn handle_batch(items: &[(String, String)]) -> (String, ShellOutcome) {
220    for (index, (language, code)) in items.iter().enumerate() {
221        let checked = if sandbox::is_shell_language(language) {
222            crate::core::shell_allowlist::check_shell_allowlist(code)
223        } else {
224            crate::core::shell_allowlist::refuse_redaction_marker(code)
225        };
226        if let Err(message) = checked {
227            return (
228                format!(
229                    "batch item {} blocked by shell policy:\n{message}",
230                    index + 1
231                ),
232                ShellOutcome::Blocked,
233            );
234        }
235    }
236    let results = sandbox::batch_execute(items);
237    let mut output = Vec::new();
238
239    for (i, result) in results.iter().enumerate() {
240        let label = format!("[{}/{}] {}", i + 1, results.len(), result.language);
241        if result.exit_code == 0 {
242            let stdout = result.stdout.trim();
243            if stdout.is_empty() {
244                output.push(format!("{label}: (no output) [{} ms]", result.duration_ms));
245            } else {
246                output.push(format!("{label}: {stdout} [{} ms]", result.duration_ms));
247            }
248        } else {
249            let stderr = result.stderr.trim();
250            output.push(format!(
251                "{label}: EXIT {} — {stderr} [{} ms]",
252                result.exit_code, result.duration_ms
253            ));
254        }
255    }
256
257    let total_ms: u64 = results.iter().map(|r| r.duration_ms).sum();
258    output.push(format!("\n{} tasks, {} ms total", results.len(), total_ms));
259    let first_failure = results
260        .iter()
261        .map(|r| r.exit_code)
262        .find(|c| *c != 0)
263        .unwrap_or(0);
264    (output.join("\n"), ShellOutcome::Exit(first_failure))
265}
266
267fn format_result(result: &SandboxResult, intent: Option<&str>) -> String {
268    let mut parts = Vec::new();
269
270    if result.exit_code == 0 {
271        let stdout = result.stdout.trim();
272        if stdout.is_empty() {
273            parts.push("(no output)".to_string());
274        } else {
275            let raw_tokens = count_tokens(stdout);
276            parts.push(stdout.to_string());
277
278            if let Some(intent_desc) = intent
279                && raw_tokens > 50
280            {
281                parts.push(format!("[intent: {intent_desc}]"));
282            }
283        }
284    } else {
285        if !result.stdout.is_empty() {
286            parts.push(result.stdout.trim().to_string());
287        }
288        parts.push(format!(
289            "EXIT {} — {}",
290            result.exit_code,
291            result.stderr.trim()
292        ));
293    }
294
295    parts.push(format!("[{} | {} ms]", result.language, result.duration_ms));
296    parts.join("\n")
297}
298
299fn sanitize_intent(raw: &str) -> String {
300    raw.chars()
301        .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_' || *c == '.')
302        .take(200)
303        .collect()
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn handle_simple_python() {
312        let _lock = crate::core::data_dir::test_env_lock();
313        let (result, outcome) = handle("python", "print(2 + 2)", None, None);
314        assert!(result.contains('4'));
315        assert!(result.contains("python"));
316        assert_eq!(outcome, ShellOutcome::Exit(0), "success must report exit 0");
317    }
318
319    #[test]
320    fn handle_with_intent() {
321        let _lock = crate::core::data_dir::test_env_lock();
322        let (result, _) = handle(
323            "python",
324            "print('found 5 errors')",
325            Some("count errors"),
326            None,
327        );
328        assert!(result.contains("found 5 errors"));
329    }
330
331    #[test]
332    fn handle_error_shows_stderr() {
333        let _lock = crate::core::data_dir::test_env_lock();
334        let (result, outcome) = handle("python", "raise Exception('boom')", None, None);
335        assert!(result.contains("EXIT"));
336        assert!(result.contains("boom"));
337        assert!(
338            outcome.is_error(),
339            "non-zero sandbox exit must surface as a tool error (#389)"
340        );
341    }
342
343    #[test]
344    #[serial_test::serial]
345    fn shell_execution_cannot_bypass_ctx_shell_allowlist() {
346        // Both guards are needed: `#[serial]` and `test_env_lock` are separate
347        // mutexes. The override below replaces the allowlist wholesale, which
348        // broke `gh391_strict_mode_blocks_substitution_in_args` — a test that
349        // serializes on the lock, not on `#[serial]`.
350        let _env_lock = crate::core::data_dir::test_env_lock();
351        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
352        let (result, outcome) = handle("shell", "definitely_not_allowed_command", None, None);
353        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
354        assert_eq!(outcome, ShellOutcome::Blocked);
355        assert!(
356            result.contains("shell allowlist"),
357            "unexpected result: {result}"
358        );
359    }
360
361    #[test]
362    #[serial_test::serial]
363    fn every_language_but_shell_needs_an_approval_under_enforce() {
364        let _data = crate::core::data_dir::isolated_data_dir();
365        crate::test_env::set_var("LEAN_CTX_SHELL_SECURITY", "enforce");
366        assert_eq!(
367            languages_needing_approval(["py", "bash", "PYTHON", "node", "sh", "shell", "cobol"]),
368            ["python", "javascript"]
369        );
370        let refused = refuse_unapproved(["ts"]).unwrap_err();
371        assert!(refused.contains("typescript code"), "{refused}");
372        assert!(refuse_unapproved(["shell", "bash"]).is_ok());
373
374        crate::test_env::set_var("LEAN_CTX_SHELL_SECURITY", "warn");
375        assert!(
376            languages_needing_approval(["python"]).is_empty(),
377            "nothing is refused outside enforce, as in ctx_shell"
378        );
379        crate::test_env::remove_var("LEAN_CTX_SHELL_SECURITY");
380    }
381
382    #[test]
383    #[serial_test::serial]
384    fn shell_batch_is_preflighted_before_any_item_runs() {
385        let _env_lock = crate::core::data_dir::test_env_lock();
386        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
387        let items = vec![
388            ("shell".to_string(), "echo safe".to_string()),
389            (
390                "shell".to_string(),
391                "definitely_not_allowed_command".to_string(),
392            ),
393        ];
394        let (result, outcome) = handle_batch(&items);
395        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
396        assert_eq!(outcome, ShellOutcome::Blocked);
397        assert!(result.contains("batch item 2 blocked"));
398    }
399
400    /// GHSA-rxv5-4c3x-g4q6 B: `bash`/`sh` (any case) resolve to the same shell
401    /// runtime as `shell` and must not skip the allowlist preflight.
402    #[test]
403    #[serial_test::serial]
404    fn shell_aliases_cannot_bypass_ctx_shell_allowlist() {
405        let _env_lock = crate::core::data_dir::test_env_lock();
406        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
407        let single: Vec<_> = ["bash", "sh", "BASH", "Sh", "SHELL"]
408            .iter()
409            .map(|lang| {
410                (
411                    *lang,
412                    handle(lang, "definitely_not_allowed_command", None, None),
413                )
414            })
415            .collect();
416        let batch = handle_batch(&[(
417            "bash".to_string(),
418            "definitely_not_allowed_command".to_string(),
419        )]);
420        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
421        for (lang, (result, outcome)) in single {
422            assert_eq!(outcome, ShellOutcome::Blocked, "{lang}: {result}");
423            assert!(result.contains("shell allowlist"), "{lang}: {result}");
424        }
425        assert_eq!(batch.1, ShellOutcome::Blocked, "{}", batch.0);
426    }
427
428    #[test]
429    #[cfg(not(target_os = "windows"))]
430    fn batch_multiple_tasks() {
431        let _lock = crate::core::data_dir::test_env_lock();
432        let items = vec![
433            ("python".to_string(), "print('task1')".to_string()),
434            ("shell".to_string(), "echo task2".to_string()),
435        ];
436        let (result, outcome) = handle_batch(&items);
437        assert!(result.contains("task1"));
438        assert!(result.contains("task2"));
439        assert!(result.contains("2 tasks"));
440        assert_eq!(outcome, ShellOutcome::Exit(0), "all tasks succeeded");
441    }
442
443    #[test]
444    #[cfg(not(target_os = "windows"))]
445    fn batch_with_failing_task_reports_failure() {
446        let _lock = crate::core::data_dir::test_env_lock();
447        let items = vec![
448            ("python".to_string(), "print('ok')".to_string()),
449            ("python".to_string(), "raise SystemExit(3)".to_string()),
450        ];
451        let (_, outcome) = handle_batch(&items);
452        assert_eq!(
453            outcome,
454            ShellOutcome::Exit(3),
455            "one failing task marks the whole batch as failed (#389)"
456        );
457    }
458
459    #[test]
460    fn handle_file_precondition_failure_is_blocked() {
461        let (result, outcome) = handle_file("/nonexistent/definitely-missing.py", None, None);
462        assert!(outcome.is_error(), "precondition failures are tool errors");
463        assert_eq!(outcome, ShellOutcome::Blocked, "nothing was executed");
464        assert!(!result.is_empty(), "`result` is empty");
465    }
466}
467
468#[cfg(test)]
469#[path = "ctx_execute_file_tests.rs"]
470mod file_tests;