Skip to main content

lean_ctx/tools/registered/
ctx_execute.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_int, get_str, require_resolved_path,
7};
8use crate::tool_defs::tool_def;
9
10pub struct CtxExecuteTool;
11
12impl McpTool for CtxExecuteTool {
13    fn name(&self) -> &'static str {
14        "ctx_execute"
15    }
16
17    fn tool_def(&self) -> Tool {
18        tool_def(
19            "ctx_execute",
20            "Run code in sandbox (11 languages) — use when conditionals, multi-line or cross-language transforms.\n\
21             ANTIPATTERN: for simple one-liners, prefer ctx_shell (lower overhead, auto-compressed).\n\
22             language=shell supports multi-line scripts but shares ctx_shell's security policy;\n\
23             other languages run only after the user approves them.\n\
24             action=code (default) for one-shot; action=batch for parallel multi-language;\n\
25             action=file to summarize admitted project text as data, without executing it.\n\
26             For code/batch, intent annotates large output; file records the intent alongside its preview. Languages: javascript,\n\
27             typescript, python, shell, ruby, go, rust, php, perl, r, elixir.",
28            json!({
29                "type": "object",
30                "properties": {
31                    "language": {
32                        "type": "string",
33                        "description": "javascript|typescript|python|shell|ruby|go|rust|php|perl|r|elixir (for action=code)"
34                    },
35                    "code": {
36                        "type": "string",
37                        "description": "Source code for action=code. Set intent to filter large output."
38                    },
39                    "intent": {
40                        "type": "string",
41                        "description": "Focus intent; triggers filtering when output is large."
42                    },
43                    "timeout": {
44                        "type": "integer",
45                        "description": "Timeout in seconds (default: 30)"
46                    },
47                    "action": {
48                        "type": "string",
49                        "description": "code (default, run script) | batch (parallel) | file (project file)"
50                    },
51                    "items": {
52                        "type": "string",
53                        "description": "JSON array of [{language, code}] for batch action."
54                    },
55                    "path": {
56                        "type": "string",
57                        "description": "Project text file for action=file; content is inspected, never executed."
58                    }
59                },
60                "oneOf": [
61                    {
62                        "properties": { "action": { "enum": ["code"] } },
63                        "required": ["language", "code"]
64                    },
65                    {
66                        "properties": { "action": { "const": "batch" } },
67                        "required": ["action", "items"]
68                    },
69                    {
70                        "properties": { "action": { "const": "file" } },
71                        "required": ["action", "path"]
72                    }
73                ]
74            }),
75        )
76    }
77
78    fn handle(
79        &self,
80        args: &Map<String, Value>,
81        ctx: &ToolContext,
82    ) -> Result<ToolOutput, ErrorData> {
83        let action = get_str(args, "action").unwrap_or_default();
84
85        // action=file inspects text and never executes it; code and batch run
86        // code, so restricted clients are refused like ctx_shell refuses them.
87        if action != "file"
88            && let Some(message) = super::ctx_shell::shell_access_denial(ctx)
89        {
90            return Ok(ToolOutput {
91                shell_outcome: Some(crate::server::tool_trait::ShellOutcome::Blocked),
92                content_blocks: None,
93                ..ToolOutput::simple(message)
94            });
95        }
96        let (result, outcome) = if action == "batch" {
97            let items_str = get_str(args, "items")
98                .ok_or_else(|| ErrorData::invalid_params("items is required for batch", None))?;
99            let items: Vec<serde_json::Value> = serde_json::from_str(&items_str)
100                .map_err(|e| ErrorData::invalid_params(format!("Invalid items JSON: {e}"), None))?;
101            let batch: Vec<(String, String)> = items
102                .iter()
103                .filter_map(|item| {
104                    let lang = item.get("language")?.as_str()?.to_string();
105                    let code = item.get("code")?.as_str()?.to_string();
106                    Some((lang, code))
107                })
108                .collect();
109            match crate::tools::ctx_execute::refuse_unapproved(
110                batch.iter().map(|(language, _)| language.as_str()),
111            ) {
112                Ok(()) => crate::tools::ctx_execute::handle_batch(&batch),
113                Err(message) => (message, ShellOutcome::Blocked),
114            }
115        } else if action == "file" {
116            let path = require_resolved_path(ctx, args, "path")?;
117            let project_root = if ctx.project_root.is_empty() {
118                None
119            } else {
120                Some(ctx.project_root.as_str())
121            };
122            let intent = get_str(args, "intent");
123            crate::tools::ctx_execute::handle_file(&path, intent.as_deref(), project_root)
124        } else {
125            let language = get_str(args, "language")
126                .ok_or_else(|| ErrorData::invalid_params("language is required", None))?;
127            let code = get_str(args, "code")
128                .ok_or_else(|| ErrorData::invalid_params("code is required", None))?;
129            let intent = get_str(args, "intent");
130            let timeout = get_int(args, "timeout").and_then(|t| u64::try_from(t).ok());
131            match crate::tools::ctx_execute::refuse_unapproved([language.as_str()]) {
132                Ok(()) => {
133                    crate::tools::ctx_execute::handle(&language, &code, intent.as_deref(), timeout)
134                }
135                Err(message) => (message, ShellOutcome::Blocked),
136            }
137        };
138
139        let result = crate::core::redaction::redact_text_if_enabled(&result);
140        Ok(ToolOutput {
141            text: result,
142            original_tokens: 0,
143            saved_tokens: 0,
144            mode: Some(action),
145            path: None,
146            changed: false,
147            shell_outcome: Some(outcome),
148            content_blocks: None,
149        })
150    }
151
152    /// `action=file` reads exactly one source, through the admitted rooted
153    /// reader on the handler thread (`tools::ctx_execute::handle_file_in_view`)
154    /// and derives its summary from that text alone. `code` and `batch` run
155    /// arbitrary programs whose reads nothing here observes: not declared.
156    fn publishes_every_source(&self, args: Option<&Map<String, Value>>) -> bool {
157        args.and_then(|args| args.get("action"))
158            .and_then(Value::as_str)
159            == Some("file")
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use crate::server::tool_trait::ShellOutcome;
167
168    fn args(pairs: &[(&str, &str)]) -> Map<String, Value> {
169        pairs
170            .iter()
171            .map(|(k, v)| ((*k).to_string(), Value::String((*v).to_string())))
172            .collect()
173    }
174
175    /// GHSA-rxv5-4c3x-g4q6 B: clients that may not run ctx_shell may not run
176    /// code through ctx_execute either.
177    #[test]
178    fn restricted_clients_cannot_execute_code() {
179        let code = args(&[("language", "python"), ("code", "print(1)")]);
180        let batch = args(&[
181            ("action", "batch"),
182            ("items", r#"[{"language":"python","code":"print(1)"}]"#),
183        ]);
184        let contexts = [
185            ToolContext {
186                client_role: Some("untrusted".to_string()),
187                ..ToolContext::default()
188            },
189            ToolContext {
190                client_role: Some("readonly".to_string()),
191                ..ToolContext::default()
192            },
193            ToolContext {
194                shell_access: Some(false),
195                ..ToolContext::default()
196            },
197        ];
198        for ctx in &contexts {
199            for request in [&code, &batch] {
200                let output = CtxExecuteTool
201                    .handle(request, ctx)
202                    .expect("denial is a tool result");
203                assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
204                assert!(
205                    output.text.contains("SHELL ACCESS DENIED"),
206                    "{}",
207                    output.text
208                );
209            }
210        }
211    }
212}