Skip to main content

lean_ctx_server/tools/registered/
ctx_execute.rs

1// SPDX-License-Identifier: Apache-2.0
2use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{
7    McpTool, ShellOutcome, ToolContext, ToolOutput, get_int, get_str, require_resolved_path,
8};
9use lean_ctx::tool_defs::tool_def;
10
11pub struct CtxExecuteTool;
12
13impl McpTool for CtxExecuteTool {
14    fn name(&self) -> &'static str {
15        "ctx_execute"
16    }
17
18    fn tool_def(&self) -> Tool {
19        tool_def(
20            "ctx_execute",
21            "Run code in sandbox (11 languages) โ€” use when conditionals, multi-line or cross-language transforms.\n\
22             ANTIPATTERN: for simple one-liners, prefer ctx_shell (lower overhead, auto-compressed).\n\
23             language=shell supports multi-line scripts but shares ctx_shell's security policy;\n\
24             other languages run only after the user approves them.\n\
25             action=code (default) for one-shot; action=batch for parallel multi-language;\n\
26             action=file to summarize admitted project text as data, without executing it.\n\
27             For code/batch, intent annotates large output; file records the intent alongside its preview. Languages: javascript,\n\
28             typescript, python, shell, ruby, go, rust, php, perl, r, elixir.",
29            json!({
30                "type": "object",
31                "properties": {
32                    "language": {
33                        "type": "string",
34                        "description": "javascript|typescript|python|shell|ruby|go|rust|php|perl|r|elixir (for action=code)"
35                    },
36                    "code": {
37                        "type": "string",
38                        "description": "Source code for action=code. Set intent to filter large output."
39                    },
40                    "intent": {
41                        "type": "string",
42                        "description": "Focus intent; triggers filtering when output is large."
43                    },
44                    "timeout": {
45                        "type": "integer",
46                        "description": "Timeout in seconds (default: 30)"
47                    },
48                    "action": {
49                        "type": "string",
50                        "description": "code (default, run script) | batch (parallel) | file (project file)"
51                    },
52                    "items": {
53                        "type": "string",
54                        "description": "JSON array of [{language, code}] for batch action."
55                    },
56                    "path": {
57                        "type": "string",
58                        "description": "Project text file for action=file; content is inspected, never executed."
59                    }
60                },
61                "oneOf": [
62                    {
63                        "properties": { "action": { "enum": ["code"] } },
64                        "required": ["language", "code"]
65                    },
66                    {
67                        "properties": { "action": { "const": "batch" } },
68                        "required": ["action", "items"]
69                    },
70                    {
71                        "properties": { "action": { "const": "file" } },
72                        "required": ["action", "path"]
73                    }
74                ]
75            }),
76        )
77    }
78
79    fn handle(
80        &self,
81        args: &Map<String, Value>,
82        ctx: &ToolContext,
83    ) -> Result<ToolOutput, ErrorData> {
84        let action = get_str(args, "action").unwrap_or_default();
85
86        // action=file inspects text and never executes it; code and batch run
87        // code, so restricted clients are refused like ctx_shell refuses them.
88        if action != "file"
89            && let Some(message) = super::ctx_shell::shell_access_denial(ctx)
90        {
91            return Ok(ToolOutput {
92                shell_outcome: Some(crate::server::tool_trait::ShellOutcome::Blocked),
93                content_blocks: None,
94                ..ToolOutput::simple(message)
95            });
96        }
97        let (result, outcome) = if action == "batch" {
98            let items_str = get_str(args, "items")
99                .ok_or_else(|| ErrorData::invalid_params("items is required for batch", None))?;
100            let items: Vec<serde_json::Value> = serde_json::from_str(&items_str)
101                .map_err(|e| ErrorData::invalid_params(format!("Invalid items JSON: {e}"), None))?;
102            let batch: Vec<(String, String)> = items
103                .iter()
104                .filter_map(|item| {
105                    let lang = item.get("language")?.as_str()?.to_string();
106                    let code = item.get("code")?.as_str()?.to_string();
107                    Some((lang, code))
108                })
109                .collect();
110            match admit_code(ctx, &batch) {
111                Ok(()) => {
112                    crate::tools::ctx_execute::handle_batch_in(&batch, rights_cwd(ctx).as_deref())
113                }
114                Err(refusal) => (refusal.into_message(), ShellOutcome::Blocked),
115            }
116        } else if action == "file" {
117            let path = require_resolved_path(ctx, args, "path")?;
118            let project_root = if ctx.project_root.is_empty() {
119                None
120            } else {
121                Some(ctx.project_root.as_str())
122            };
123            let intent = get_str(args, "intent");
124            crate::tools::ctx_execute::handle_file(&path, intent.as_deref(), project_root)
125        } else {
126            let language = get_str(args, "language")
127                .ok_or_else(|| ErrorData::invalid_params("language is required", None))?;
128            let code = get_str(args, "code")
129                .ok_or_else(|| ErrorData::invalid_params("code is required", None))?;
130            let intent = get_str(args, "intent");
131            let timeout = get_int(args, "timeout").and_then(|t| u64::try_from(t).ok());
132            match admit_code(ctx, &[(language.as_str(), code.as_str())]) {
133                Ok(()) => crate::tools::ctx_execute::handle_in(
134                    &language,
135                    &code,
136                    intent.as_deref(),
137                    timeout,
138                    rights_cwd(ctx).as_deref(),
139                ),
140                Err(refusal) => (refusal.into_message(), ShellOutcome::Blocked),
141            }
142        };
143
144        let result = lean_ctx::core::redaction::redact_text_if_enabled(&result);
145        Ok(ToolOutput {
146            text: result,
147            original_tokens: 0,
148            saved_tokens: 0,
149            mode: Some(action),
150            path: None,
151            changed: false,
152            shell_outcome: Some(outcome),
153            content_blocks: None,
154        })
155    }
156
157    /// `action=file` reads exactly one source, through the admitted rooted
158    /// reader on the handler thread (`tools::ctx_execute::handle_file_in_view`)
159    /// and derives its summary from that text alone. `code` and `batch` run
160    /// arbitrary programs whose reads nothing here observes: not declared.
161    fn publishes_every_source(&self, args: Option<&Map<String, Value>>) -> bool {
162        args.and_then(|args| args.get("action"))
163            .and_then(Value::as_str)
164            == Some("file")
165    }
166}
167
168/// Why [`admit_code`] refused code before anything ran.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub(crate) enum CodeRefusal {
171    /// The session's rights profile refuses it.
172    Rights(String),
173    /// A language that needs the user's approval has none in this dispatch.
174    Unapproved(String),
175}
176
177impl CodeRefusal {
178    pub(crate) fn into_message(self) -> String {
179        match self {
180            Self::Rights(message) | Self::Unapproved(message) => message,
181        }
182    }
183}
184
185/// The gates `ctx_execute` code passes before anything runs: the session's
186/// rights for every item, then the user's approval of every language that
187/// needs one (GHSA-rxv5-4c3x-g4q6). Every path that runs code through
188/// `tools::ctx_execute` โ€” this tool's code and batch actions and the
189/// interpreter heredoc `ctx_shell` reroutes here (GHSA-hqgc-cjh7-q3w4) โ€”
190/// goes through this one function, so the paths cannot drift apart.
191pub(crate) fn admit_code<S: AsRef<str>>(
192    ctx: &ToolContext,
193    items: &[(S, S)],
194) -> Result<(), CodeRefusal> {
195    items
196        .iter()
197        .try_for_each(|(language, code)| {
198            session_rights_check(ctx, language.as_ref(), code.as_ref())
199        })
200        .map_err(CodeRefusal::Rights)?;
201    crate::tools::ctx_execute::refuse_unapproved(
202        items.iter().map(|(language, _)| language.as_ref()),
203    )
204    .map_err(CodeRefusal::Unapproved)
205}
206
207/// The session's rights profile (process-v1 ยง9) for code this tool runs:
208/// shell code is analysed like a `ctx_shell` command line, other languages
209/// are refused under a profile.
210fn session_rights_check(ctx: &ToolContext, language: &str, code: &str) -> Result<(), String> {
211    lean_ctx::core::session_rights::current().check_code(language, code, &checked_cwd(ctx))
212}
213
214/// The directory the rights check judges relative paths against.
215fn checked_cwd(ctx: &ToolContext) -> std::path::PathBuf {
216    if ctx.project_root.is_empty() {
217        std::env::current_dir().unwrap_or_default()
218    } else {
219        std::path::PathBuf::from(&ctx.project_root)
220    }
221}
222
223/// Under a profile the code runs where it was checked (the shared daemon's
224/// own directory is not the session's); without one, as before.
225fn rights_cwd(ctx: &ToolContext) -> Option<std::path::PathBuf> {
226    lean_ctx::core::session_rights::current()
227        .is_active()
228        .then(|| checked_cwd(ctx))
229}
230
231#[cfg(test)]
232pub(crate) mod session_rights_fixture {
233    //! A Developer rights file over a temporary worktree whose
234    //! `tests/locked_test.rs` is locked (spec_commit set).
235
236    pub(crate) struct Fixture {
237        pub _dir: tempfile::TempDir,
238        pub worktree: std::path::PathBuf,
239        pub rights: std::path::PathBuf,
240    }
241
242    pub(crate) fn developer(denied_tools: &[&str]) -> Fixture {
243        let dir = tempfile::tempdir().expect("tempdir");
244        let worktree = dir.path().join("wt");
245        std::fs::create_dir_all(worktree.join("tests")).expect("tests dir");
246        std::fs::create_dir_all(worktree.join("specs/42")).expect("spec dir");
247        std::fs::write(worktree.join("tests/locked_test.rs"), "#[test] fn t() {}\n").expect("test");
248        let list = serde_json::json!({
249            "schema": "leanctx.cloud.process.feature-list/v1", "process": "1.0",
250            "task": {"vault": "#acme/payments", "number": 42},
251            "spec_commit": "1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d",
252            "test_command": "cargo test",
253            "locked_paths": ["tests/locked_test.rs", "specs/42/features.json"],
254            "features": [{"id": "F1", "description": "d", "steps": ["s"],
255                          "tests": ["tests/locked_test.rs::t"], "passes": false}]
256        });
257        std::fs::write(worktree.join("specs/42/features.json"), list.to_string()).expect("list");
258        let record = serde_json::json!({
259            "schema": "leanctx.session-rights/v1", "process": "1.0",
260            "profile": {"id": "developer", "name": "Developer", "stages": ["build"],
261                        "delivers": "commits in its own worktree", "read": ["repo", "vault"],
262                        "write": ["own_worktree"], "deny_write": ["locked", "spec", "tests"],
263                        "may_stop": false, "availability": "now"},
264            "bindings": {"own_worktree": [worktree.to_string_lossy()]},
265            "feature_list": "specs/42/features.json",
266            "denied_tools": denied_tools,
267        });
268        let rights = dir.path().join("rights.json");
269        std::fs::write(&rights, record.to_string()).expect("rights");
270        #[cfg(unix)]
271        {
272            use std::os::unix::fs::PermissionsExt;
273            std::fs::set_permissions(&rights, std::fs::Permissions::from_mode(0o600))
274                .expect("0600");
275        }
276        Fixture {
277            _dir: dir,
278            worktree,
279            rights,
280        }
281    }
282
283    impl Fixture {
284        pub(crate) fn state(&self) -> lean_ctx::core::session_rights::State {
285            let state =
286                lean_ctx::core::session_rights::from_file_arg(Some(&self.rights.to_string_lossy()));
287            assert!(state.is_active(), "{state:?}");
288            state
289        }
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use crate::server::tool_trait::ShellOutcome;
297
298    /// F4: ctx_execute runs code under the session rights: shell code that
299    /// writes a locked test and code in another language are refused before
300    /// anything runs.
301    #[test]
302    fn session_rights_ctx_execute_refuses_locked_writes_and_other_languages() {
303        let fx = super::session_rights_fixture::developer(&[]);
304        let ctx = ToolContext {
305            project_root: fx.worktree.to_string_lossy().into_owned(),
306            ..ToolContext::default()
307        };
308        lean_ctx::core::session_rights::sync_scope(fx.state(), || {
309            for (language, code) in [
310                ("shell", "echo x > tests/locked_test.rs"),
311                ("bash", "bash -c 'echo x > tests/locked_test.rs'"),
312                ("python", "open('tests/locked_test.rs','w').write('x')"),
313            ] {
314                let output = CtxExecuteTool
315                    .handle(&args(&[("language", language), ("code", code)]), &ctx)
316                    .expect("answer");
317                assert_eq!(
318                    output.shell_outcome,
319                    Some(ShellOutcome::Blocked),
320                    "{language}"
321                );
322                assert!(output.text.contains("rule "), "{language}: {}", output.text);
323            }
324            let batch = args(&[
325                ("action", "batch"),
326                (
327                    "items",
328                    r#"[{"language":"shell","code":"echo x >> tests/locked_test.rs"}]"#,
329                ),
330            ]);
331            let output = CtxExecuteTool.handle(&batch, &ctx).expect("answer");
332            assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
333            assert!(session_rights_check(&ctx, "shell", "echo ok > notes.txt").is_ok());
334            // R2-4: the code runs in the directory it was checked against,
335            // not in the server's own working directory.
336            let output = CtxExecuteTool
337                .handle(
338                    &args(&[("language", "shell"), ("code", "echo ok > made_here.txt")]),
339                    &ctx,
340                )
341                .expect("answer");
342            assert_eq!(
343                output.shell_outcome,
344                Some(ShellOutcome::Exit(0)),
345                "{}",
346                output.text
347            );
348        });
349        assert!(
350            fx.worktree.join("made_here.txt").is_file(),
351            "the checked directory is where the code ran"
352        );
353        assert_eq!(
354            std::fs::read_to_string(fx.worktree.join("tests/locked_test.rs")).expect("read"),
355            "#[test] fn t() {}\n",
356            "the locked test is unchanged"
357        );
358    }
359
360    fn args(pairs: &[(&str, &str)]) -> Map<String, Value> {
361        pairs
362            .iter()
363            .map(|(k, v)| ((*k).to_string(), Value::String((*v).to_string())))
364            .collect()
365    }
366
367    /// GHSA-rxv5-4c3x-g4q6 B: clients that may not run ctx_shell may not run
368    /// code through ctx_execute either.
369    #[test]
370    fn restricted_clients_cannot_execute_code() {
371        let code = args(&[("language", "python"), ("code", "print(1)")]);
372        let batch = args(&[
373            ("action", "batch"),
374            ("items", r#"[{"language":"python","code":"print(1)"}]"#),
375        ]);
376        let contexts = [
377            ToolContext {
378                client_role: Some("untrusted".to_string()),
379                ..ToolContext::default()
380            },
381            ToolContext {
382                client_role: Some("readonly".to_string()),
383                ..ToolContext::default()
384            },
385            ToolContext {
386                shell_access: Some(false),
387                ..ToolContext::default()
388            },
389        ];
390        for ctx in &contexts {
391            for request in [&code, &batch] {
392                let output = CtxExecuteTool
393                    .handle(request, ctx)
394                    .expect("denial is a tool result");
395                assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
396                assert!(
397                    output.text.contains("SHELL ACCESS DENIED"),
398                    "{}",
399                    output.text
400                );
401            }
402        }
403    }
404}